本文首發(fā)于微信公眾號“生信補(bǔ)給站”,https://mp.weixin.qq.com/s/A5nqo6qnlt_5kF3_GIrjIA
學(xué)習(xí)了ggplot2|詳解八大基本繪圖要素后,就可以根據(jù)自己的需要繪制圖形。前面也給出了一些ggplot2繪制生信分析基本圖形的例子
pheatmap|暴雨暫歇,“熱圖”來襲?。?!
ggplot2-plotly|讓你的火山圖“活”過來
ggplot2|擴(kuò)展包從0開始繪制雷達(dá)圖
ggplot2| 繪制KEGG氣泡圖
ggplot2|繪制GO富集柱形圖
ggplot2|從0開始繪制PCA圖
ggplot2|ggpubr進(jìn)行“paper”組圖合并
本文將介紹一些對legend的細(xì)節(jié)操作來完成圖形的“精雕細(xì)琢”。
載入R包和數(shù)據(jù)
mtcars數(shù)據(jù)集作為示例數(shù)據(jù)
library(ggplot2)#查看數(shù)據(jù)集
head(mtcars)
# 將cyl gear變量轉(zhuǎn)為因子變量
mtcars$cyl<-as.factor(mtcars$cyl)
mtcars$gear <- as.factor(mtcars$gear)
繪制基本圖形
#gear為橫坐標(biāo),對mpg做箱線圖,gear填充顏色
p <- ggplot(mtcars, aes(x=gear, y=mpg, fill=gear)) + geom_boxplot()
p
img
設(shè)置 legend position
使用 theme() 參數(shù)設(shè)置legend位置
# 可選參數(shù)為“l(fā)eft”,“top”, “right”, “bottom”.
p + theme(legend.position="bottom")
img
# 數(shù)值向量 c(x,y) 調(diào)控位置
p + theme(legend.position = c(0.8, 0.2))
[圖片上傳失敗...(image-c8a690-1566271826199)]
更改legend 的title , font styles
# legend title
p + theme(legend.title = element_text(colour="blue", size=10, face="bold"))
# legend labels
p + theme(legend.text = element_text(colour="blue", size=10, face="bold"))
[圖片上傳失敗...(image-3533e3-1566271826199)]img
img
設(shè)置 legend 背景色
#fill設(shè)置legend box背景色,colour設(shè)置邊框顏色
p + theme(legend.background = element_rect(fill="lightblue", size=0.5, linetype="solid",
colour ="darkblue"))
img
設(shè)置legend items順序
scale_x_discrete自定義設(shè)置順序
p + scale_x_discrete(limits=c("3", "5", "4"))
img
去除legend
# 去除legend title
p + theme(legend.title = element_blank())
# 去除整個(gè)legend
p + theme(legend.position='none')
img
guides 設(shè)置specific aesthetic
使用guides()參數(shù)來設(shè)置或移除特定的美學(xué)映射(fill, color, size, shape等).
因子變量cyl和gear映射為點(diǎn)圖的顏色和形狀,qsec決定點(diǎn)的大小。
p <- ggplot(data = mtcars, aes(x=mpg, y=wt, color=cyl, size=qsec, shape=gear))+ geom_point()
# 不設(shè)定specific aesthetic時(shí)候
p
img
設(shè)置多個(gè)legend的位置
# 更改 legend position
p +theme(legend.position="bottom")
# Horizontal legend box
p +theme(legend.position="bottom", legend.box = "")
img
設(shè)置multiple guides順序
使用 guide_legend() 參數(shù):
p+guides(color = guide_legend(order=1), size = guide_legend(order=2), shape = guide_legend(order=3))
img
去除particular aesthetic
通過設(shè)置FALSE,可不展示對應(yīng)的legend
p+guides(color = FALSE)
img
也可以使用scale_xx.函數(shù)去掉特定的legend
# Remove legend for the point shape
p+scale_shape(guide=FALSE)
# Remove legend for size
p +scale_size(guide=FALSE)
# Remove legend for color
p + scale_color_manual(values=c('#999999','#E69F00','#56B4E9'), guide=FALSE)
img
通過以上參數(shù)的設(shè)置即完成對所繪制圖形的legend的細(xì)節(jié)修改,得到自己所需要的圖形。
更多關(guān)于生信,R,Python的內(nèi)容請關(guān)注小號“生信補(bǔ)給站”,謝謝 !
img