ggplot barplot order according to max value for a

2019-05-19 21:42发布

I have searched around and found cases similar to mine, but I cannot find a working solution to the following.

I have a dataframe like this one:

df <- data.frame(name = rep(c("a","b","c"), each=2), measure_type = rep(c("n1","n2"),3), value=c(20,1,3,3,17,9))


> df
    name measure_type value
  1    a           n1    20
  2    a           n2     1
  3    b           n1     3
  4    b           n2     3
  5    c           n1    17
  6    c           n2     9

I want to create a dodged bar plot with ggplot. X-axis should be name, y-axis should be value, fill=measure_type and the dodged bars sorted according the highest value for measure_type=n1. The last feature (bold font) is what I am struggling with. I simply do not know how to produce it.

My code so far:

plot <- ggplot(df, aes(x = name, y = value, fill = measure_type)) + geom_bar(stat = "identity", position=position_dodge())

Produces:

enter image description here

I want the smallest value of n1 determine the order of the dodged bar plots.

Thanks for your help.

1条回答
孤傲高冷的网名
2楼-- · 2019-05-19 22:30

You can sort by value and then set the order of name to the sorted order of name for measure_type=="n1". This can all be done on the fly using the dplyr pipe:

library(dplyr)

ggplot(df %>% arrange(value) %>% 
         mutate(name=factor(name, levels=name[measure_type=="n1"])), 
       aes(x = name, y = value, fill = measure_type)) + 
  geom_bar(stat = "identity", position=position_dodge())

enter image description here

查看更多
登录 后发表回答