我如何删除ggplot2中的图例标题? [英] How can I remove the legend title in ggplot2?

查看:2482
本文介绍了我如何删除ggplot2中的图例标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于ggplot2中的图例的问题。



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

 胡萝卜< -NULL 
胡萝卜$农场<-rep(c(X,Y),2)
胡萝卜$ Type <-rep(c(Orange,Purple),each = 2)
胡萝卜$ MeanLength <-c(10,6,4,2)
胡萝卜< - data.frame(胡萝卜)

我做了一个简单的棒图:

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

我的问题是:有没有办法从图例中删除标题('Type')?

b $ b

解决方案

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

pre $ g $ p $ ggplot(胡萝卜,aes(y = MeanLength,x = Farm,fill = Type))+
geom_bar(position =dodge)+
theme(legend.position =top,legend.direction =horizo​​ntal)+
scale_fill_discrete()

还有一个快捷方式,例如 labs(fill =)

由于您的图例位于图表的顶部,因此您可能还希望修改图例方向。您可以使用 opts(legend.direction =horizo​​ntal)


I have a question concerning the legend in ggplot2.

Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:

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)

I make a simple bar plot:

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

My question is: is there a way to remove the title ('Type') from the legend?

Thanks!

解决方案

You can modify the legend title by passing it as the first parameter to a scale. For example:

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

There is also a shortcut for this, i.e. labs(fill="")

Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using opts(legend.direction="horizontal").

这篇关于我如何删除ggplot2中的图例标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆