Reordering bars in ggplot2 bar graph using only one variable (w/o value or ranking)?

无人久伴 提交于 2020-01-06 06:03:52

问题


I'd like to ra-arrange the bars of my ggplot bar chart - and there is quite a number of similar entries here on stackoverflow (e.g. here).

However, the question I have is: can you do this with only one variable (the one used for the bar graph) by telling ggplot not to sort alphabetically by labels but sort by take the count of identical labels as the value of interest.

In my case, I have survey data on the question of which political party champions a certain issue/ is the most competent in a given issue area.

respondent-id    competence
1                "Party A"
2                "Party A"
3                "Party B"
4                "Party B"
5                "Party B"
6                "Party C"

What ggplot would do now is a bar chart with the 2nd-highest first (party A), highest second (party B) and lowest last (party C). But how do I tell ggplot to take the count into account (2:3:1 --> place party B first)?

I tried several ways as suggested here, but that didn't solve the problem: most of them included a position-variable which would tell ggplot "assign party B first place". I also tried to reorder() simply by "competence", with no success. Finally, I could assign different prefixes to the parties ("1_party_B", "2_...") but that would really tedious work.

ggplot(MyData, aes(x=competence,y=(..count..))) + geom_bar()

Also, I have a NA-bar in my bar chart, and MyData[,c("competence")] doesn't seem to do the trick. But that's another story.

Thanks in advance!


回答1:


library(ggplot2)

df
#   resp    comp
# 1    1 Party A
# 2    2 Party A
# 3    3 Party B
# 4    4 Party B
# 5    5 Party B
# 6    6 Party C

df1 <- data.frame(table(df$comp))
df1
#      Var1 Freq
# 1 Party A    2
# 2 Party B    3
# 3 Party C    1

Manually arranging levels using factor()

df1$Var1 <- factor(df1$Var1, c("Party B", "Party C", "Party A"))
df1
#      Var1 Freq
# 2 Party B    3
# 3 Party C    1
# 1 Party A    2


ggplot(df1, aes(x = Var1, y = Freq)) + geom_bar(stat = "identity")

Frequency of party in decreasing order

df1 <- data.frame(table(df$comp))
df1
#      Var1 Freq
# 1 Party A    2
# 2 Party B    3
# 3 Party C    1

df1 <- df1[order(df1$Freq, decreasing=TRUE),]
df1
#      Var1 Freq
# 2 Party B    3
# 1 Party A    2
# 3 Party C    1

ggplot(df1, aes(x = Var1, y = Freq)) + geom_bar(stat = "identity")  




回答2:


Depending on if you want a descending order, you can do this simply with dplyr and reorder.

library(dplyr)
library(ggplot2)

count(df, competence) %>% 
      ggplot(aes(x = reorder(competence, -n), y = n)) +
      geom_col()



来源:https://stackoverflow.com/questions/46865895/reordering-bars-in-ggplot2-bar-graph-using-only-one-variable-w-o-value-or-ranki

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!