2012-07-09 74 views
53

有没有人知道我可以如何控制ggplot2中的图例排序?控制ggplot2图例显示顺序

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

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 
+2

相关(尽管这个问题有一个更好的解决方案):http://stackoverflow.com/questions/10035551 /多重传奇 - 指南 - 什么是自动逻辑 - 如何改变 – 2012-07-09 16:12:53

回答

87

在0.9.1中,确定图例顺序的规则是秘密不可预知。 现在,在github的0.9.2版本中,您可以使用参数来设置图例的顺序。

这里是例如:

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

enter image description here

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

enter image description here

12

在我看来,图例的顺序是由刻度名称中的字符数决定的。 (是的,我同意,这似乎离奇。)

所以,一个解决办法是垫您的标签用空格:

plot + labs(colour = "Clarity", shape = "  Cut") 

enter image description here


我真诚地希望有人张贴一个妥善的解决办法不久!

+0

我得到清晰,然后在我的传说中剪切(用空格填充),如果我做wha你做到了。 packageDescription(“ggplot2”)$ Version = 0.9.1 – Spacedman 2012-07-09 12:45:04

+0

我应该清楚说明我实际上需要颜色然后是形状(即清晰度然后切割),而不是切割然后是清晰度类似于您的示例。但是,我希望能够对任何尺寸进行命名并仍然具有该顺序。 – Alastair 2012-07-09 13:31:49

+4

@Alastair现在很清楚,我的解决方法只能在'ggplot2'版本0.9.0中使用 - 此解决方法不再适用于0.9.1版本。因此,如果您仍然使用0.9.0,则可以用空格填充字符串以获得所需的顺序。正如我所说,这只是一种解决方法(并且保质期有限)。 – Andrie 2012-07-09 13:37:31