與ggplot 2并排的地塊我想將兩個情節(jié)并排放置在ggplot 2軟件包,即相當(dāng)于par(mfrow=c(1,2)).例如,我希望下面的兩個情節(jié)以相同的規(guī)模并排展示。x <- rnorm(100)eps <- rnorm(100,0,.2)qplot(x,3*x+eps)qplot(x,2*x+eps)我需要把它們放在同一個數(shù)據(jù)幀中嗎?qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()
2 回答

喵喵時光機(jī)
TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個贊
并排(或網(wǎng)格上的n塊)
功能grid.arrange()
在gridExtra
包將合并多個情節(jié);這是如何將兩個并排放置。
require(gridExtra)plot1?<-?qplot(1)plot2?<-?qplot(1)grid.arrange(plot1,?plot2,?ncol=2)
當(dāng)這兩幅圖不是基于相同的數(shù)據(jù)時,這是非常有用的,例如,如果您想要繪制不同的變量而不使用RESTPE()。
這將把輸出繪制成一個副作用。若要將副作用打印到文件,請指定設(shè)備驅(qū)動程序(如pdf
,?png
等),例如。
pdf("foo.pdf")grid.arrange(plot1,?plot2)dev.off()
或者,使用arrangeGrob()
結(jié)合在一起ggsave()
,
ggsave("foo.pdf",?arrangeGrob(plot1,?plot2))
這相當(dāng)于使用par(mfrow = c(1,2))
..這不僅節(jié)省了整理數(shù)據(jù)的時間,而且當(dāng)你想要兩個不同的情節(jié)時,這也是必要的。
附錄:使用面
面有助于為不同的群體制作相似的情節(jié)。下面的許多答案都指出了這一點(diǎn),但我想用相當(dāng)于上述情節(jié)的例子來強(qiáng)調(diào)這一方法。
mydata?<-?data.frame(myGroup?=?c('a',?'b'),?myX?=?c(1,1))qplot(data?=?mydata,? ????x?=?myX,? ????facets?=?~myGroup)ggplot(data?=?mydata)?+? ????geom_bar(aes(myX))?+? ????facet_wrap(~myGroup)

呼如林
TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個贊
multiplot
multiplot(plot1, plot2, cols=2)
multiplot <- function(..., plotlist=NULL, cols) { require(grid) # Make a list from the ... arguments and plotlist plots <- c(list(...), plotlist) numPlots = length(plots) # Make the panel plotCols = cols # Number of columns of plots plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols # Set up the page grid.newpage() pushViewport(viewport(layout = grid.layout(plotRows, plotCols))) vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y) # Make each plot, in the correct location for (i in 1:numPlots) { curRow = ceiling(i/plotCols) curCol = (i-1) %% plotCols + 1 print(plots[[i]], vp = vplayout(curRow, curCol )) }}
- 2 回答
- 0 關(guān)注
- 780 瀏覽
添加回答
舉報(bào)
0/150
提交
取消