如何更改ggplot中的图例标题 [英] How to change legend title in ggplot

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

问题描述

我有下面这样的情节。
它是用这个命令创建的:

  library(ggplot2)

df< - data.frame(cond = factor(rep(c(A,B),each = 200)),
rating = c(rnorm(200),rnorm(200,mean = .8) ))

ggplot(df,aes(x = rating,fill = cond))+
geom_density(alpha = .3)+
xlab(NEW RATING TITLE) +
ylab(新密度标题)

现在我要做的下一件事是将图例标题 cond 修改为新图例标题 我做的只是添加以下代码,添加上面代码的结尾:

  + labs(color =NEW LEGEND TITLE )

但它不起作用。什么是正确的做法?



解决方案

这应该有效:

  p < -  ggplot(df,aes(x = rating,fill = cond))+ 
geom_density(alpha = .3)+
xlab(NEW RATING TITLE) +
ylab(新密度标题)
p <-p + guides(fill = guide_legend(title =New Legend Title))
pre

(或者)

pre $ scale_fill_discrete(name = New Legend Title)


I have the following plot like below. It was created with this command:

library(ggplot2)

df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)), 
                 rating = c(rnorm(200), rnorm(200, mean=.8)))

ggplot(df, aes(x=rating, fill=cond)) + 
geom_density(alpha = .3) +
xlab("NEW RATING TITLE") +
ylab("NEW DENSITY TITLE")

Now next thing I want to do is to modify the legend title from cond into NEW LEGEND TITLE.

So what I did is to just add the following line add the end of the above code:

+labs(colour="NEW LEGEND TITLE")

But it doesn't work. What's the right way to do it?

解决方案

This should work:

p <- ggplot(df, aes(x=rating, fill=cond)) + 
           geom_density(alpha=.3) + 
           xlab("NEW RATING TITLE") + 
           ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))

(or alternatively)

p + scale_fill_discrete(name = "New Legend Title")

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

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