控制ggplot2图例显示顺序

Ala*_*air 68 r 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
Run Code Online (Sandbox Code Playgroud)

koh*_*ske 108

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

这是一个例子:

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

plot + guides(colour = guide_legend(order = 2), 
              shape = guide_legend(order = 1))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


And*_*rie 12

在我看来,图例的顺序由比例名称中的字符数决定.(是的,我同意,这看起来很奇怪.)

因此,解决方法是用空格填充标签:

plot + labs(colour = "Clarity", shape = "      Cut")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


我衷心希望有人能尽快找到合适的解决方案!

  • @Alastair现在很明显,我的解决方法只适用于`ggplot2`版本0.9.0 - 这种解决方法在版本0.9.1中不再有效.因此,如果您仍在使用0.9.0,则可以使用空格填充字符串以获得所需的订单.正如我所说,这只是一种解决方法(而且保质期有限). (4认同)