R语言ggplot2之图例的设置

这篇文章主要介绍了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 1\ntreatment", "Type 2\ntreatment"))

以上就是R语言ggplot2之图例的设置的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » R语言