删除ggplot中的图例标题

smi*_*lig 103 r ggplot2

我正在尝试删除传奇的标题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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我已经看到了这个问题,似乎没有任何解决方案对我有用.大多数人都提出了关于如何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)
Run Code Online (Sandbox Code Playgroud)

ggplot2自从0.9.3版本发布以来我第一次使用,我发现很难导航一些变化......

jub*_*uba 178

你几乎就在那里:只需添加 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())
Run Code Online (Sandbox Code Playgroud)

Cookbook for R上的这个页面提供了有关如何自定义图例的大量详细信息.

  • 这将删除所有图例标题。要获得更多本地控制,可以使用“guide = guide_legend()”命令。删除填充图例标题,但保留颜色图例标题,例如``scale_fill_brewer(palette = "Dark2", guide = guide_legend(title = NULL)) + scale_color_manual(values = c("blue", "white", “红色”))`` (2认同)

Rol*_*and 9

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

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

  • 这将使用空字符串替换标题,因此会在标签和图例框之间产生额外的空间,仅当图例的框或背景颜色与其所在位置不同时才会显示.因此,在简单的情况下(例如``theme_bw()``可以快速准备好方法,但在图例周围有一个方框并且位于绘图区域的某个位置(我通常的方法)的情况下,这是最好的. (5认同)

mpa*_*nco 5

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

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

在此输入图像描述