R把传统的情节和ggplot2放在一起

时间:2014-02-18 13:30:23

标签: r plot ggplot2

我有两张图,一张用ggplot2绘制的地图,如下所示:

w<-ggplot()+
  geom_polygon(data=dep_shp.df, aes(x=long,y=lat,group=group,fill=classJenks))+

  #   scale_fill_gradient(limits=c(40, 100))+
  labs(title ="Classification de la proportion de producteurs par départements
       \n par la methode de jenks (2008)")+
  theme_bw()+
  coord_equal()

和来自classIntervals库的classInt类型对象的图表。

我想将这两张图组合在一起。我试过了:

vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))

#creation
print(u, vp = vplayout(1, 1))
print(v, vp = vplayout(1, 2))

grid.arrange

的内容
grid.arrange(plot1, plot2, ncol=2)

但这些都不起作用。

1 个答案:

答案 0 :(得分:14)

gridBase vignetteEmbedding base graphics plots in grid viewports部分介绍了该方法。

gridBase包中包含为基本绘图区域绘制合理参数的函数。所以我们需要这些包:

library(grid)
library(ggplot2)
library(gridBase)

这是一个例子ggplot:

a_ggplot <- ggplot(cars, aes(speed, dist)) + geom_point()

诀窍似乎是在设置plot.new之前调用par,否则可能会混淆并且无法正确设置。您还需要设置new = TRUE,以便在致电plot时不会启动新页面。

#Create figure window and layout
plot.new()
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))

#Draw ggplot
pushViewport(viewport(layout.pos.col = 1))
print(a_ggplot, newpage = FALSE)
popViewport()

#Draw bsae plot
pushViewport(viewport(layout.pos.col = 2))
par(fig = gridFIG(), new = TRUE)
with(cars, plot(speed, dist))
popViewport()