60

我对 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

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

谢谢!

4

6 回答 6

55

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

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

于 2015-03-26T17:49:13.580 回答
53

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

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").

在此处输入图像描述

于 2011-05-16T20:36:11.853 回答
29

您可以使用labs

p + labs(fill="")

绘图示例

于 2011-05-16T20:27:37.047 回答
24

对我有用的唯一方法是使用and 我认为与andlegend.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()
)

PS文档中有更多有用的选项。

于 2011-08-25T05:52:17.483 回答
7

您已经有两个不错的选择,所以这里有另一个使用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"))

如果您使用的是最新的(截至 2015 年 1 月)版本的 ggplot2(版本 1.0),那么以下应该可以工作:

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"))
于 2011-05-16T20:40:04.190 回答
1

@pascal 在评论中设置name比例函数参数的解决方案,例如scale_fill_discrete, to NULL,对我来说是最好的选择。它允许删除标题以及如果您使用 保留的空白空间,""同时允许用户有选择地删除标题,这在该theme(legend.title = element_blank())方法中是不可能的。

由于它隐藏在评论中,因此我将其发布为可能增加其知名度的答案,并感谢@pascal。

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

scale_fill_discrete(name = NULL)

于 2020-06-05T10:20:57.440 回答