2017-03-29 12 views
0

我想這兩個圖形結合起來:智能協會 - GGPLOT2

p1 <- ggplot(iris, aes(Sepal.Length)) + 
    geom_density() + 
    facet_wrap(~ Species) 

p2 <- ggplot(iris, aes(Sepal.Length)) + 
    geom_density() 

結合起來,我做的:

multiplot(p1, p2, cols = 2) 

但它不是所需的形狀。

我想圖p2具有與其他尺寸相同的尺寸,並位於最後一個分面圖旁邊。

感謝您的幫助

+0

'facet_grid(〜Species,margins = TRUE)'將在這裏工作。但對於一般情況來說,這並不容易。 'cowplot'軟件包會對齊,但不能對齊多面和非多面的圖。 – Axeman

回答

0

不知道這是否適用於你一般情況下,但facet_grid代替facet_wrap,您可以使用margins參數:

library(ggplot2) 

ggplot(iris, aes(Sepal.Length)) + 
    geom_density() + 
    facet_grid(. ~ Species, margins = T) 

如果您問題更爲普遍,答案可能在於grid.arrange
喜歡的東西,這可能是一個開始:

library(gridExtra) 

grid.arrange(arrangeGrob(p1, p2, 
         widths = c(3,1), 
         heights = c(1,20), 
         layout_matrix = matrix(c(1,1,NA,2),2))) 

正如你可以看到有幾個問題(不同軸,頂板條),但與grid工作能得到迅速複雜化。

0

此代碼應工作:

p1 <- ggplot(iris, aes(Sepal.Length)) + 
     geom_density() + 
     ylim(limits = c(0, 1.25))+ 
     facet_wrap(~ Species) 

p2 <- ggplot(iris, aes(Sepal.Length)) + 
     geom_density() + 
     ggtitle("") + # ad empty title as place holder 
     labs(y = "", x = "") + # hide axis labels 
     ylim(limits = c(0, 1.25)) + # y axis values should be fixed in both plots 
     coord_fixed(ratio=20/1) + # ratio of x- and y-axis to reduce width of plot 
     theme(axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.line.y = element_blank(), 
     plot.margin=unit(c(0,0,0.65,-10), "lines")) # margin between plots = "0.65" 

我擺弄了一下,只是用不同的造型選擇,產生這種結果。如果你有比這更多的情節,我會建議爲所有人使用一個主題。

,你已經在使用

multiplot(p1, p2, cols = 2) 

您可以使用該功能的multiplot或您安裝的軟件包gridExtra和電網,並使用一個:

grid.arrange(p1, p2, ncol=2) 

希望這有助於!