【问题标题】:Controlling ggplot2 legend display order控制 ggplot2 图例显示顺序
【发布时间】:2012-07-09 23:14:00
【问题描述】:

有谁知道如何控制 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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

在 0.9.1 中,确定图例顺序的规则是 secretunpredictable。 现在,在 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))

【讨论】:

    【解决方案2】:

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

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

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


    我真诚地希望有人尽快发布适当的解决方案!

    【讨论】:

    • 如果我按照你的做法,我会清楚然后在我的图例中剪切(用空格填充)。 packageDescription("ggplot2")$Version = 0.9.1
    • 我应该明确表示我实际上想要颜色然后形状(即清晰度然后剪切),而不是类似于您的示例的剪切然后清晰度。但是,我希望能够将秤命名为任何名称并且仍然具有该顺序。
    • @Alastair 现在很明显,我的解决方法仅适用于 ggplot2 0.9.0 版本 - 此解决方法不再适用于 0.9.1 版本。因此,如果您仍在使用 0.9.0,您可以用空格填充字符串以获得所需的顺序。正如我所说,这只是一种解决方法(并且保质期有限)。
    猜你喜欢
    • 2013-03-20
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多