geotics
geotics

Reputation: 61

Combining a ggplot and plotRGB in one PNG plot

I am trying to combine a ggplot result and a plotRGB of a spatial raster into one plot and write it to PNG. I have already found how to combine ggplots or do a multiplot but this specific setup I do not know how to get to work. This code is also integrated in a for-loop, which means that a print statement needs to be used to actually plot the ggplot (in either PNG or Rstudio).

library(raster)
library(ggplot2)

plotRGB(brick(raster(matrix(rnorm(10000),ncol=100)),
              raster(matrix(rnorm(10000),ncol=100)),
              raster(matrix(rnorm(10000),ncol=100))),r=1,g=2,b=3,stretch="lin")
ggdata=data.frame("x"=seq(100),"y"=rnorm(100))
ggplot(ggdata,aes(x=x,y=y))+
  geom_line()

Does anyone of you know how to combine these two into a PNG (favorably shown in a for-loop, but not necessary)?

Upvotes: 1

Views: 869

Answers (1)

inscaven
inscaven

Reputation: 2584

As plotRGB is using base graphics and ggplot2 is using grid graphics, to combine them we can use gridBase package. This code seems to work

require("raster")
require("ggplot2")
require("gridBase")
require("grid")
require("gridExtra")

png("gg.png", width = 600, height = 1200)

grid.newpage()
pushViewport(viewport(width=1, height=0.5, y = .75))
par(omi=gridOMI())
par(mfrow=c(2, 2), mfg=c(1, 1), mar=c(3, 3, 1, 0))
for (i in 1:3) {
  plotRGB(brick(raster(matrix(rnorm(10000),ncol=100)),
                raster(matrix(rnorm(10000),ncol=100)),
                raster(matrix(rnorm(10000),ncol=100))),r=1,g=2,b=3,stretch="lin")
}
upViewport()

pushViewport(viewport(width=1, height=0.5, y = .25))
ggdata=data.frame("x"=seq(100),"y"=rnorm(100))
grid.draw(ggplotGrob(
  ggplot(ggdata,aes(x=x,y=y))+
    geom_line() ))
upViewport()
dev.off()

This produces following png: enter image description here

I advise you to get familiar with the documentation of used packages to be able to draw what you need in the way you want :)

Upvotes: 5

Related Questions