如何删除ggplot2中的图例标题?

问题描述 投票:58回答:6

我对ggplot2中的图例有疑问。

说我有一个关于两个农场两种不同颜色的平均胡萝卜长度的假设数据集:

carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)

我制作了一个简单的条形图:

require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) + 
geom_bar(position="dodge") +
opts(legend.position="top")
p

我的问题是:有没有办法从图例中删除标题(“类型”)?

谢谢!

r ggplot2 legend
6个回答
51
投票

您可以通过将图例标题作为第一个参数传递给比例尺来修改图例标题。例如:

ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) + 
  geom_bar(position="dodge") +
  theme(legend.position="top", legend.direction="horizontal") +
  scale_fill_discrete("")

还有一个快捷方式,即labs(fill="")

由于图例位于图表的顶部,因此您可能还希望修改图例的方向。您可以使用opts(legend.direction="horizontal")执行此操作。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9WT2RSNy5wbmcifQ==” alt =“在此处输入图像描述”>


51
投票

我发现最好的选择是使用+ theme(legend.title = element_blank())作为用户“ gkcn”。

对我来说(15年3月26日,使用我以前建议的labs(fill="")scale_fill_discrete("")删除一个标题,只是添加另一个图例,这是没有用的。


29
投票

您可以使用labs

p + labs(fill="")

“绘图示例”


24
投票

[对我而言,唯一有效的方法是使用legend.title = theme_blank(),与labs(fill="")scale_fill_discrete("")相比,我认为它是最方便的变体,在某些情况下也可能有用。

ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) + 
geom_bar(position="dodge") +
opts(
    legend.position="top",
    legend.direction="horizontal",
    legend.title = theme_blank()
)

P.S。 documentation中还有更多有用的选项。


6
投票

您已经有两个不错的选择,所以这里是另一个使用scale_fill_manual()的选择。请注意,这还使您可以轻松指定条形的颜色:

ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) + 
  geom_bar(position="dodge") +
  opts(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))

如果您使用的是ggplot2(1.0版)的最新版本(截至2015年1月),则应执行以下操作:

ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))

0
投票

@ pascal在comment中的解决方案中,将比例函数(例如name)的scale_fill_discrete参数设置为NULL,对我来说是最佳选择。它允许删除标题以及如果您使用""会保留的空白,同时允许用户有选择地删除标题,这是theme(legend.title = element_blank())方法无法实现的。

由于它已包含在评论中,因此我将其发布为答案,以可能提高其可见性,并以@pascal表示赞誉。

TL; DR(用于复制粘贴):

scale_fill_discrete(name = NULL)

© www.soinside.com 2019 - 2024. All rights reserved.