ggplot 条形图,具有依赖于方面的类别顺序 [英] ggplot bar plot with facet-dependent order of categories

查看:42
本文介绍了ggplot 条形图,具有依赖于方面的类别顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多问题(通常链接到 ggplot2 条形图中的订单条) 关于如何在条形图中(重新)排序类别.

I've seen many questions (often linked to Order Bars in ggplot2 bar graph) about how to (re)order categories in a bar plot.

我所追求的只是一点点不同,但我还没有找到一个好的方法:我有一个多面的条形图,我想独立地为每个面排序 x 轴,根据另一个变量(在我的情况下,该变量只是 y 值本身,即我只希望条形在每个方面的长度增加).

What I am after is just a touch different, but I haven't found a good way to do it: I have a multi-faceted bar plot, and I want to order the x axis for each facet independently, according to another variable (in my case, that variable is just the y value itself, i.e. I just want the bars to go in increasing length in each facet).

简单的例子,如下ggplot2 条形图中的订单条:

df <- data.frame(name=c('foo','bar','foo','bar'),period=c('old','old','recent','recent'),val=c(1.23,2.17,4.15,3.65))
p = ggplot(data = df, aes(x = reorder(name, val), y = val))
p = p + geom_bar(stat='identity')
p = p + facet_grid(~period)
p

我们得到的是:

而我想要的是:

推荐答案

好吧,所有的哲学问题都放在一边,如果有人感兴趣,这里有一个丑陋的 hack 来做.这个想法是使用不同的标签(想想 paste(period, name) 除了我将句点替换为 0-space、1-space 等,以便它们不显示).我需要这个情节,我不想安排grobs之类的,因为我可能想分享一个共同的传说等等.

Ok, so all philosophizing aside, and in case anyone is interested, here is an ugly hack to do it. The idea is to use different labels (think paste(period, name) except I replace the period into 0-space, 1-space, etc. so that they don't show). I need this plot and I don't want to arrange grobs and the like, because I might want to share a common legend, etc.

之前给出的原子示例变为:

The atomic example given earlier becomes:

df <- data.frame(name=c('foo','bar','foo','bar'),
  period=c('old','old','recent','recent'),
  val=c(1.23,2.17,4.15,3.65),
  stringsAsFactors=F)
df$n = as.numeric(factor(df$period))
df = ddply(df,.(period,name),transform, x=paste(c(rep(' ',n-1), name), collapse=''))
df$x = factor(df$x, levels=df[order(df$val), 'x'])
p = ggplot(data = df, aes(x = x, y = val))
p = p + geom_bar(stat='identity')
p = p + facet_grid(~period, scale='free_x')
p

另一个例子,仍然有点傻,但更接近我的实际用例,是:

Another example, still a bit silly but closer to my actual use case, would be:

df <- ddply(mpg, .(year, manufacturer), summarize, mixmpg = mean(cty+hwy))
df$manufacturer = as.character(df$manufacturer)
df$n = as.numeric(factor(df$year))
df = ddply(df, .(year,manufacturer), transform,
     x=paste(c(rep(' ',n-1), manufacturer), collapse=''))
df$x = factor(df$x, levels=df[order(df$mixmpg), 'x'])
p = ggplot(data = df, aes(x = x, y = mixmpg))
p = p + geom_bar(stat='identity')
p = p + facet_grid(~year, scale='free_x')
p = p + theme(axis.text.x=element_text(angle=90,hjust=1,vjust=.5,colour='gray50'))
p

闭上眼睛,想想帝国,试着享受.

Close your eyes, think of the Empire, and try to enjoy.

这篇关于ggplot 条形图,具有依赖于方面的类别顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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