【问题标题】:remove legend title in ggplot删除ggplot中的图例标题
【发布时间】:2013-01-24 03:48:12
【问题描述】:

我正在尝试删除ggplot2 中的图例标题:

df <- data.frame(
  g = rep(letters[1:2], 5),
  x = rnorm(10),
  y = rnorm(10)
)

library(ggplot2)
ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom")

我见过this question,但那里的解决方案似乎都不适合我。大多数人给出了一个关于如何弃用opts 并改用theme 的错误。我也试过各种版本的theme(legend.title=NULL)theme(legend.title="")theme(legend.title=element_blank)等。典型的错误信息有:

'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1)
'theme_blank' is deprecated. Use 'element_blank' instead. (Deprecated; last used in version 0.9.1)

自 0.9.3 版发布以来,我第一次使用 ggplot2,但我发现有些变化很难驾驭...

【问题讨论】:

  • 您可以为此使用labs():将labs(colour = "") 行添加到生成上图的代码中。

标签: r ggplot2


【解决方案1】:

你快到了:只需添加theme(legend.title=element_blank())

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  theme(legend.title=element_blank())

This page on Cookbook for R 提供了大量关于如何自定义图例的详细信息。

【讨论】:

  • 这将删除所有图例标题。对于更多本地控制,guide = guide_legend() 命令有效。删除填充图例标题,但保留颜色图例标题,例如scale_fill_brewer(palette = "Dark2", guide = guide_legend(title = NULL)) + scale_color_manual(values = c("blue", "white", "red"))
【解决方案2】:

这也有效,还演示了如何更改图例标题:

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  scale_color_discrete(name="")

【讨论】:

  • 这会将标题替换为空字符串,因此会在标签和图例框之间产生额外的空间,只有当图例的框或背景颜色与其所在位置不同时,该空间才会可见定位。因此,在像 theme_bw() 这样的简单情况下,快速且现成的方法是可以的,但在图例周围有一个框并且位于绘图区域某处(我通常的方法)的情况下不是最好的。
  • +1 用于观察。我在使用两个不同的图例以及由上述解决方案创建的它们之间的空白时遇到了问题。设置scale_color_manual(name=element_blank())+for 下面的图例为我解决了这个问题
  • @joaoal, element_blank() 似乎是推荐的方法。设置name = NULL 是另一种方式。
【解决方案3】:

对于Error: 'opts' is deprecated。请改用theme()。 (已失效;最后在 0.9.1 版中使用)' 我将opts(title = "Boxplot - Candidate's Tweet Scores") 替换为 labs(title = "Boxplot - Candidate's Tweet Scores")。成功了!

【讨论】:

    【解决方案4】:

    使用labs 并将颜色设置为NULL 的另一个选项。

    ggplot(df, aes(x, y, colour = g)) +
      geom_line(stat = "identity") +
      theme(legend.position = "bottom") +
      labs(colour = NULL)
    

    【讨论】:

      【解决方案5】:

      由于情节中可能有多个图例,一种有选择地只删除一个标题而不留下空白空间的方法是将scale_ 函数的name 参数设置为NULL,即

      scale_fill_discrete(name = NULL)

      (感谢@pascal a comment on another thread

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-03
        • 2016-06-07
        • 1970-01-01
        • 2016-04-09
        • 2021-12-07
        • 1970-01-01
        相关资源
        最近更新 更多