📜  如何使用 ggplot 更改 R 中的图例标题?

📅  最后修改于: 2022-05-13 01:54:43.524000             🧑  作者: Mango

如何使用 ggplot 更改 R 中的图例标题?

图例有助于理解同一图形上不同的图所表示的含义。它们基本上为图形描述的有用数据提供标签或名称。在本文中,我们将讨论如何在 R 编程语言中更改图例名称。

让我们先看看默认情况下会出现什么图例标题。

例子:

R
library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()


R
library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
scale_colour_discrete(name="participant")


R
library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
labs(col="participant")


R
library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
guides(col=guide_legend("participant"))


输出:



现在让我们讨论提供图例标题的各种方式。

方法 1:使用 scale_colour_discrete()

要使用此方法更改图例标题,只需提供所需的标题作为其 name 属性的值。

句法:

例子:

电阻

library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
scale_colour_discrete(name="participant")

输出:



方法 2:使用 labs()

Labs()函数用于修改轴、标签等。它可以通过为 col 属性提供适当的标题名称来更改图例标题。

句法:

例子:

电阻

library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
labs(col="participant")

输出:

方法 3:使用 guides()

guides() 可用于更改图例标题。要使用此函数更改标题,请将所需名称作为参数传递给 guide_legend()函数,并最终作为属性 col 的值。

句法:

例子:

电阻

library("ggplot2")
  
year<-c(2000,2001,2002,2003,2004)
winner<-c('A','B','B','A','B')
score<-c(9,7,9,8,8)
  
df<-data.frame(year,winner,score)
  
ggplot(df,aes(x=year,y=score,group=winner))+
geom_line(aes(color=winner))+geom_point()+
guides(col=guide_legend("participant"))

输出: