R如何结合传统绘图和ggplot2?

8

我有两个图表,一个是使用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()

并使用classInt库中的classIntervals对象类型绘制图形。

我想将这2个图形放在一起。 我已经尝试过:

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)

但是这些都不起作用。

4
这有帮助吗?https://dev59.com/yWYq5IYBdhLWcg3w4EZx - rawr
是的!!! 太棒了,谢谢!! - delaye
1个回答

17

该方法在gridBase文档将基础图形绘制嵌入网格视口部分中进行描述。

gridBase软件包包含一些函数用于为基础图形绘制的绘图区域设置合理的参数。因此,我们需要这些软件包:

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

这是一个ggplot的示例:

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

诀窍似乎是在设置par之前调用plot.new,否则它可能会混淆并未正确地遵守设置。您还需要设置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()

什么是gridFIG()? - Antoni
1
@Antoni 它将基础绘图区域的坐标与当前网格视口对齐。请参阅?gridBase::gridFIG - Richie Cotton
我认为不需要使用 grid.newpage()。当使用 png 保存绘图时,它会生成两个 png 文件,一个是空白的,另一个是所需的输出。当删除 grid.newpage() 后,只会创建一个文件。 - Erick Chacon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接