与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 关注
- 839 浏览
添加回答
举报
0/150
提交
取消
