ggplot barplot根据两个类别的行的最大值排序 [英] ggplot barplot order according to max value for a row of two categories

查看:525
本文介绍了ggplot barplot根据两个类别的行的最大值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了四周,发现



我希望n1的最小值决定躲闪条形图的顺序。



感谢您的帮助。

解决方案

您可以按 value 进行排序,然后设置名称名称的排序顺序 measure_type ==n1。这可以使用 dplyr 管道即时完成:

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


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:

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

Thanks for your help.

解决方案

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

这篇关于ggplot barplot根据两个类别的行的最大值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆