如何编辑图例标题和标签?

时间:2019-11-26 03:08:57

标签: r ggplot2

第一篇文章,希望我已经包含了所有内容。

我正在尝试在以下图表中做两件事:

  1. 将图例标题从z,z1,z2更改为POS,ROD,INS
  2. 将图例标签全部更改为AOK和TUR

我整天都在努力寻找答案,但到目前为止没有任何效果。

Plot

我的数据是:

Year Area   Percentage
  <dbl> <fct>       <dbl>
1  2008 AOKPOS      0.571
2  2008 AOKPOS      0.6  
3  2008 AOKPOS      0.5  
4  2008 AOKPOS      0.846
5  2008 AOKPOS      0.2  
6  2008 AOKPOS      0.625

我的代码是:

plot1 <- ggplot() +
    # blue plot
    scale_x_continuous(name="", limits = c(2008, 2019),breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ 
    theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Possum, aes(x=x, y=y, group=z, colour=z), size=1)

plot1

plot2 <- ggplot() +
    # blue plot
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ 
    theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Rodent, aes(x=x1, y=y1, group=z1, colour=z1), size=1)

plot2

plot3 <- ggplot() +
    # blue plot
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ 
    theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Insect, aes(x=x2, y=y2, group=z2, colour=z2), size=1)

plot3

grid.arrange(plot1, plot2, plot3, nrow=3)

2 个答案:

答案 0 :(得分:0)

我不知道您要如何更改它,但 您可以使用labs()函数来做到这一点

#Default plot
print(p)

#Modify legend titles
p + labs(fill = "Dose (mg)")

enter image description here

使用代码后,标题会像这样更改 enter image description here

答案 1 :(得分:0)

好,所以发布后不久,我设法弄清楚了:

    plot1<-ggplot() +
    scale_x_continuous(name="", limits = c(2008, 2019),breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Possum, aes(x=x, y=y, group=z, colour=z), name = "Possum",size=1)

plot1<- plot1 + scale_color_discrete(name="Pos", label=c("Aok","Tur"))

plot1

plot2<-ggplot() +
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Rodent, aes(x=x1, y=y1, group=z1, colour=z1), size=1)

plot2<- plot2 + scale_color_discrete(name="Rod", label=c("Aok","Tur"))

plot2

plot3<-ggplot() +
    scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title
    scale_y_continuous(name = "",labels = scales::percent)+ theme(text = element_text(size=10))+
    coord_cartesian(ylim = c(0,1))+
    geom_smooth(data=Insect, aes(x=x2, y=y2, group=z2, colour=z2), size=1)

plot3<- plot3 + scale_color_discrete(name="Ins",label=c("Aok","Tur"))

plot3

grid.arrange(plot1,plot2,plot3, nrow=3)