引言
圖例的設置包括移除圖例、改變圖例的位置、改變標簽的順序、改變圖例的標題等。
移除圖例
有時候你想移除圖例,使用 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"))
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/zx403413599/article/details/48581713