與ggplot 2并排的地塊我想將兩個情節并排放置在ggplot 2軟件包,即相當于par(mfrow=c(1,2)).例如,我希望下面的兩個情節以相同的規模并排展示。x <- rnorm(100)eps <- rnorm(100,0,.2)qplot(x,3*x+eps)qplot(x,2*x+eps)我需要把它們放在同一個數據幀中嗎?qplot(displ, hwy, data=mpg, facets = . ~ year) + geom_smooth()
2 回答
喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
并排(或網格上的n塊)
功能grid.arrange()在gridExtra包將合并多個情節;這是如何將兩個并排放置。
require(gridExtra)plot1?<-?qplot(1)plot2?<-?qplot(1)grid.arrange(plot1,?plot2,?ncol=2)
當這兩幅圖不是基于相同的數據時,這是非常有用的,例如,如果您想要繪制不同的變量而不使用RESTPE()。
這將把輸出繪制成一個副作用。若要將副作用打印到文件,請指定設備驅動程序(如pdf,?png等),例如。
pdf("foo.pdf")grid.arrange(plot1,?plot2)dev.off()或者,使用arrangeGrob()結合在一起ggsave(),
ggsave("foo.pdf",?arrangeGrob(plot1,?plot2))這相當于使用par(mfrow = c(1,2))..這不僅節省了整理數據的時間,而且當你想要兩個不同的情節時,這也是必要的。
附錄:使用面
面有助于為不同的群體制作相似的情節。下面的許多答案都指出了這一點,但我想用相當于上述情節的例子來強調這一方法。
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貢獻1798條經驗 獲得超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 關注
- 790 瀏覽
添加回答
舉報
0/150
提交
取消
