3

I have been using the Rayshader package in R in conjunction with RStudio and have been producing some nice 2D and 3D images.

I usually export images directly from the RStudio viewing panel using the drop down box and then by selecting the format required i.e. pdf or png. This seems to work fine for the 2D images produced by the Rayshader plot_map() function.

However, for the plot_3d() function the image appears in a rgl viewer for a few seconds before disappearing and then re-appearing in the RStudio viewing panel. The image within the viewing panel is rather small and then when I try to export the image as above they are of quite poor quality.

The render_snapshot() function is meant to be able to save a file but I have not been able to get that to work so far. Any help appreciated.

So does anybody have any suggestions for how I would go about saving very high quality images produced by Rayshader directly to my working directory?

My code I have been using so far is below.

library(dplyr)
library(ggplot2)
library(raster)
library(rgdal)
library(scales)
library(rgeos)
library(sp)
library(ggspatial)
library(sf)
library(rayshader)

dem1<- getData("SRTM",lat=34.5,lon=33)
dem2<- getData("SRTM",lat=34.5,lon=36)
dem3<- getData("SRTM",lat=36,lon=33)
dem4<- getData("SRTM",lat=36,lon=36)
dem <- merge(dem1,dem2, dem3, dem4)

#Create polygon to crop the elevation data file   
Ps1 = as(extent(34.5, 35, 31.5, 32), 'SpatialPolygons')
crs(Ps1) = "+proj=longlat +datum=WGS84 +no_defs"
#crop the elevation data using the polygon
dem = crop(dem, Ps1, snap= 'out')

#Create input matrix for Rayshader plot
elev_matrix <- matrix(
  raster::extract(dem, raster::extent(dem), buffer = 1000), 
  nrow = ncol(dem), ncol = nrow(dem)
)
elev_matrix[is.na(elev_matrix)] = 0

#Produce 3D map - remember that the y axis for render_label is in -ve direction
elev_matrix %>%
  sphere_shade(texture = "imhof2") %>%
  add_water(detect_water(elev_matrix), color = "desert") %>%
  add_shadow(ray_shade(elev_matrix, zscale = 3), 0.5) %>%
  add_shadow(ambient_shade(elev_matrix), 0) %>%
  plot_3d(elev_matrix, zscale = 30, fov = 0, theta = 335, zoom = 0.75, phi = 25, windowsize = c(10000, 10000))
Sys.sleep(0.2)
render_snapshot(clear = TRUE)
RJF
  • 41
  • 2

1 Answers1

3

You need to add a parameter stating the file path and name of the output image in render_snapshot().

render_snapshot("FILENAME.png", clear = TRUE)

Meanwhile, the resolution of the image rendered by the function is limited by the resolution of your monitor. It is a currently known limitation.

Increase resolution of R rayshader image

wkth
  • 107
  • 1
  • 9