【问题标题】:Controlling linetype, color and label in ggplot legend控制 ggplot 图例中的线型、颜色和标签
【发布时间】:2017-09-25 01:03:46
【问题描述】:

我在以前也指定了自定义线型和颜色的图上设置自定义图例标签时遇到问题。在 stackoverflow 上有一个类似的问题,它处理 linetypes and line colors 的自定义图例。但是,一旦您希望在上述两个属性之上指定图例标签,ggplot2 似乎就开始崩溃了。

这是我的最小可重现示例:

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
           treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
  geom_line() +
  scale_linetype_manual(values = c(1, 3),
                        labels = c("Treatment one", "Treatment two")) +
  scale_color_manual(values = c("black", "red"))

上面的代码结果如下图

scale_linetype_manual()scale_color_manual() 中设置标签会导致创建两个单独的图例。具有正确虚线的那条线将始终是无色的。另一方面,具有正确颜色的线型将无法正确表示线型(仅实线)。

有没有办法在 ggplot2 中同时控制颜色、线型和图例标签?或者这是我应该在 getgo 的数据框中正确指定标签的包的限制?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    使scale_linetype_manual()scale_color_manual() 的标签相同。

    library(ggplot2)
    
    df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
                     treatment = c(rep("one", 2), rep("two", "2")))
    
    ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
      geom_line() +
      scale_linetype_manual(values = c(1, 3),
                            labels = c("Treatment one", "Treatment two")) +
      scale_color_manual(values = c("black", "red"),
                         labels = c("Treatment one", "Treatment two"))
    

    【讨论】:

    • 有没有办法在不向data 添加处理列的情况下做到这一点?换句话说,我可以更特别地添加具有各种颜色的线条并在图例中为它们分配自定义名称吗?
    • @theforestecologist 我不知道。
    猜你喜欢
    • 2012-07-05
    • 2022-11-22
    • 1970-01-01
    • 2017-02-05
    • 2015-07-04
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多