控制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


阿晨1998
浏览 594回答 2
2回答

万千封印

在0.9.1中,确定图例顺序的规则是秘密且不可预测的。现在,在github中的dev版本0.9.2中,您可以使用参数设置图例的顺序。这是示例:plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) +&nbsp; geom_point() + opts(legend.position = "top")plot + guides(colour = guide_legend(order = 1),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; shape = guide_legend(order = 2))plot + guides(colour = guide_legend(order = 2),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; shape = guide_legend(order = 1))
打开App,查看更多内容
随时随地看视频慕课网APP