2016-06-01 167 views
0

我嘗試在R中使用ggplot2來做這樣的繪圖嗎?檢查下圖中的面板g,h j,l或m。所以一個散點圖在主圖旁邊有箱形圖。我想在這裏介紹的方法,但它並沒有在所有http://www.r-bloggers.com/scatterplot-with-marginal-boxplots/工作...R散點圖,與x軸和y軸相鄰的盒圖

FYI這個數字是從這篇文章:http://www.ncbi.nlm.nih.gov/pubmed/26437030

謝謝 enter image description here

+1

請發佈一些數據,你究竟沒有工作,試圖沿着代碼。 – beetroot

+0

我發現我的錯誤。我在網格包中遇到了問題。我將發佈我的功能作爲答案。 –

+1

@NicoBxl cowplot做得很好。從你的答案使用情節。 (p2,0,0,0,width = 0.2,height = 0.8)+ draw_plot()+ draw_plot(p1,0.2,0,width = 0.8,height = 0.8)+ draw_plot寬度= 0.8,高度= 0.2) – timcdlucas

回答

2

這裏是我的解決方案。我只是不知道如何將y boxplot放在圖的左邊,而不是右邊。我想我必須改變gtable_add_grob參數。

library(ggplot2) 
library(gtable) 
library(grid) 

a.x <- rnorm(20,5,1) 
a.y <- rnorm(20,10,2) 
b.x <- rnorm(10,20,2) 
b.y <- rnorm(10,5,2) 
x <- data.frame(x=c(a.x,b.x),y=c(a.y,b.y),col=c(rep("A",20),rep("B",10))) 

p1 <- ggplot(x,aes(x=x,y=y))+geom_point(aes(color=col))+stat_smooth(method = "lm",se=F,colour="black",linetype=2,size=0.5)+theme_bw()+theme(legend.position="none") 
p2 <- ggplot(x,aes(x=col,y=y,color=col))+geom_boxplot()+theme_bw()+theme(legend.position="none",axis.ticks.y=element_blank(),axis.title.y=element_blank(),axis.text.y=element_blank()) 
p3 <- ggplot(x,aes(x=col,y=x,color=col))+geom_boxplot()+coord_flip()+theme_bw()+theme(legend.position="none",axis.ticks.x=element_blank(),axis.title.x=element_blank(),axis.text.x=element_blank()) 

gt1 <- ggplot_gtable(ggplot_build(p1)) 
gt2 <- ggplot_gtable(ggplot_build(p2)) 
gt3 <- ggplot_gtable(ggplot_build(p3)) 

maxWidth <- unit.pmax(gt1$widths[2:3], gt2$widths[2:3]) 
maxHeight <- unit.pmax(gt1$heights[4:5], gt3$heights[4:5]) 


gt1$widths[2:3] <- as.list(maxWidth) 
gt2$widths[2:3] <- as.list(maxWidth) 

gt1$heights[4:5] <- as.list(maxHeight) 
gt3$heights[4:5] <- as.list(maxHeight) 

gt <- gtable(widths = unit(c(4, 1), "null"), height = unit(c(1, 4), "null")) 

gt <- gtable_add_grob(gt, gt1, 2, 1) 
gt <- gtable_add_grob(gt, gt2, 2, 2) 
gt <- gtable_add_grob(gt, gt3, 1, 1) 


grid.newpage() 
grid.draw(gt) 

而結果:

enter image description here