ggplot2學(xué)習(xí)筆記之圖形排列

R語言基本繪圖函數(shù)中可以利用par()以及l(fā)ayout()來進(jìn)行圖形排列郊闯,但是這兩個(gè)函數(shù)對(duì)于ggplot圖則不太適用裕偿,本文主要講解如何對(duì)多ggplot圖形多頁面進(jìn)行排列。主要講解如何利用包gridExtra门岔、cowplot以及ggpubr中的函數(shù)進(jìn)行圖形排列钥庇。

繪制圖形

#load packages
library(gridExtra)
library(cowplot)
library(ggpubr)
#dataset ToothGrowth and mtcars
mtcars$name <- rownames(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars[, c("name", "wt","mpg", "cyl")])
#First let's create some plots
#Box plot(bxp)
bxp <- ggboxplot(ToothGrowth, x="dose", y="len", color = "dose", palette = "jco")
#Dot plot(dp)
dp <- ggdotplot(ToothGrowth, x="dose", y="len", color = "dose", palette = "jco", binwidth = 1)
#An ordered Bar plot(bp)
bp <- ggbarplot(mtcars, x="name", y="mpg", fill="cyl", #change fill color by cyl 
color="white", #Set bar border colors to white 
palette = "jco", #jco jourbal color palette 
sort.val = "asc", #Sort the value in ascending order 
sort.by.groups = TRUE, #Sort inside each group 
x.text.angle=90 #Rotate vertically x axis texts )
bp+font("x.text", size = 8)
#Scatter plots(sp)
sp <- ggscatter(mtcars, x="wt", y="mpg", add = "reg.line", #Add regression line 
conf.int = TRUE, #Add confidence interval 
color = "cyl", palette = "jco",#Color by group cyl 
shape = "cyl" #Change point shape by groups cyl 
)+ 
stat_cor(aes(color=cyl), label.x = 3) #Add correlation coefficientsp

圖形排列

多幅圖形排列于一面

  • ggpubr::ggarrange()
ggarrange(bxp, dp, bp+rremove("x.text"), labels = c("A", "B", "C"), ncol = 2, nrow = 2)
  • cowplot::plot.grid()
plot_grid(bxp, dp, bp+rremove("x.text"), labels = c("A", "B", "C"), ncol = 2, nrow = 2)
  • gridExtra::grid.arrange()
grid.arrange(bxp, dp, bp+rremove("x.text"), ncol=2, nrow=2)

排列圖形注釋

  • ggpubr::annotate_figure()
figure <- ggarrange(sp, bp+font("x.text", size = 10), ncol = 1, nrow = 2)
annotate_figure(figure, top=text_grob("Visualizing mpg", color = "red", 
face = "bold", size=14), bottom = text_grob("Data source:\n mtcars data set", 
color = "blue", hjust = 1, x=1, face = "italic", size=10), left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90), 
right = "I'm done, thanks :-)!", fig.lab = "Figure 1", fig.lab.face = "bold")

繪圖面板對(duì)齊

  • 繪制生存曲線
library(survival)
head(colon[, c(1:4)])
#Fit survival curves
fit <- survfit(Surv(time, status)~adhere, data = colon)
library(survminer)
ggsurv <- ggsurvplot(fit, data = colon, palette = "jco", #jco palette 
pval = TRUE, pval.coord=c(500, 0.4), #Add p-value 
risk.table = TRUE #Add risk table)
names(ggsurv)
## [1] "plot" "table" "data.survplot" "data.survtable"

ggsurv是一個(gè)包含兩部分的list

  • plot:生存曲線
  • table:風(fēng)險(xiǎn)表
    可以用ggarrange()進(jìn)行排列這兩者
ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7), ncol = 1, nrow = 2)

上圖中的坐標(biāo)軸沒有對(duì)齊,可以通過參數(shù)align來設(shè)置

ggarrange(ggsurv$plot, ggsurv$table, heights = c(2, 0.7), ncol = 1, nrow = 2, align = "v")

改變排列圖的行列

設(shè)置面板為兩行兩列,其中sp占據(jù)第一行的兩列爹土,bxp以及dp置于第二行的兩列

ggarrange(sp, #First row with scatter plot(sp) 
ggarrange(bxp, dp, ncol = 2, labels = c("B","C")),#Second row with box and dot plot 
nrow = 2, labels = "A" #Labels of the scatter plot)

R包c(diǎn)owplot

cowplot::ggdraw()可以將圖形置于特定位置, ggdraw()首先會(huì)初始化一個(gè)繪圖面板甥雕, 接下來draw_plot()則是將圖形繪制于初始化的繪圖面板中,通過參數(shù)設(shè)置可以將圖形置于特定位置着饥。

draw_plot(plot, x=0, y=0, width=1, height=1)

其中:

  • plot:將要放置的圖形
  • x,y:控制圖形位置
  • width,height:圖形的寬度和高度
  • draw_plot_label():為圖形添加標(biāo)簽
draw_plot_label(label, x=0, y=1, size=16, ...)

其中:

  • label:標(biāo)簽
  • x,y:控制標(biāo)簽位置
  • size:標(biāo)簽字體大小

下面通過一個(gè)例子來講解如何將多個(gè)圖形放置在特定的位置犀农。

ggdraw()+ draw_plot(bxp, x=0, y=0.5, width=0.5, height = 0.5)+
draw_plot(dp, x=0.5, y=0.5, width = 0.5, height = 0.5)+ 
draw_plot(bp, x=0, y=0, width = 1.5, height = 0.5)+ 
draw_plot_label(label = c("A", "B", "C"), size = 15, x=c(0, 0.5, 0), y=c(1, 1, 0.5))

R包gridExtra

gridExtra::arrangeGrop()改變行列分布

下面將sp置于第一行并橫跨兩列,而bxp和dp分別分布于第二行兩列

grid.arrange(sp, #First row with one plot spaning over 2 columns
arrangeGrob(bxp, dp, ncol = 2), #Second row with 2plots in 2 different columns 
nrow=2) #number of rows

也可以通過函數(shù)grid.arrange中的layout_matrix來設(shè)置復(fù)雜的圖形布局

grid.arrange(bp, #bar plot spaning two columns 
bxp, sp, #box plot amd scatter plot 
ncol=2, nrow=2, layout_matrix=rbind(c(1, 1), c(2, 3)))

要相對(duì)grid.arrange()以及arrangeGrob()的輸出進(jìn)行注釋宰掉,首先要利用as_ggplot()將其轉(zhuǎn)化為ggplot圖形呵哨,進(jìn)而利用函數(shù)draw_plot_label()對(duì)其進(jìn)行注釋。

gt <- arrangeGrob(bp, bxp, sp, layout_matrix = rbind(c(1,1),c(2, 3)))
p <- as_ggplot(gt)+ 
draw_plot_label(label = c("A", "B", "C"), size = 15, x=c(0, 0, 0.5), y=c(1, 0.5, 0.5))
p

R包grid

R包grid中的grid.layout()可以設(shè)置復(fù)雜的圖形布局轨奄,viewport()可以定義一個(gè)區(qū)域用來安置圖形排列孟害,print()則用來將圖形置于特定區(qū)域。 總結(jié)起來步驟如下:

  • 創(chuàng)建圖形p1,p2,p3,…
  • grid.newpage()創(chuàng)建一個(gè)畫布
  • 創(chuàng)建圖形布局挪拟,幾行幾列
  • 定義布局的矩形區(qū)域
  • print:將圖形置于特定區(qū)域
library(grid)
#Move to a new page
grid.newpage()
#Create layout:nrow=3, ncol=2
pushViewport(viewport(layout = grid.layout(nrow=3, ncol=2)))
#A helper function to define a region on the layout
define_region <- function(row, col){ 
viewport(layout.pos.row = row, layout.pos.col = col)}
#Arrange the plots
print(sp, vp=define_region(row=1, col=1:2)) #Span over two columns
print(bxp, vp=define_region(row=2, col=1))
print(dp, vp=define_region(row=2, col=2))
print(bp+rremove("x.text"), vp=define_region(row=3, col=1:2))

設(shè)置共同圖例

ggpubr::ggarrange()可以為組合圖形添加共同圖例

  • common.legeng=TRUE:在圖形旁邊添加圖例
  • legend:指定legend的位置挨务,主要選項(xiàng)有:top、bottom玉组、left谎柄、right。
ggarrange(bxp, dp, labels = c("A", "B"), common.legend = TRUE, legend = "bottom")

含有邊際密度圖的散點(diǎn)圖

sp <- ggscatter(iris, x="Sepal.Length", y="Sepal.Width", color="Species", 
palette = "jco", size=3, alpha=0.6)+border()
#Marginal density plot of x(top panel) and y(right panel)
xplot <- ggdensity(iris, "Sepal.Length", fill="Species",palette = "jco")
yplot <- ggdensity(iris, "Sepal.Width", fill="Species", palette = "jco")+rotate()
#Clean the plots
xplot <- xplot+clean_theme()
yplot <- yplot+clean_theme()
#Arrange the plots
ggarrange(xplot, NULL, sp, yplot, ncol = 2, nrow = 2, align = "hv", widths = c(2, 1), 
heights = c(1, 2), common.legend = TRUE)

ggplot圖惯雳、文本朝巫、表格組合

density.p <- ggdensity(iris, x="Sepal.Length", fill="Species", palette = "jco")
#Compute the summary table of Sepal.Length
stable <- desc_statby(iris, measure.var = "Sepal.Length", grps = "Species")
stable <- stable[, c("Species", "length", "mean", "sd")]
#Summary table plot, medium and theme
stable.p <- ggtexttable(stable, rows = NULL, theme = ttheme("mOrange"))
text <- paste("iris data set gives the measurements in cm", "of the variables sepal length and width", "and petal length and width, respectively,", "for 50 flowers from each of 3 species of iris.", "The species are Iris setosa, versicolor, and virginica.", sep = " ")
text.p <- ggparagraph(text = text, face = "italic", size = 11, color = "black")
#Arrange the plots on the same page
ggarrange(density.p, stable.p, text.p, ncol = 1, nrow = 3, heights = c(1, 0.5, 0.3))

ggplot圖形中嵌入圖形元素

ggplot2::annotation_custom()可以添加各種圖形元素到ggplot圖中

annotation_custom(grob, xmin, xmax, ymin, ymax)

其中:

  • grob:要添加的圖形元素
  • xmin, xmax: x軸方向位置(水平方向)
  • ymin, ymax: y軸方向位置(豎直方向)

ggplot圖形中添加table

density.p+annotation_custom(ggplotGrob(stable.p), xmin = 5.5, xmax = 8, ymin = 0.7)

ggplot圖形中添加box plot

sp <- ggscatter(iris, x="Sepal.Length", y="Sepal.Width", color = "Species", palette = "jco", size = 3, alpha=0.6)
xbp <- ggboxplot(iris$Sepal.Length, width = 0.3, fill = "lightgray")+ rotate()+theme_transparent()
ybp <- ggboxplot(iris$Sepal.Width, width = 0.3, fill="lightgray")+theme_transparent()
# Create the external graphical objects
# called a "grop" in Grid terminology
xbp_grob <- ggplotGrob(xbp)
ybp_grob <- ggplotGrob(ybp)
#place box plots inside the scatter plot
xmin <- min(iris$Sepal.Length)
xmax <- max(iris$Sepal.Length)
ymin <- min(iris$Sepal.Width)
ymax <- max(iris$Sepal.Width)
yoffset <- (1/15)*ymax
xoffset <- (1/15)*xmax
# Insert xbp_grob inside the scatter plots
p+annotation_custom(grob = xbp_grob, xmin = xmin, xmax = xmax, 
ymin = ymin-yoffset, ymax = ymin+yoffset)+
# Insert ybp_grob inside the scatter plot
annotation_custom(grob = ybp_grob, xmin = xmin-xoffset, 
xmax=xmin+xoffset, ymin=ymin, ymax=ymax)

ggplot圖形添加背景

#import the imageimg.file <- system.file(file.path("images", "background-image.png"), package = "ggpubr")
img <- png::readPNG(img.file)

利用ggpubr::background_image()為ggplot圖形添加背景圖

library(ggplot2)
library(ggpubr)
ggplot(iris, aes(Species,Sepal.Length))+
background_image(img)+
geom_boxplot(aes(fill=Species), color="white")+ fill_palette("jco")

修改透明度

ggplot(iris, aes(Species,Sepal.Length))+
background_image(img)+geom_boxplot(aes(fill=Species), color="white", alpha=0.5)+ 
fill_palette("jco")

多頁排列

日常工作中我們有時(shí)要繪制許多圖,假如我們有16幅圖石景,每頁排列4張的話就需要4頁才能排完劈猿,而ggpubr::ggarrange()可以通過制定行列數(shù)自動(dòng)在多頁之間進(jìn)行圖形排列

multi.page <-ggarrange(bxp, dp, bp, sp, nrow = 1, ncol = 2)

上述代碼返回兩頁每頁兩圖

multi.page[[1]]
multi.page[[2]]

利用ggarrange()嵌套布局

p1 <- ggarrange(sp, bp+font("x.text", size = 9), ncol = 1, nrow = 2)
p2 <- ggarrange(density.p, stable.p, text.p, ncol = 1, nrow = 3, 
heights = c(1, 0.5, 0.3))
ggarrange(p1, p2, ncol = 2, nrow = 1)

SessionInfo

sessionInfo()
## R version 3.4.1 (2017-06-30)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 15063)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936 
## [2] LC_CTYPE=Chinese (Simplified)_China.936 
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C
## [5] LC_TIME=Chinese (Simplified)_China.936 
## 
## attached base packages:
## [1] grid stats graphics grDevices utils datasets methods 
## [8] base 
## 
## other attached packages:
## [1] survminer_0.4.0 survival_2.41-3 ggpubr_0.1.5 magrittr_1.5 
## [5] cowplot_0.8.0 ggplot2_2.2.1 gridExtra_2.2.1
## 
## loaded via a namespace (and not attached):
## [1] zoo_1.8-0 purrr_0.2.3 reshape2_1.4.2 
## [4] splines_3.4.1 lattice_0.20-35 colorspace_1.3-2 
## [7] htmltools_0.3.6 yaml_2.1.14 survMisc_0.5.4
## [10] rlang_0.1.2 foreign_0.8-69 glue_1.1.1 
## [13] bindrcpp_0.2 bindr_0.1 plyr_1.8.4 
## [16] stringr_1.2.0 munsell_0.4.3 gtable_0.2.0 
## [19] ggsci_2.7 psych_1.7.5 evaluate_0.10.1 
## [22] labeling_0.3 knitr_1.17 parallel_3.4.1 
## [25] broom_0.4.2 Rcpp_0.12.12 xtable_1.8-2 
## [28] scales_0.4.1 backports_1.1.0 cmprsk_2.2-7 
## [31] km.ci_0.5-2 mnormt_1.5-5 png_0.1-7 
## [34] digest_0.6.12 stringi_1.1.5 dplyr_0.7.2 
## [37] KMsurv_0.1-5 rprojroot_1.2 tools_3.4.1 
## [40] lazyeval_0.2.0 tibble_1.3.3 tidyr_0.7.0 
## [43] pkgconfig_2.0.1 Matrix_1.2-11 data.table_1.10.4
## [46] assertthat_0.2.0 rmarkdown_1.6 R6_2.2.2 
## [49] nlme_3.1-131 compiler_3.4.1
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市潮孽,隨后出現(xiàn)的幾起案子揪荣,更是在濱河造成了極大的恐慌,老刑警劉巖往史,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仗颈,死亡現(xiàn)場離奇詭異,居然都是意外死亡椎例,警方通過查閱死者的電腦和手機(jī)挨决,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來粟矿,“玉大人,你說我怎么就攤上這事损拢∧按猓” “怎么了?”我有些...
    開封第一講書人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵福压,是天一觀的道長掏秩。 經(jīng)常有香客問我或舞,道長,這世上最難降的妖魔是什么蒙幻? 我笑而不...
    開封第一講書人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任映凳,我火速辦了婚禮,結(jié)果婚禮上邮破,老公的妹妹穿的比我還像新娘诈豌。我一直安慰自己,他們只是感情好抒和,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開白布矫渔。 她就那樣靜靜地躺著,像睡著了一般摧莽。 火紅的嫁衣襯著肌膚如雪庙洼。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評(píng)論 1 308
  • 那天镊辕,我揣著相機(jī)與錄音油够,去河邊找鬼。 笑死征懈,一個(gè)胖子當(dāng)著我的面吹牛石咬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播受裹,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼碌补,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了棉饶?” 一聲冷哼從身側(cè)響起厦章,我...
    開封第一講書人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎照藻,沒想到半個(gè)月后袜啃,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡幸缕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年群发,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片发乔。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡熟妓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出栏尚,到底是詐尸還是另有隱情起愈,我是刑警寧澤,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站抬虽,受9級(jí)特大地震影響官觅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜阐污,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一休涤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧笛辟,春花似錦功氨、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至弯菊,卻和暖如春纵势,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背管钳。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來泰國打工钦铁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人才漆。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓牛曹,卻偏偏與公主長得像,于是被迫代替她去往敵國和親醇滥。 傳聞我的和親對(duì)象是個(gè)殘疾皇子黎比,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 簡介 文章較長,點(diǎn)擊直達(dá)我的博客鸳玩,瀏覽效果更好阅虫。本文內(nèi)容基本是來源于STHDA,這是一份十分詳細(xì)的ggplot2使...
    taoyan閱讀 51,195評(píng)論 7 159
  • Matplotlib 入門教程 來源:Introduction to Matplotlib and basic l...
    布客飛龍閱讀 31,808評(píng)論 5 162
  • 一不跟、 這是今天的晚飯颓帝,蛋炒飯。 大寶看到這圖片窝革,感嘆:這賣相可以啊购城,你終于學(xué)會(huì)擺拍了。 我說:哼虐译,我那是懶得擺拍瘪板,...
    冰小喵的貓糧閱讀 381評(píng)論 0 2
  • 01 吃過不少桑椹,但真沒吃過像昨天那么甜的桑椹漆诽。 昨天應(yīng)一個(gè)朋友的邀請(qǐng)侮攀,去另一朋友家玩史侣。因?yàn)槟抢镉猩接兴液芟?..
    西瓜甜甜啦閱讀 883評(píng)論 34 18