Search code examples
rggplot2geom-bar

order y axis by count of one particular value in column with geom_bar


wondering how I can order the clusters on y-axis by decreasing count of kiwi?

df = data.frame()
df = data.frame(matrix(df, nrow=200, ncol=2))
colnames(df) <- c("cluster", "name")
df$cluster <- sample(20, size = nrow(df), replace = TRUE)
df$fruit <- sample(c("banana", "apple", "orange", "kiwi", "plum"), size = nrow(df), replace = TRUE)

p = ggplot(df, aes(x = as.factor(cluster), fill = as.factor(fruit)))+
  geom_bar(stat = 'count') + 
  theme_classic()+
  coord_flip() +
  theme(axis.text.y = element_text(size = 20),
        axis.title.x = element_text(size = 20),
        axis.title.y = element_text(size = 20),
        axis.text=element_text(size=20)) +
  theme(legend.text = element_text(size = 20)) +
  xlab("Cluster")+
  ylab("Fruit count") +
  labs( fill = "")
p

enter image description here


Solution

  • No need to modify the data, just use x = reorder(cluster, fruit=='kiwi', sum) in aes() (instead of as.factor(cluster)).

    Barplot sorted according to kiwi

    ggplot(df, aes(x = reorder(cluster, fruit=='kiwi', sum), 
                   fill = as.factor(fruit))) +
      geom_bar(stat = 'count') + 
      theme_classic() +
      coord_flip() +
      theme(axis.text.y = element_text(size = 20),
            axis.title.x = element_text(size = 20),
            axis.title.y = element_text(size = 20),
            axis.text=element_text(size=20)) +
      theme(legend.text = element_text(size = 20)) +
      xlab('Cluster') +
      ylab('Fruit count') +
      labs(fill = '')