2014-03-31 35 views
2

我想把一個boxplot放在直方圖的下面。我已經想出瞭如何做到這一點,但boxplot和直方圖是相同的大小,我想減少boxplot。 當我減小寬度時,邊緣的空間保持不變。但是,我想減小整個事物的寬度。如何用ggplot2減少從boxplot到edge的空間?

這是我到目前爲止有:

library(ggplot2) 
h = ggplot(mtcars, aes(x=hp)) + 
    geom_histogram(aes(y = ..density..)) + 
    scale_x_continuous(breaks=c(100, 200, 300), limits=c(0,400)) + 
    geom_density(, linetype="dotted") 

b <- ggplot(mtcars,aes(x=factor(0),hp))+geom_boxplot(width=0.1) + 
    coord_flip(ylim=c(0,400)) + 
    scale_y_continuous(breaks=c(100, 200, 300)) + 
    theme(axis.title.y=element_blank(), 
    axis.text.y=element_blank(), 
    axis.ticks.y=element_blank()) 

library(gridExtra) 
plots <- list(h, b) 
grobs <- list() 
widths <- list() 
for (i in 1:length(plots)){ 
    grobs[[i]] <- ggplotGrob(plots[[i]]) 
    widths[[i]] <- grobs[[i]]$widths[2:5] 
} 
maxwidth <- do.call(grid::unit.pmax, widths) 
for (i in 1:length(grobs)){ 
    grobs[[i]]$widths[2:5] <- as.list(maxwidth) 
} 
do.call("grid.arrange", c(grobs, ncol=1)) 

hist+boxplot

編輯:
如果我使用grid.arrange()像這樣:

grid.arrange(heights=c(4,1), h, b) 

enter image description here

比例都酷似我想它,但我無法弄清楚如何調整面,使得軸再次對準我的第一個例子。

有人嗎?

+0

看看:http://stackoverflow.com/questions/16148076/altering-height-of-rows-produced-by-grid-arrange-when-nrow-1 – hrbrmstr

+0

謝謝,但沒有按看起來不像我以後。如果你指的是grid.arrange的高度選項,你能否告訴我如何相應地調整我的示例。我迄今爲止的所有嘗試都失敗了。 – jhscheer

+0

+1這樣一個很好的可重現的問題,幾乎包括那裏的嘗試。 – Gregor

回答

1

您只需在grid.arrange調用中使用寬度校正的grobs,而不是原始圖。

grid.arrange(heights = c(4, 1), grobs[[1]], grobs[[2]]) 
+0

這樣做,謝謝! – jhscheer