ggplot2:更改图例中的因子顺序 [英] ggplot2: Change factor order in legend

查看:1844
本文介绍了ggplot2:更改图例中的因子顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个折线图,我想重新排列图例中因子的显示方式.我已经尝试过scale_fill_discrete,但是它不会改变顺序. 这是我的问题的模拟:

I have a a line graph and I want to reorder the way in which the factors appear in the legend. I have tried scale_fill_discrete but it doesn't change the order. Here's a simulation of my problem:

df <- data.frame(var1=c("F", "F", "F", "B", "B", "B"),
                 var2=c("levelB", "levelC", "levelA"),
                 value=c("2.487585", "2.535944", "3.444764", "2.917308", "2.954155","3.739049"))

p <- ggplot(data=df, aes(x=var1, y=value, 
  group=var2, colour=var2, shape = var2)) +
  geom_line(size = 0.8) +
  geom_point()+
  xlab("var1") + ylab("Value") +
  scale_x_discrete(limits=c("F","B")) + 
  theme(legend.title = element_text(size=12)) + 
  theme(legend.text = element_text(size=10)) +
  scale_fill_discrete(breaks=c("levelB","levelC","levelA")) +
  theme(title = element_text(size=12)) +
  blank + scale_color_manual(values=c("green2", "red", "black")) +
  theme(legend.key = element_blank())
p

哪个创建的:

除了图例,我希望所有内容都保持不变,在图例中,我想将顺序更改为levelB然后levelC然后levelA. 我猜想ggplot2按字母顺序排列图例,我想覆盖它. 重新排序数据框无效,scale_fill_discrete也不会更改它. 有任何想法吗?

I would like everything to remain the exactly the same, except for the legend, where I would like to change the order to levelB then levelC then levelA. I'm guessing ggplot2 orders the legend alphabetically and I would like to override this. Reordering my data frame didn't work, and scale_fill_discrete also doesn't change it. Any ideas?

谢谢!

推荐答案

通过在因子中重新排列级别,可以更改图例标签的顺序.运行:

By reordering the levels in your factor, you can change the order of the legend labels. Run:

df$var2 <- factor(df$var2, levels=c("levelB", "levelC", "levelA"))

然后重新运行ggplot代码,现在levelB应该位于图例的顶部,绿色,levelC第二和红色,levelA第三和黑色.

Then rerun the ggplot code, and levelB should now be at the top of the legend and green, levelC second and red, and levelA third and black.

这篇关于ggplot2:更改图例中的因子顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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