引言
圖例的設(shè)置包括移除圖例、改變圖例的位置、改變標(biāo)簽的順序、改變圖例的標(biāo)題等。
移除圖例
有時(shí)候你想移除圖例,使用 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
改變圖例標(biāo)簽的順序
我們可以設(shè)置圖例的指定順序,也可以逆轉(zhuǎn)圖例的位置。
p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() #使用limit參數(shù)設(shè)置圖例位置 p + scale_fill_discrete(limits=c("trt1", "trt2", "ctrl")) #使用guides(fill=guide_legend(reverse=TRUE))逆轉(zhuǎn)圖例 p + guides(fill=guide_legend(reverse=TRUE))
設(shè)置圖例的標(biāo)題
我們可以改變圖例的標(biāo)題,也可以改變標(biāo)題的主題格式,還可以刪除圖例標(biāo)題。
#改變標(biāo)題名字 用labs() p + labs(fill="Condition") # 設(shè)置圖例的標(biāo)題的字體、顏色、大小用theme(legend.title=element_text()) p + theme(legend.title=element_text(face="italic", family="Times", colour="red", size=14)) #移除圖例標(biāo)題 #增加 guides(fill=guide_legend(title=NULL))函數(shù)即可移除圖例標(biāo)題 ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() + guides(fill=guide_legend(title=NULL))
設(shè)置圖例的標(biāo)簽
library(gcookbook) #改變標(biāo)簽的名字 p <- ggplot(PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() p + scale_fill_discrete(labels=c("Control", "Treatment 1", "Treatment 2")) #改變標(biāo)簽的主題 p + theme(legend.text=element_text(face="italic", family="Times", colour="red", size=14)) #多行圖例標(biāo)簽的展示 #有時(shí)候標(biāo)簽名字較長(zhǎng),一行展示不夠美觀,需要多行呈現(xiàn) 加一個(gè)\n p + scale_fill_discrete(labels=c("Control", "Type 1\ntreatment", "Type 2\ntreatment"))
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/zx403413599/article/details/48581713