引言
图例的设置包括移除图例、改变图例的位置、改变标签的顺序、改变图例的标题等。
移除图例
有时候你想移除图例,使用 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))#多行图例标签的展示#有时候标签名字较长,一行展示不够美观,需要多行呈现 加一个\np + scale_fill_discrete(labels=c("Control", "Type 1\ntreatment","Type 2\ntreatment"))以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。