r - 控制ggplot2图例显示顺序

标签 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

最佳答案

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

enter image description here

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

enter image description here

关于r - 控制ggplot2图例显示顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11393123/

相关文章:

r - 将调色板与 ggplot2 主题相关联

r - R 中的时间序列与 ggplot2

r - ggplot2 中的小时刻度

r - 更有效的声音文件二次采样方法?

r - window 7 : Installing multiple R packages via script

r - 使用 R 创建与 twitter 流 API 的持久连接

R:使用组引用计算行中值之间的差异

r - 使用 prcomp 和我自己在 R 中进行主成分分析 : different results

r - 控制点的 z 顺序并在 ggplot2/rpy2 中组合来自多个图层的图例

r - 提供给离散尺度的连续值