0
votes

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!

2
First you have to create another table with counts, then plot them. Prepare count table for each party using table()Sowmya S. Manian

2 Answers

2
votes
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")

enter image description here

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")  

enter image description here

1
votes

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()

enter image description here