ggplot2 |legend參數設置,圖形精雕細琢

本文首發於微信公衆號「生信補給站」,https://mp.weixin.qq.com/s/A5nqo6qnlt_5kF3_GIrjIA微信

學習了ggplot2|詳解八大基本繪圖要素後,就能夠根據本身的須要繪製圖形。前面也給出了一些ggplot2繪製生信分析基本圖形的例子

pheatmap|暴雨暫歇,「熱圖」來襲!!!

ggplot2-plotly|讓你的火山圖「活」過來

ggplot2|擴展包從0開始繪製雷達圖

ggplot2| 繪製KEGG氣泡圖

ggplot2|繪製GO富集柱形圖

ggplot2|從0開始繪製PCA圖

ggplot2|ggpubr進行「paper」組圖合併

本文將介紹一些對legend的細節操做來完成圖形的「精雕細琢」。

載入R包和數據

mtcars數據集做爲示例數據markdown

library(ggplot2)#查看數據集
head(mtcars)                   
# 將cyl gear變量轉爲因子變量
mtcars$cyl<-as.factor(mtcars$cyl)
mtcars$gear <- as.factor(mtcars$gear)

繪製基本圖形

#gear爲橫座標,對mpg作箱線圖,gear填充顏色
p <- ggplot(mtcars, aes(x=gear, y=mpg, fill=gear)) + geom_boxplot()
p

img

設置 legend position

使用 theme() 參數設置legend位置app

# 可選參數爲「left」,「top」, 「right」, 「bottom」.
p + theme(legend.position="bottom")

img

# 數值向量 c(x,y) 調控位置
p + theme(legend.position = c(0.8, 0.2))

img

更改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"))

imgimg
img

 

設置 legend 背景色

#fill設置legend box背景色,colour設置邊框顏色
p + theme(legend.background = element_rect(fill="lightblue",                                 size=0.5, linetype="solid",                                 
    colour ="darkblue"))

img

設置legend items順序

scale_x_discrete自定義設置順序ide

p + scale_x_discrete(limits=c("3", "5", "4"))

img

去除legend

# 去除legend title
p + theme(legend.title = element_blank())
# 去除整個legend
p + theme(legend.position='none')

img

 

guides 設置specific aesthetic

使用guides()參數來設置或移除特定的美學映射(fill, color, size, shape等).
因子變量cyl和gear映射爲點圖的顏色和形狀,qsec決定點的大小。函數

p <- ggplot(data = mtcars,   aes(x=mpg, y=wt, color=cyl, size=qsec, shape=gear))+   geom_point()
# 不設定specific aesthetic時候
p

img

設置多個legend的位置

# 更改 legend position
p +theme(legend.position="bottom")
# Horizontal legend box
p +theme(legend.position="bottom", legend.box = "")

img

設置multiple guides順序

使用 guide_legend() 參數:學習

p+guides(color = guide_legend(order=1),        size = guide_legend(order=2),        shape = guide_legend(order=3))

img

去除particular aesthetic

經過設置FALSE,可不展現對應的legendui

p+guides(color = FALSE)

img

也能夠使用scale_xx.函數去掉特定的legendspa

# 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

經過以上參數的設置即完成對所繪製圖形的legend的細節修改,獲得本身所須要的圖形。3d

參考資料:http://www.sthda.com/english/wiki/ggplot2-legend-easy-steps-to-change-the-position-and-the-appearance-of-a-graph-legend-in-r-softwarecode

 

相關文章
相關標籤/搜索