控制GGPLOT2传说显示顺序(Controlling ggplot2 legend display

2019-06-14 18:10发布

有谁知道我怎样才能在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

Answer 1:

在0.9.1,确定传说中的顺序规则是秘密的不可预测的 。 现在,在0.9.2,在github上开发的版本,您可以使用参数设置传奇的顺序。

这里是例子:

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



Answer 2:

在我看来,那个传说中的顺序由字符的音阶名的数量决定。 (是的,我同意,这似乎离奇。)

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

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


我真诚地希望有人尽快上岗妥善的解决办法!



文章来源: Controlling ggplot2 legend display order
标签: r ggplot2