如何在ggplot2中重新排序图例? [英] How to reorder a legend in ggplot2?

查看:461
本文介绍了如何在ggplot2中重新排序图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个包含标签分类列和数据百分比定量列的两列数据框,我可以可靠地在ggplot中生成一个条形图,该条形图可以按照以下值按值排序,而不是按字母顺序排序:

  ggplot(data = df,aes(x = reorder(Label,Percent),y = Percent,fill = Label))+ geom_bar )

这将告诉重新排序按百分比而不是文本对条形图进行排序,使其更容易看到变化。

但是,我不能让图例匹配:相反,它仍然按照原始字母值排序。这会导致与图表不匹配的图例,这是令人困惑的。

我查看了StackOverflow和其他地方,并且没有找到可以工作的修复程序。任何意见?

编辑:每个请求,这基本上是数据:

 标签<-c(G,G,A,C,M,B,M,G,A,M)
Percent <-c( - 0.241, - 0.046,-0.037,-0.024,-0.003,0.007,0.01,0.059,0.121 0.152)


解决方案

我发现最简单的方法是只需在绘图之前对您的数据进行重新排序即可。通过在 aes()中指定重新排序(()),您必须为绘图部分制作一个有序副本,但对于 ggplot 在内部很棘手,例如传递给图例。



这应该可以工作(b)

$ $ p $ df $标签< - with(df,reorder(Label,Percent))
ggplot( data = df,aes(x = Label,y = Percent,fill = Label))+ geom_bar()

我确实假设你的 Percent 列是数字,而不是因子或字符,这从你的问题中是不清楚的。将来,如果你发布了 dput(df)这些类将是明确的,并且允许用户将数据复制/粘贴到R中。


Given a two column data frame with a categorical column of labels and a quantitative column of percent data, I can reliably produce a bar chart in ggplot that sorts the bars by value rather than by alphabetical order using the following:

ggplot(data=df, aes(x=reorder(Label, Percent), y=Percent, fill=Label)) + geom_bar()

This tells reorder to sorts the bar chart by the percent value rather than the text, making it easier to see the changes.

I cannot, however, get the legend to match: instead it persists in being sorted by the original alphabetical values. This results in a legend which doesn't match the chart, which is confusing.

I've looked on StackOverflow and elsewhere, and haven't found a fix that will work. Any advice?

Edit: per requests, this is essentially the data:

Labels <- c("G", "G", "A", "C", "M", "B", "M", "G", "A","M")
Percent <- c("-0.241","-0.046", "-0.037", "-0.024", "-0.003","0.007","0.01","0.059","0.121", "0.152")

解决方案

I find the easiest way is to just reorder your data before plotting. By specifying the reorder(() inside aes(), you essentially making a ordered copy of it for the plotting parts, but it's tricky internally for ggplot to pass that around, e.g. to the legend making functions.

This should work just fine:

df$Label  <- with(df, reorder(Label, Percent))
ggplot(data=df, aes(x=Label, y=Percent, fill=Label)) + geom_bar()

I do assume your Percent column is numeric, not factor or character. This isn't clear from your question. In the future, if you post dput(df) the classes will be unambiguous, as well as allowing people to copy/paste your data into R.

这篇关于如何在ggplot2中重新排序图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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