I am very new to R and this may seem like an easy fix but I am having trouble trying to figure out how to do this. So the question in this survey is along the lines of "Do you use this site?" and respondents are asked to answer "yes" or "no".
Here's my data frame:
ic <- data.frame(items = c("item1", "item2", "item3", "item4", "item5",
"item6", "item7","item8", "item9", "item10",
"item11", "item12"),
yes = c("6", "6", "7", "4", "2", "6", "6", "8", "2",
"3", "7", "6"),
no = c("2", "2", "1", "4", "6", "2", "2", "0", "6", "5",
"1", "2"))
And this is what it looks like when I use the head(ic) function:
head(ic)
items yes no
1 item1 6 2
2 item2 6 2
3 item3 7 1
4 item4 4 4
5 item5 2 6
6 item6 6 2
I use this code to plot it:
ic %>%
gather(key = "success", value=value, -items) %>%
ggplot(aes(x=items, y=value, fill=success))
geom_bar(position = "stack", stat = "identity")
coord_flip()
labs(title = "Items People Use", x= "Items", y= "# of individuals")
scale_fill_brewer("legend", palette = "Spectral")
I technically didn't solve your problem of items sorting, but I always pad my numbers with relevant number of 0 so that I never have to waste my life with this kind of issues.
Hope it helps.
CodePudding user response:
a and b are happening because you set up your yes and no as characters. If you declare them to be numeric, it will order the "yes" and "no" correctly and stop at the beginning and end numbers. For c, to order, you can assign to be a factor and order the levels how you wish. In this case, as the levels are in ascending order, you can add forcats::fct_inorder and the factors will be in the order they are first encountered. Without coord_flip, you would see the items in ascending order. However, when you flip it will rotate counterclockwise. You can reverse that order with forcats::fct_rev. So, you can revise your data as:
ic <- data.frame(items = forcats::fct_rev(forcats::fct_inorder(c("item1", "item2", "item3", "item4", "item5",
"item6", "item7","item8", "item9", "item10",
"item11", "item12"))),
yes = as.numeric(c("6", "6", "7", "4", "2", "6", "6", "8", "2",
"3", "7", "6")),
no = as.numeric(c("2", "2", "1", "4", "6", "2", "2", "0", "6", "5",
"1", "2")))
and this will plot as you desire