简体   繁体   中英

Order geom_bar y axis by percentage of one particular value in column (position = "fill")

how would I go about plotting this where the clusters are reordered in decreasing % 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(position = 'fill') + 
  theme_classic()+
  coord_flip() +
  scale_y_continuous(labels = scales::percent) + 
  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 percentage") +
  labs( fill = "")
p  

在此处输入图像描述

Adapting the elegeant solution by @RobertHacken on your former post, you could achieve your desired result using reorder by switching to the mean instead of using the sum and by adding decreasing=TRUE if you want to order in decreasing order:

library(ggplot2)

ggplot(df, aes(x = reorder(cluster, fruit == "kiwi", FUN = mean, decreasing = TRUE) , 
                   fill = fruit))+
  geom_bar(position = 'fill') + 
  theme_classic()+
  coord_flip() +
  scale_y_continuous(labels = scales::percent) + 
  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 percentage") +
  labs( fill = "")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM