我对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)
Run Code Online (Sandbox Code Playgroud)
我做了一个简单的条形图:
require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
Run Code Online (Sandbox Code Playgroud)
我的问题是:有没有办法从图例中删除标题('类型')?
谢谢!
And*_*rie 50
您可以通过将其作为第一个参数传递给比例来修改图例标题.例如:
ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +
geom_bar(position="dodge") +
theme(legend.position="top", legend.direction="horizontal") +
scale_fill_discrete("")
Run Code Online (Sandbox Code Playgroud)
这也有一个捷径,即 labs(fill="")
由于您的图例位于图表的顶部,因此您可能还希望修改图例方向.你可以使用opts(legend.direction="horizontal").

小智 49
我发现最好的选择是使用+ theme(legend.title = element_blank())用户"gkcn"注明.
对于我(在03/26/15)使用以前建议labs(fill="")并scale_fill_discrete("")删除一个标题,只添加另一个图例,这是没用的.
Yur*_*kiy 23
工作对我来说,唯一的方法是使用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()
)
Run Code Online (Sandbox Code Playgroud)
PS 文档中有更多有用的选项.
你已经有了两个不错的选择,所以这是另一个使用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"))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是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"))
Run Code Online (Sandbox Code Playgroud)