控制ggplot2图例显示顺序 [英] Controlling ggplot2 legend display order

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

问题描述



从我所看到的顺序看起来与实际尺度标签相关,而不是与实际尺寸标签相关比例声明顺序。更改比例标题会改变顺序。我用钻石数据集做了一个小例子来强调这一点。我正在尝试使用ggplot2进行一系列的绘图,并且我想让其中的一个变量出现在右侧。目前,虽然这只发生在其中的一些,并且我在如何执行我想要的订购时仍然感到茫然,同时保留适当的比例标签。

  library(ggplot2)
diamond.data < - diamonds [sample(nrow(diamonds),1000), ]
plot < - ggplot(diamond.data,aes(carat,price,color = clarity,shape = cut))+
geom_point()+ opts(legend.position =top,legend .box =horizo​​ntal)
plot#图例会出现形状然后颜色
plot + labs(color =A,shape =B)# b plot + labs(color =Clarity,shape =Cut)#图例将被变形然后颜色


秘密和不可预知
现在,在github的0.9.2版本中,您可以使用参数设置图例的顺序。



下面是示例: p
$ b $ pre $ lt; code> plot< - ggplot(diamond.data,aes(carat,price,color = clarity,shape = cut))+
geom_point()+ opts(legend.position =top)

绘图+指南(color = guide_legend(order = 1),
shape = guide_legend(order = 2))


pre code $ plot $ + color = guide_legend(order = 2),
shape = guide_legend(order = 1))


Does anyone know how I can get control of the ordering of legends in ggplot2?

From what I can see the order appears related to the actual scale labels rather than the scale declaration order. Changing the scale titles alters the ordering. I've made a small example using the diamond dataset to highlight this. I'm trying to use ggplot2 for a series of plots and I want to make one variable appear on the right in them all. At present though this only happens in some of them, and I'm at a loss on how to enforce my desired ordering whilst retaining the appropriate scale labels.

library(ggplot2)
diamond.data <- diamonds[sample(nrow(diamonds), 1000), ]
plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) +
  geom_point() + opts(legend.position = "top", legend.box = "horizontal")
plot # the legend will appear shape then colour 
plot + labs(colour = "A", shape = "B") # legend will be colour then shape
plot + labs(colour = "Clarity", shape = "Cut") # legend will be shape then colour

解决方案

In 0.9.1, the rule for determining the order of the legends is secret and unpredictable. Now, in 0.9.2, dev version in github, you can use the parameter for setting the order of legend.

Here is the example:

plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) +
  geom_point() + opts(legend.position = "top")

plot + guides(colour = guide_legend(order = 1), 
              shape = guide_legend(order = 2))

plot + guides(colour = guide_legend(order = 2), 
              shape = guide_legend(order = 1))

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

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