更改图例标题ggplot2

时间:2018-10-25 09:30:47

标签: r ggplot2 legend

我基于ggplot2在R中得到了一个图。不幸的是,我在这里没有足够的声誉上载剧情。现在,我想更改我的图例标题和两行的标签名称。

因此,我在代码中添加了scale_fill_continuous(name = "New Legend Title", labels=c("Control", "Treatment"))

ggplot(data=descripintens, 
aes(x=syear, y=workingintensity, group= treatment, colour=factor(treatment))) + 
geom_line() +
xlab("Year") +
ylab("Working intensity") +
scale_fill_continuous(name = "New Legend Title", labels=c("Control", "Treatment"))

这是stackoverflow和ggplot2备忘单中建议的内容。没有什么变化。甚至没有错误出现。

我的代码有什么问题?

谢谢!

编辑:我用于绘图的数据是一个表格,该表格基于以下代码:

descripintens<-intensity141516 %>% 
  group_by(syear, treatment) %>%
  summarise(workingintensity=mean(intensity))

descripintens如下所示:

   syear Treatment workingintensity
1  2014     0         96.2
2  2014     1         98.4
3  2015     0         101.00000
4  2015     1         102.00000
5  2016     0         105.9
6  2016     1         106.2

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:

ggplot(data=descripintens, aes(x=syear, y=workingintensity, group= treatment,colour=factor(treatment)))+
  geom_line()+xlab("Year")+
  ylab("Working intensity") + labs(color='NEW LEGEND TITLE')  +
   # you should specify the color also
  scale_color_manual(labels = c("Control", "Treatment"), values = c("blue", "red"))

enter image description here


有数据:

descripintens <- read.table(text ="   syear treatment workingintensity
1  2014     0         96.2
2  2014     1         98.4
3  2015     0         101.00000
4  2015     1         102.00000
5  2016     0         105.9
6  2016     1         106.2")

答案 1 :(得分:0)

对于表格:

descripintens <- data.frame(syear =  rep(2014:2016, each = 2),
                            Treatment = rep(c(0,1), 3),
                            workingintensity = c(96.2, 98.4, 101, 102, 105.9, 106.2))

图:

ggplot(data=data, 
       aes(x=syear, y=working_intensity, 
           group= Treatment, 
           color=factor(Treatment))) + 
  geom_line() + 
  xlab("Year") + 
  ylab("Working intensity") + 
  scale_color_discrete(name = "New Legend Title", 
                        labels=c("Control", "Treatment"))

首先,您尝试

scale_fill_continuous()

适用于连续变量,该变量映射到 fill ggplot2 aesthetics。 类型和映射必须适合您使用的功能,在您的情况下应为:

scale_color_discrete()