I've plotted multiple rasters into a matrix grid and I'd like to save the plot into a specified folder in my directory. My plots are for a poster presentation at a conference and the images need to be really sharp with a resolution of 600.
I know how to save ggplot objects, but I can't figure out how to save this images with this configuration of R code.
When I run my code for the function jpeg
, I get this warning message:
Warning message:
In jpeg("Raster_Layers.jpg", quality = 100, units = "px", bg = "white", :
NAs introduced by coercion
Code:
#Create an empty raster to plot the rasters
r <- raster(ncols=3, nrows=2, xmn=1, xmx=6, ymn=1, ymx=6)
r1 <- r2 <- r3 <- r4 <- r5 <- r6 <- setValues(r, rnorm(ncell(r)))
#Bind the rasters together in a matrix grid layout of three columns and 2 rows
m <- rbind(c(1, 2, 3), c(4, 5, 6))
layout(m)
#Select the name the raster layer plot and specifiy to store it in the output folder
jpeg('Raster_Layers.jpg',
quality = 100,
units = "px",
bg="white",
res=600,
height=437,
width=760,
file = "/Users/Output")
#Plot the rasters (2 rows by 3 columns) into the grid
plot(resampled_sss, main = "Mean Sea Surface Salinity (kg/m3)")
plot(resampled_sst, main = "Mean Sea Surface Temperature (°C)")
plot(resampled_chla, main = "Mean Chlorphyll-a (kg/m3)")
plot(depth, main = "Depth (m)")
plot(slope, col=rev(map.pal("viridis",100)), main="Slope (degrees°)")
plot(rugosity, col=rainbow(50), main="Rugosity (degrees°)")
dev.off()
When I try and run my code for the function png, I get this error message
#Create an empty raster to plot the rasters
r <- raster(ncols=3, nrows=2, xmn=1, xmx=6, ymn=1, ymx=6)
r1 <- r2 <- r3 <- r4 <- r5 <- r6 <- setValues(r, rnorm(ncell(r)))
#Bind the rasters together in a grid layout of three columns and 2 rows
m <- rbind(c(1, 2, 3), c(4, 5, 6))
layout(m)
options(X11.options = c("-dpi", "600"))
#Select the name the raster layer plot and specifiy to store it in the output folder
png(file = "Raster_Layers.jpg",
name.opt = ".X11.Options",
envir = .X11env,
quality = 100,
units = "px",
bg="white",
type = "quartz",
res=600,
height=437,
width=760)
Error Message:
Error: object '.X11env' not found
Screenshot of my Plotted Raster Layers:
Move the layout definition after png device is created, like:
library(raster)
#> Loading required package: sp
r <- raster(ncols=3, nrows=2, xmn=1, xmx=6, ymn=1, ymx=6)
r1 <- r2 <- r3 <- r4 <- r5 <- r6 <- setValues(r, rnorm(ncell(r)))
#Select the name the raster layer plot and specifiy to store it in the output folder
png(file = '~/Raster_Layers.png',
units = "px",
bg="white",
res=600,
height=3000,
width=4000)
layout(matrix(c(1,2,3,4,5,6), 2, 3, byrow=T))
plot(r1)
plot(r2)
plot(r3)
plot(r4)
plot(r5)
plot(r6)
dev.off()
#> png
#> 2
And the created image:
Or use stack:
png(file = '~/Raster_Layers.png',
units = "px",
bg="white",
res=600,
height=2000,
width=4000)
t <- stack(r1, r2, r3, r4, r5, r6)
plot(t, nc = 3, nr = 2)
dev.off()
Created on 2024-10-24 with reprex v2.1.0