有谁知道我如何控制 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
最佳答案
在0.9.1中,确定图例顺序的规则是 secret 和不可预测。 现在,在 github 的 0.9.2 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))
plot + guides(colour = guide_legend(order = 2),
shape = guide_legend(order = 1))
关于r - 控制ggplot2图例显示顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11393123/