【问题标题】:Removing legend name [duplicate]删除图例名称 [重复]
【发布时间】:2019-09-15 03:47:37
【问题描述】:

我有一个如下的数据框:

X       Y      Variable
0.351   4.453  a
0.352   4.423  a
0.353   4.422  a
...     ...    ...
...     ...    ...
...     ...    ...
0.351   5.656  b
0.352   5.431  b
0.353   5.222  b

对于不同的变量等等。我将在示例中使用 2 个变量来保持简短。

我绘制了数据框,我想要一个显示变量名称但不显示图例标题的图例。

ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y") +
  theme_bw()

这给出了一个简单但干净的图表,带有一个图例。 但后来我想更改显示的图例中的标签,删除图例标题,并使用scale_color_manual 选项更改线条的颜色。 我可以更改颜色,但我无法做其他事情,因为图例消失了。

ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y") +
  scale_color_manual(values=c("green","red")
                     breaks=c("a","b")) +
  theme_bw()

我知道在最后一个代码中,图例标题缺少一个选项。我做错了什么?

【问题讨论】:

  • 这两个答案各有千秋,谢谢。

标签: r ggplot2 legend


【解决方案1】:

以下是如何更改图例标题和标签的示例。要完全删除标题,可以设置name = NULL

# Create data frame
df <- read.table(text = "X       Y      Variable
0.351   4.453  a
0.352   4.423  a
0.353   4.422  a
0.351   5.656  b
0.352   5.431  b
0.353   5.222  b", header = TRUE)

# Load libraries
library(ggplot2)

# Plot results
ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
  geom_line(size=1)+
  labs(x = "x",
       y = "y") +
  scale_color_manual(values=c("green","red"),
                     breaks=c("a","b"),
                     labels = c("Label one", "Label two"),
                     name = "My Legend Title") +
  theme_bw()

reprex package (v0.2.1) 于 2019 年 4 月 25 日创建

【讨论】:

    【解决方案2】:

    您可以使用 labs(color="") 删除您的图例标题,因为颜色 aes 为您的图例提供了名称:

    library(ggplot2)
    ggplot(data=df, aes(x=df$X, y=df$Y, color=df$Variable))+
      geom_line(size=1)+
      labs(x = "x",
           y = "y",
           color = NULL) +
      theme_bw()
    

    剧情:


    同样有效:

    scale_color_discrete(name = NULL)

    欲了解更多信息,请在此处查看thread

    【讨论】:

      猜你喜欢
      • 2015-08-04
      • 2019-05-18
      • 1970-01-01
      • 2021-04-16
      • 2018-05-17
      • 2013-09-16
      • 1970-01-01
      • 2016-01-30
      • 2021-07-23
      相关资源
      最近更新 更多