R语言ggplot2之图例的设置

2021-04-22 17:11:10 IT技术网 互联网
浏览

R语言ggplot2之图例的设置

 更新时间:2021年04月22日 11:57:29   作者:zx403413599  

这篇文章主要介绍了R语言ggplot2之图例的设置方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

引言

图例的设置包括移除图例、改变图例的位置、改变标签的顺序、改变图例的标题等。

移除图例

有时候你想移除图例,使用 guides()。

library(ggplot2)
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
p + guides(fill=FALSE)

改变图例的位置

我们可以用theme(legend.position=…)将图例移到图表的上方、下方、左边和右边。

p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
scale_fill_brewer(palette="Pastel2")
#上方 
p + theme(legend.position="top")#左边left,右边 right, 底部bottom

改变图例标签的顺序

我们可以设置图例的指定顺序,也可以逆转图例的位置。

p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
#使用limit参数设置图例位置
p + scale_fill_discrete(limits=c("trt1", "trt2", "ctrl"))
#使用guides(fill=guide_legend(reverse=TRUE))逆转图例
p + guides(fill=guide_legend(reverse=TRUE))

设置图例的标题

我们可以改变图例的标题,也可以改变标题的主题格式,还可以删除图例标题。

#改变标题名字 用labs()
p + labs(fill="Condition")
# 设置图例的标题的字体、颜色、大小用theme(legend.title=element_text())
p + theme(legend.title=element_text(face="italic", family="Times", colour="red",
size=14))
#移除图例标题
#增加 guides(fill=guide_legend(title=NULL))函数即可移除图例标题
ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
guides(fill=guide_legend(title=NULL))

设置图例的标签

library(gcookbook)
#改变标签的名字
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
p + scale_fill_discrete(labels=c("Control", "Treatment 1", "Treatment 2"))
#改变标签的主题
p + theme(legend.text=element_text(face="italic", family="Times", colour="red",
size=14))
#多行图例标签的展示
#有时候标签名字较长,一行展示不够美观,需要多行呈现 加一个n
p + scale_fill_discrete(labels=c("Control", "Type 1ntreatment",
"Type 2ntreatment"))

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT技术网。如有错误或未考虑完全的地方,望不吝赐教。