### Install rayshader from GitHub Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Use devtools to install the latest development version of rayshader. ```r # To install the latest version from Github: # install.packages("devtools") devtools::install_github("tylermorganwall/rayshader") ``` -------------------------------- ### Install Ubuntu System Dependencies Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Required system libraries for rayshader on Ubuntu systems. ```bash libpng-dev libjpeg-dev libfreetype6-dev libglu1-mesa-dev libgl1-mesa-dev pandoc zlib1g-dev libicu-dev libgdal-dev gdal-bin libgeos-dev libproj-dev ``` -------------------------------- ### Install package from GitHub Source: https://github.com/tylermorganwall/rayshader/blob/master/CONTRIBUTING.md Use this command to update the package to the latest version from the repository. ```R remotes::install_github("tylermorganwall/{package name}") ``` -------------------------------- ### High-Quality Rendering with Labels Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Renders a high-quality 3D map incorporating labels. Adjusts text size and offset for better visibility. Requires prior setup of the 3D scene. ```r render_highquality( samples = 16, line_radius = 1, text_size = 36, text_offset = c(0, 12, 0), clear = TRUE ) ``` -------------------------------- ### Snapshot Rendering Options Source: https://context7.com/tylermorganwall/rayshader/llms.txt Demonstrates applying a vignette effect and software-based rendering for snapshots. ```r # With vignette effect render_camera(zoom = 0.8) render_snapshot(title_text = "Monterey Bay, California", title_color = "white", title_bar_color = "darkgreen", vignette = TRUE) # Software rendering (no OpenGL required) render_snapshot(software_render = TRUE, width = 1920, height = 1080) ``` -------------------------------- ### Retrieve system information Source: https://github.com/tylermorganwall/rayshader/blob/master/CONTRIBUTING.md Include this output in bug reports to provide environment context. ```R Sys.info() ``` -------------------------------- ### Basic Elevation-to-Color Mapping with height_shade Source: https://context7.com/tylermorganwall/rayshader/llms.txt Creates a direct mapping of elevation to color using a default color palette. Useful for visualizing topography or bathymetry. ```r # Default terrain colors montereybay |> height_shade() |> plot_map() ``` -------------------------------- ### Load and visualize raster data Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Initializes a map from a raster file and displays it using sphere shading. ```r library(rayshader) #Here, I load a map with the raster package. loadzip = tempfile() download.file("https://tylermw.com/data/dem_01.tif.zip", loadzip) localtif = raster::raster(unzip(loadzip, "dem_01.tif")) unlink(loadzip) #And convert it to a matrix: elmat = raster_to_matrix(localtif) #We use another one of rayshader's built-in textures: elmat |> sphere_shade(texture = "desert") |> plot_map() ``` -------------------------------- ### Basic Hillshade with sphere_shade Source: https://context7.com/tylermorganwall/rayshader/llms.txt Generates a basic hillshade using the default 'imhof1' palette. Requires the rayshader library and elevation data in a matrix format. ```r library(rayshader) # Basic hillshade with default imhof1 palette montereybay |> sphere_shade() |> plot_map() ``` -------------------------------- ### Render Snapshots Source: https://context7.com/tylermorganwall/rayshader/llms.txt Capture the current rgl view to a file or display with optional title and vignette effects. ```r # Basic snapshot render_snapshot() # Save to file render_snapshot(filename = "monterey_bay.png") # With title bar render_snapshot(title_text = "Monterey Bay, California", title_offset = c(0, 20), title_color = "white", title_bar_color = "black", title_font = "Helvetica") ``` -------------------------------- ### Render location with realistic sky models Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Uses the skymodelr package to simulate sun direction and atmosphere based on latitude, longitude, and time. ```r elmat_lat_long = c(-42.745792, 147.171103) render_highquality( samples = 16, lat = elmat_lat_long[1], long = elmat_lat_long[2], iso = 5, clamp_value = 1000, datetime = as.POSIXct("2025-06-21 15:00:00", tz = "Australia/Sydney"), sky_args = list(hosek = FALSE), width=1000, height=800 ) ``` ```r render_highquality( samples = 16, lat = elmat_lat_long[1], long = elmat_lat_long[2], iso = 5, clamp_value = 1000, datetime = as.POSIXct("2025-06-21 12:00:00", tz = "Australia/Sydney"), sky_args = list(hosek = FALSE), width=1000, height=800 ) ``` -------------------------------- ### Create and Save 3D Movie Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Creates and saves an MP4 or GIF file of the camera rotating around the 3D scene. Supports built-in orbits or user-provided paths. ```R render_movie(filename = "animation.gif", fps = 30) ``` -------------------------------- ### Add procedural clouds Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Generates and renders cloud layers over 3D maps with customizable parameters. ```r elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "lightblue") |> add_shadow( cloud_shade( elmat, zscale = 10, start_altitude = 500, end_altitude = 1000, ), 0 ) |> plot_3d( elmat, zscale = 10, fov = 0, theta = 135, zoom = 0.75, phi = 45, windowsize = c(1000, 800), background = "darkred" ) render_camera(theta = 20, phi = 40, zoom = 0.64, fov = 56) render_clouds( elmat, zscale = 10, start_altitude = 800, end_altitude = 1000, attenuation_coef = 5, sun_altitude = 10, clear_clouds = T ) render_snapshot(clear = TRUE) ``` ```r rgl::rgl.clear() ``` ```r elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "lightblue") |> add_shadow( cloud_shade( elmat, zscale = 10, start_altitude = 500, end_altitude = 700, sun_altitude = 45, attenuation_coef = 2, offset_y = 300, cloud_cover = 0.55, frequency = 0.01, scale_y = 3, fractal_levels = 32 ), 0 ) |> plot_3d( elmat, zscale = 10, fov = 0, theta = 135, zoom = 0.75, phi = 45, windowsize = c(1000, 800), background = "darkred" ) render_camera(theta = 125, phi = 22, zoom = 0.47, fov = 60) render_clouds( elmat, zscale = 10, start_altitude = 500, end_altitude = 700, sun_altitude = 45, attenuation_coef = 2, offset_y = 300, cloud_cover = 0.55, frequency = 0.01, scale_y = 3, fractal_levels = 32, clear_clouds = T ) render_snapshot(clear = TRUE) ``` -------------------------------- ### render_snapshot Source: https://context7.com/tylermorganwall/rayshader/llms.txt Captures the current rgl view and displays or saves to disk with optional title and vignette effects. ```APIDOC ## render_snapshot ### Description Captures the current rgl view and displays or saves to disk with optional title and vignette effects. ### Parameters - **filename** (string) - Optional - Path to save the image. - **title_text** (string) - Optional - Title to overlay on the snapshot. ``` -------------------------------- ### Create 3D Map Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Creates a 3D map from a texture and an elevation matrix. Allows customization of map appearance and water level. ```R plot_3d(texture_matrix, elevation_matrix, water_level = 0.5) ``` -------------------------------- ### Export 3D Models with save_obj Source: https://context7.com/tylermorganwall/rayshader/llms.txt Saves visualizations to Wavefront OBJ format. Includes options for texture, water refraction, and manifold geometry. ```r # Basic OBJ export volcano |> sphere_shade() |> plot_3d(volcano, zscale = 2) save_obj("volcano_model.obj") # Without texture save_obj("volcano_notex.obj", save_texture = FALSE) # With water and realistic refraction montereybay |> sphere_shade() |> plot_3d(montereybay, zscale = 50, water = TRUE) save_obj("monterey_model.obj", water_index_refraction = 1.33) # Manifold geometry for 3D printing save_obj("printable_model.obj", manifold_geometry = TRUE) ``` -------------------------------- ### Basic Ambient Occlusion with ambient_shade Source: https://context7.com/tylermorganwall/rayshader/llms.txt Calculates an ambient occlusion shadow map, which darkens valleys and areas with less light. This function simulates indirect lighting. ```r # Basic ambient occlusion montereybay |> ambient_shade() |> plot_map() ``` -------------------------------- ### Render 3D maps Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Converts a 2D matrix into a 3D visualization with camera and snapshot controls. ```r elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "desert") |> add_shadow(ray_shade(elmat, zscale = 3), 0.3) |> add_shadow(ambient_shade(elmat), 0) |> plot_3d( elmat, zscale = 10, fov = 0, theta = 135, zoom = 0.75, phi = 45, windowsize = c(1000, 800) ) Sys.sleep(0.2) render_snapshot() ``` -------------------------------- ### Add Map Overlays Source: https://context7.com/tylermorganwall/rayshader/llms.txt Apply 3 or 4-layer RGB/RGBA arrays to maps with optional transparency settings. ```r # Generate and add altitude-based overlay bathy_hs = height_shade(montereybay, texture = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200)) montereybay |> sphere_shade(zscale = 10) |> add_overlay(generate_altitude_overlay(bathy_hs, montereybay, 0, 0)) |> add_shadow(ray_shade(montereybay, zscale = 50), 0.3) |> plot_map() # Add with custom transparency montereybay |> sphere_shade() |> add_overlay(bathy_hs, alphalayer = 0.6) |> plot_map() ``` -------------------------------- ### ray_shade with Soft Shadows Source: https://context7.com/tylermorganwall/rayshader/llms.txt Creates softer shadows by adjusting the 'anglebreaks' parameter, effectively widening the light source. This requires careful tuning of the sequence. ```r # Create soft shadows with wider light source montereybay |> ray_shade(zscale = 50, anglebreaks = seq(30, 50, by = 0.5)) |> plot_map() ``` -------------------------------- ### Run package checks Source: https://github.com/tylermorganwall/rayshader/blob/master/CONTRIBUTING.md Use these functions to verify package integrity across different platforms before submitting a pull request. ```R rhub::check_for_cran() ``` ```R rhub::check_on_solaris() ``` ```R rhub::check_on_macos() ``` ```R rhub::check_on_windows() ``` -------------------------------- ### Render 3D Plot with Custom Camera and Snapshot Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Renders a 3D plot with custom camera settings (FOV, zoom, theta, phi) and captures a snapshot. `multicore = TRUE` enables parallel processing. ```r plot_gg( pp, width = 5, height = 4, scale = 300, multicore = TRUE, windowsize = c(1000, 800) ) render_camera(fov = 70, zoom = 0.5, theta = 130, phi = 35) Sys.sleep(0.2) gg8 = render_snapshot(clear = TRUE, plot = FALSE) ``` -------------------------------- ### Basic Raytraced Shadow Map with ray_shade Source: https://context7.com/tylermorganwall/rayshader/llms.txt Generates a basic shadow map using raytracing. The 'zscale' argument controls the vertical exaggeration of the terrain. ```r # Basic raytraced shadow map montereybay |> ray_shade(zscale = 50) |> plot_map() ``` -------------------------------- ### ray_shade with Multicore Processing Source: https://context7.com/tylermorganwall/rayshader/llms.txt Enables multicore processing for faster computation of raytraced shadows. Ensure your system has multiple cores available for this option. ```r # Use multicore processing for faster computation montereybay |> ray_shade(zscale = 50, multicore = TRUE) |> plot_map() ``` -------------------------------- ### Write PNG Image Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Writes the current map to a PNG file with a user-specified filename. ```R write_png(filename = "map.png") ``` -------------------------------- ### Adding Labels and Annotations Source: https://context7.com/tylermorganwall/rayshader/llms.txt Places text labels on 3D scenes using geographic coordinates or absolute altitude, with options for styling and clearing. ```r # Setup scene montereybay |> sphere_shade() |> plot_3d(montereybay, zscale = 50, water = TRUE, watercolor = "#233aa1") # Add label using lat/long coordinates santa_cruz = c(36.962957, -122.021033) render_label(montereybay, lat = santa_cruz[1], long = santa_cruz[2], extent = attr(montereybay, "extent"), textsize = 2, altitude = 12000, zscale = 50, text = "Santa Cruz") # Add dashed line label with custom colors monterey = c(36.603053, -121.892933) render_label(montereybay, lat = monterey[1], long = monterey[2], altitude = 10000, extent = attr(montereybay, "extent"), textsize = 2, zscale = 50, text = "Monterey", textcolor = "white", linecolor = "darkred", dashed = TRUE) # Label at absolute altitude (not relative to surface) canyon = c(36.621049, -122.333912) render_label(montereybay, lat = canyon[1], long = canyon[2], altitude = 2000, extent = attr(montereybay, "extent"), textsize = 2, zscale = 50, text = "Monterey Canyon", relativez = FALSE) render_snapshot() # Clear all labels render_label(clear_previous = TRUE) ``` -------------------------------- ### Basic 3D Plot with Water Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Generates a basic 3D plot of a surface with water features. Requires prior data preparation and shading. ```r montereybay |> sphere_shade(zscale = 10, texture = "imhof1") |> add_shadow(montshadow, 0.5) |> add_shadow(montamb, 0) |> plot_3d( montereybay, zscale = 50, fov = 0, theta = -45, phi = 45, windowsize = c(1000, 800), zoom = 0.6, water = TRUE, waterdepth = 0, wateralpha = 0.5, watercolor = "lightblue", waterlinecolor = "white", waterlinealpha = 0.5, baseshape = "hex" ) render_snapshot(clear = TRUE) ``` -------------------------------- ### add_overlay Source: https://context7.com/tylermorganwall/rayshader/llms.txt Overlays a 3 or 4-layer RGB/RGBA array on the current map, respecting transparency. ```APIDOC ## add_overlay ### Description Overlays a 3 or 4-layer RGB/RGBA array on the current map, respecting transparency. ### Parameters - **overlay** (array) - Required - The 3 or 4-layer RGB/RGBA array to overlay. - **alphalayer** (numeric) - Optional - Transparency level for the overlay. ``` -------------------------------- ### Render 3D ggplot with Preview Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Renders a 3D ggplot with specified dimensions, scale, and raytracing disabled, enabling a preview. Use `preview = TRUE` for interactive viewing. ```r gg7 = plot_gg( pp, width = 5, height = 4, scale = 300, raytrace = FALSE, preview = TRUE ) ``` -------------------------------- ### Render high-quality 3D maps Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Uses render_highquality to generate a high-quality render without pre-computing shadows. ```r elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "desert") |> plot_3d( elmat, zscale = 10, fov = 0, theta = 72, zoom = 0.68, phi = 40, shadowdepth = -100, soliddepth = -100, windowsize = c(1000, 800) ) render_scalebar( limits = c(0, 5, 10), label_unit = "km", position = "W", y = 50, scale_length = c(0.33, 1) ) render_compass(position = "E") Sys.sleep(0.2) render_highquality(samples = 16, scale_text_size = 24) ``` -------------------------------- ### ambient_shade with Increased Quality Settings Source: https://context7.com/tylermorganwall/rayshader/llms.txt Improves the quality of ambient occlusion by increasing the 'maxsearch' distance and 'sunbreaks' (ray density). Multicore processing is also enabled for speed. ```r # Increase search distance and ray density for better quality montereybay |> ambient_shade(sunbreaks = 24, maxsearch = 100, multicore = TRUE) |> plot_map() ``` -------------------------------- ### detect_water Source: https://context7.com/tylermorganwall/rayshader/llms.txt Uses a flood-fill algorithm to detect bodies of water of a user-specified minimum area based on flat surface normals. ```APIDOC ## detect_water ### Description Uses a flood-fill algorithm to detect bodies of water of a user-specified minimum area based on flat surface normals. ### Parameters - **heightmap** (matrix) - Required - The elevation matrix. - **min_area** (numeric) - Optional - Minimum area threshold for water detection. ``` -------------------------------- ### Add map annotations Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Adds a scale bar and compass to the current 3D render. ```r render_camera(fov = 0, theta = 60, zoom = 0.75, phi = 45) render_scalebar( limits = c(0, 5, 10), label_unit = "km", position = "W", y = 50, scale_length = c(0.33, 1) ) render_compass(position = "E") render_snapshot(clear = TRUE) ``` -------------------------------- ### Add water and shadow layers Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Enhances maps by adding water detection and various shadow types like raytracing and ambient occlusion. ```r #detect_water and add_water adds a water layer to the map: elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "desert") |> plot_map() ``` ```r #And we can add a raytraced layer from that sun direction as well: elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "desert") |> add_shadow(ray_shade(elmat), 0.5) |> plot_map() ``` ```r #And here we add an ambient occlusion shadow layer, which models #lighting from atmospheric scattering: elmat |> sphere_shade(texture = "desert") |> add_water(detect_water(elmat), color = "desert") |> add_shadow(ray_shade(elmat), 0.5) |> add_shadow(ambient_shade(elmat, maxsearch = 30), 0) |> plot_map() ``` -------------------------------- ### Render 3D Plot Snapshot Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Renders a 3D plot with specified dimensions, zoom, and camera angles, then captures it as a snapshot. Use `clear = TRUE` to clear the previous scene. ```r plot_gg( mtplot, width = 3.5, multicore = TRUE, windowsize = c(800, 800), zoom = 0.85, phi = 35, theta = 30, sunangle = 225 ) Sys.sleep(0.2) gg6 = render_snapshot(clear = TRUE, plot = FALSE) ``` -------------------------------- ### Red Relief Image Map (RRIM) Technique Source: https://context7.com/tylermorganwall/rayshader/llms.txt Combines sphere_shade with custom red colors, ambient_shade, and lamb_shade to create a Red Relief Image Map. This technique is useful for highlighting topographic features. ```r # Create Red Relief Image Map (RRIM) technique bigmb = resize_matrix(montereybay, scale = 2, method = "cubic") bigmb |> sphere_shade(zscale = 3, texture = create_texture("red", "red", "red", "red", "white")) |> add_shadow(ambient_shade(bigmb, maxsearch = 100, multicore = TRUE, zscale = 1), 0) |> add_shadow(lamb_shade(bigmb), 0.5) |> plot_map() ``` -------------------------------- ### Add water layers to 3D maps Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Integrates water layers into 3D visualizations using plot_3d arguments. ```r montshadow = ray_shade(montereybay, zscale = 50, lambert = FALSE) montamb = ambient_shade(montereybay, zscale = 50) montereybay |> sphere_shade(zscale = 10, texture = "imhof1") |> add_shadow(montshadow, 0.5) |> add_shadow(montamb, 0) |> plot_3d( montereybay, zscale = 50, fov = 0, theta = -45, phi = 45, windowsize = c(1000, 800), zoom = 0.75, water = TRUE, waterdepth = 0, wateralpha = 0.5, watercolor = "lightblue", waterlinecolor = "white", waterlinealpha = 0.5 ) Sys.sleep(0.2) render_snapshot(clear = TRUE) ``` -------------------------------- ### sphere_shade with Custom Texture Colors Source: https://context7.com/tylermorganwall/rayshader/llms.txt Creates a custom texture using specific hex color codes for highlight, shadow, left, right, and center/flat areas. The 'create_texture' function helps define these colors. ```r # Create custom texture colors montereybay |> sphere_shade(zscale = 10, texture = create_texture( "#E9C68D", # highlight color "#AF7F38", # shadow color "#674F30", # left fill "#494D30", # right fill "#B3BEA3" # center/flat areas )) |> plot_map() ``` -------------------------------- ### Layer Multiple Shadow Types with add_shadow Source: https://context7.com/tylermorganwall/rayshader/llms.txt Stacks multiple shadow maps (sphere_shade, ray_shade, ambient_shade) to create complex lighting. The second argument in 'add_shadow' controls the intensity of each layer. ```r # Layer multiple shadow types montereybay |> sphere_shade(texture = "desert") |> add_shadow(ray_shade(montereybay, zscale = 50), 0.5) |> add_shadow(ambient_shade(montereybay, maxsearch = 30), 0) |> plot_map() ``` -------------------------------- ### Animated Movie Creation Source: https://context7.com/tylermorganwall/rayshader/llms.txt Produces MP4 or GIF animations using orbit, oscillation, or custom camera paths. ```r # Basic orbit animation montereybay |> sphere_shade(texture = "imhof1") |> plot_3d(montereybay, zscale = 50, water = TRUE, watercolor = "imhof1") render_movie(filename = "monterey_orbit.mp4", frames = 360, fps = 30) # Oscillating animation render_movie(filename = "monterey_oscillate.mp4", type = "oscillate", frames = 60, phi = 30, zoom = 0.8, theta = -90, title_text = "Monterey Bay: Oscillating") # Custom camera path animation phivec = 30 + 60 * 1/(1 + exp(seq(-7, 20, length.out = 180)/2)) phivecfull = c(phivec, rev(phivec)) thetavec = -90 + 45 * sin(seq(0, 359, length.out = 360) * pi/180) zoomvec = 0.45 + 0.2 * 1/(1 + exp(seq(-5, 20, length.out = 180))) zoomvecfull = c(zoomvec, rev(zoomvec)) render_movie(filename = "monterey_custom.mp4", type = "custom", frames = 360, phi = phivecfull, theta = thetavec, zoom = zoomvecfull) ``` -------------------------------- ### sphere_shade with Desert Palette and Custom Sun Angle Source: https://context7.com/tylermorganwall/rayshader/llms.txt Applies the 'desert' texture palette and customizes the sun angle for a different lighting effect. Ensure the 'texture' argument matches a built-in palette or a custom texture. ```r # Use desert palette with custom sun angle montereybay |> sphere_shade(texture = "desert", sunangle = 45) |> plot_map() ``` -------------------------------- ### Rendering Polygons on a 3D Map Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Adds polygons to a 3D map, with options for buffering, data column mapping, and color. Requires `sf` package and spatial data. ```r montereybay |> sphere_shade(texture = "desert") |> add_shadow(ray_shade(montereybay, zscale = 50)) |> plot_3d( montereybay, water = TRUE, windowsize = c(1000, 800), watercolor = "dodgerblue" ) render_camera(theta = -60, phi = 60, zoom = 0.85, fov = 30) #We will apply a negative buffer to create space between adjacent polygons: sf::sf_use_s2(FALSE) mont_county_buff = sf::st_simplify( sf::st_buffer(monterey_counties_sf, -0.003), dTolerance = 0.004 ) render_polygons( mont_county_buff, extent = attr(montereybay, "extent"), data_column_top = "ALAND", scale_data = 300 / (2.6E9), color = "chartreuse4", parallel = TRUE ) render_highquality(samples = 16) ``` ```r render_polygons(clear_previous = TRUE) render_camera(theta = 225, phi = 30, zoom = 0.37, fov = 48) ``` -------------------------------- ### Place Compass on Map Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Places a compass on the map in a 3D perspective. ```R render_compass() ``` -------------------------------- ### Save or Plot 3D Snapshot Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Saves an image of the current 3D view to disk if a filename is provided, or plots it to the current device. Useful for R Markdown integration. ```R render_snapshot(filename = "scene.png") ``` ```R render_snapshot() ``` -------------------------------- ### High-Quality Raytraced Rendering Source: https://context7.com/tylermorganwall/rayshader/llms.txt Generates photorealistic renders using the rayrender package with support for custom lighting, materials, and environmental settings. ```r # Basic high quality render volcano |> sphere_shade() |> plot_3d(volcano, zscale = 2) render_highquality(samples = 128, min_variance = 0) # Custom lighting render_highquality(lightdirection = 45, lightaltitude = 60, samples = 128) # Multiple colored lights render_highquality(lightdirection = c(0, 120, 240), lightaltitude = 45, lightcolor = c("red", "green", "blue"), title_text = "RGB Lighting", title_bar_color = "white", samples = 128) # Custom ground material with checkerboard render_highquality(lightdirection = c(-45, 45), lightaltitude = 30, samples = 128, camera_lookat = c(0, -50, 0), ground_material = rayrender::diffuse( color = "grey50", checkercolor = "grey20", checkerperiod = 100 )) # Render with realistic sky at specific location and time render_highquality(samples = 128, lat = 36.6, long = -121.9, iso = 5, clamp_value = 1000, datetime = as.POSIXct("2024-06-21 12:00:00", tz = "America/Los_Angeles")) ``` -------------------------------- ### plot_3d Source: https://context7.com/tylermorganwall/rayshader/llms.txt Displays the shaded map in 3D using the rgl package with extensive customization options for water, shadows, base shapes, and camera settings. ```APIDOC ## plot_3d ### Description Displays the shaded map in 3D using the rgl package with extensive customization options for water, shadows, base shapes, and camera settings. ### Parameters - **hillshade** (matrix) - Required - The hillshaded map. - **heightmap** (matrix) - Required - The elevation matrix. - **zscale** (numeric) - Required - The ratio between the x/y spacing and the z-axis. - **water** (boolean) - Optional - Whether to render water. - **baseshape** (string) - Optional - The shape of the base (e.g., 'circle', 'hex'). ``` -------------------------------- ### High-Quality Render with Glass Material and Environment Light Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Renders a 3D ggplot with `render_highquality()`, reducing triangulation error for performance. It uses a glass material and an HDR environment map for lighting. `max_error` controls triangulation detail. ```r tempfilehdr = tempfile(fileext = ".hdr") download.file("https://www.tylermw.com/data/venice_sunset_2k.hdr", tempfilehdr) par(mfrow = c(1, 1)) plot_gg( pp, width = 5, height = 4, scale = 300, raytrace = FALSE, windowsize = c(1200, 960), fov = 129, zoom = 0.21, theta = -25, phi = 9, max_error = 0.01, verbose = TRUE, ) Sys.sleep(0.2) render_highquality( samples = 16, aperture = 30, light = FALSE, override_material = TRUE, focal_distance = 1043, material = rayrender::dielectric(attenuation = c(1, 1, 0.3) / 200), ground_material = rayrender::diffuse( checkercolor = "grey80", sigma = 90, checkerperiod = 100 ), environment_light = tempfilehdr, rotate_env = 180 ) ``` -------------------------------- ### Place Scalebar on Map Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Places a scalebar on the map in a 3D perspective. ```R render_scalebar() ``` -------------------------------- ### Detect Water Bodies Source: https://context7.com/tylermorganwall/rayshader/llms.txt Use flood-fill algorithms to identify water based on surface normals and minimum area thresholds. ```r # Detect water in modified volcano dataset island_volcano = volcano island_volcano[island_volcano < mean(island_volcano)] = mean(island_volcano) # Basic water detection with minimum area threshold water_map = detect_water(island_volcano, min_area = 400) island_volcano |> sphere_shade(texture = "imhof3") |> add_water(water_map, color = "imhof3") |> plot_map() # Detect ocean in Monterey Bay montbay_water = montereybay montbay_water[montbay_water < 0] = 0 montereybay |> sphere_shade(texture = "imhof4") |> add_water(detect_water(montbay_water), color = "imhof4") |> plot_map() ``` -------------------------------- ### height_shade with Custom Color Palette Source: https://context7.com/tylermorganwall/rayshader/llms.txt Applies a custom color palette to the elevation data. The 'topo.colors(256)' function provides a standard topographic color scheme. ```r # Custom color palette montereybay |> height_shade(texture = topo.colors(256)) |> plot_map() ``` -------------------------------- ### Render high-quality maps with water and custom materials Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Combines rayrender materials with rayshader high-quality rendering for advanced visual effects. ```r library(rayrender) montereybay |> sphere_shade(zscale = 10, texture = "imhof1") |> plot_3d( montereybay, zscale = 50, fov = 70, theta = 270, phi = 30, windowsize = c(1000, 800), zoom = 0.6, water = TRUE, waterdepth = 0, wateralpha = 0.5, watercolor = "#233aa1", waterlinecolor = "white", waterlinealpha = 0.5 ) Sys.sleep(0.2) render_highquality( lightdirection = c(-45, 45), lightaltitude = 30, samples = 16, camera_lookat = c(0, -50, 0), ground_material = diffuse( color = "grey50", checkercolor = "grey20", checkerperiod = 100 ), clear = TRUE ) ``` -------------------------------- ### Export for 3D Printing with save_3dprint Source: https://context7.com/tylermorganwall/rayshader/llms.txt Exports models to STL format specifically for 3D printing. ```r # Export for 3D printing volcano |> sphere_shade() |> plot_3d(volcano, zscale = 2) save_3dprint("volcano_print.stl") ``` -------------------------------- ### ray_shade with Custom Sun Position Source: https://context7.com/tylermorganwall/rayshader/llms.txt Customizes the sun's altitude and angle for raytraced shadows. 'sunaltitude' controls the height of the sun, and 'sunangle' its direction. ```r # Customize sun position and altitude montereybay |> ray_shade(zscale = 50, sunaltitude = 25, sunangle = 225) |> plot_map() ``` -------------------------------- ### Render Camera Source: https://context7.com/tylermorganwall/rayshader/llms.txt Adjust camera position, rotation, and field of view for 3D scenes. ```r # Setup 3D scene montereybay |> sphere_shade() |> plot_3d(montereybay, zscale = 50, water = TRUE, waterlinecolor = "white") # Rotate view render_camera(theta = -45, phi = 45) render_snapshot() # Overhead view render_camera(theta = 0, phi = 89.9, zoom = 0.9) render_snapshot() # Front view with field of view render_camera(theta = -90, phi = 30, zoom = 0.5, fov = 130) render_snapshot() # Get current camera values current_cam = render_camera() # Returns c(theta, phi, zoom, fov) ``` -------------------------------- ### render_camera Source: https://context7.com/tylermorganwall/rayshader/llms.txt Changes the camera position and properties around the 3D scene. ```APIDOC ## render_camera ### Description Changes the camera position and properties around the 3D scene. ### Parameters - **theta** (numeric) - Optional - Rotation angle. - **phi** (numeric) - Optional - Azimuth angle. - **zoom** (numeric) - Optional - Zoom level. - **fov** (numeric) - Optional - Field of view. ``` -------------------------------- ### Add Water Layers Source: https://context7.com/tylermorganwall/rayshader/llms.txt Apply water color layers to 2D maps using a detection mask. ```r # Add water with built-in color palette montereybay |> sphere_shade(texture = "desert") |> add_water(detect_water(montereybay), color = "desert") |> plot_map() # Custom water color montereybay |> sphere_shade() |> add_water(detect_water(montereybay), color = "#233aa1") |> plot_map() ``` -------------------------------- ### height_shade with Water Palette for Bathymetry Source: https://context7.com/tylermorganwall/rayshader/llms.txt Uses a custom color ramp designed for water depths to visualize bathymetric data. The 'colorRampPalette' function generates the gradient. ```r # Water palette for bathymetry water_palette = colorRampPalette(c("darkblue", "dodgerblue", "lightblue"))(200) montereybay |> height_shade(texture = water_palette) |> plot_map() ``` -------------------------------- ### Create a Terraced Hexbin Plot Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Generates a terraced hexbin plot by mapping fill colors to the count of points within hexagonal bins. Line colors of hexagons are set to black. Requires `ggplot2` and `viridis`. ```r a = data.frame(x = rnorm(20000, 10, 1.9), y = rnorm(20000, 10, 1.2)) b = data.frame(x = rnorm(20000, 14.5, 1.9), y = rnorm(20000, 14.5, 1.9)) c = data.frame(x = rnorm(20000, 9.5, 1.9), y = rnorm(20000, 15.5, 1.9)) data = rbind(a, b, c) #Lines pp = ggplot(data, aes(x = x, y = y, fill = after_stat(count))) + geom_hex(bins = 20, linewidth = 0.5, color = "black") + scale_fill_viridis_c(option = "C") + scale_color_viridis_c(option = "C") ``` -------------------------------- ### Plot 3D Maps Source: https://context7.com/tylermorganwall/rayshader/llms.txt Render shaded maps in 3D with support for water, shadows, and custom base shapes. ```r # Basic 3D plot montereybay |> sphere_shade(texture = "desert") |> plot_3d(montereybay, zscale = 50) render_snapshot() # With water layer and waterlines montereybay |> sphere_shade(texture = "imhof2") |> plot_3d(montereybay, zscale = 50, water = TRUE, watercolor = "imhof2", waterlinecolor = "white", waterlinealpha = 0.5) render_snapshot() # Custom camera and window settings montereybay |> sphere_shade(texture = "desert") |> add_water(detect_water(montereybay), color = "desert") |> add_shadow(ray_shade(montereybay, zscale = 3), 0.3) |> add_shadow(ambient_shade(montereybay), 0) |> plot_3d(montereybay, zscale = 10, fov = 0, # Isometric view theta = 135, # Rotation angle phi = 45, # Azimuth angle zoom = 0.75, windowsize = c(1000, 800)) render_snapshot() # Circular or hexagonal base shape montereybay |> sphere_shade(texture = "imhof1") |> plot_3d(montereybay, zscale = 50, water = TRUE, watercolor = "imhof1", baseshape = "circle", # or "hex" theta = -45, zoom = 0.7) render_snapshot() # With soil texture on base montereybay |> sphere_shade(texture = "imhof3") |> plot_3d(montereybay, zscale = 50, water = TRUE, watercolor = "imhof4", soil = TRUE) render_camera(theta = 225, phi = 7, zoom = 0.5, fov = 67) render_snapshot() ``` -------------------------------- ### Rendering Points on a 3D Map Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Adds points to a 3D map, suitable for plotting tracks or specific locations. Requires latitude, longitude, and altitude data. Uses `clear_previous = TRUE` to reset the scene. ```r moss_landing_coord = c(36.806807, -121.793332) x_vel_out = -0.0018 + rnorm(1000)[1:300] / 1000 y_vel_out = rnorm(1000)[1:300] / 100 z_out = c( seq(0, 2000, length.out = 180), seq(2000, 0, length.out = 10), seq(0, 2000, length.out = 100), seq(2000, 0, length.out = 10) ) bird_track_lat = list() bird_track_long = list() bird_track_lat[[1]] = moss_landing_coord[1] bird_track_long[[1]] = moss_landing_coord[2] for (i in 2:300) { bird_track_lat[[i]] = bird_track_lat[[i - 1]] + y_vel_out[i] bird_track_long[[i]] = bird_track_long[[i - 1]] + x_vel_out[i] } render_points( extent = attr(montereybay, "extent"), lat = unlist(bird_track_lat), long = unlist(bird_track_long), altitude = z_out, zscale = 50, size = 3, color = "red", clear_previous = TRUE ) render_highquality(point_radius = 0.5, samples = 16) ``` ```r render_points(clear_previous = TRUE) ``` -------------------------------- ### Arrange Multiple Plots in a Grid Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Arranges multiple plot objects (e.g., snapshots) into a grid layout. `dim = c(1, 2)` specifies a grid with 1 row and 2 columns. ```r rayimage::plot_image_grid(list(gg5, gg6), dim = c(1, 2)) ``` ```r rayimage::plot_image_grid(list(gg7, gg8), dim = c(1, 2)) ``` -------------------------------- ### height_shade Combined with Raytraced Shadows Source: https://context7.com/tylermorganwall/rayshader/llms.txt Combines a height-based color map with raytraced shadows to add depth and realism. The 'add_shadow' function layers the shadow map with a specified intensity. ```r # Combine with raytraced shadows montereybay |> height_shade(texture = rainbow(256)) |> add_shadow(ray_shade(montereybay, zscale = 50), 0.1) |> plot_map() ``` -------------------------------- ### Rendering Paths on a 3D Map Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Adds paths to a 3D map, useful for visualizing trajectories or routes. Supports antialiasing and extrusion for higher quality rendering. ```r render_path( extent = attr(montereybay, "extent"), lat = unlist(bird_track_lat), long = unlist(bird_track_long), altitude = z_out, zscale = 50, linewidth = 3, color = "white", antialias = TRUE ) render_highquality( line_radius = 0.5, samples = 16, clear = TRUE, use_extruded_paths = TRUE ) ``` -------------------------------- ### 3D Contour Plot with Volcano Dataset Source: https://github.com/tylermorganwall/rayshader/blob/master/README.md Create a 3D contour plot from the `volcano` dataset using `ggplot2` and `geom_contour`. Rayshader automatically ignores lines that should not be mapped to 3D. Use `plot_gg()` for 3D rendering and `render_snapshot()` to capture the output. ```r library(reshape2) #Contours and other lines will automatically be ignored. Here is the volcano dataset: ggvolcano = volcano |> melt() |> ggplot() + geom_tile(aes(x = Var1, y = Var2, fill = value)) + geom_contour(aes(x = Var1, y = Var2, z = value), color = "black") + scale_x_continuous("X", expand = c(0, 0)) + scale_y_continuous("Y", expand = c(0, 0)) + scale_fill_gradientn("Z", colours = terrain.colors(10)) + coord_fixed() # Return a preview snapshot gg3 = plot_gg( ggvolcano, width = 7, height = 4, raytrace = FALSE, preview = TRUE ) ``` ```r # Plot in 3D plot_gg( ggvolcano, multicore = TRUE, raytrace = TRUE, width = 7, height = 4, scale = 300, windowsize = c(1400, 866), zoom = 0.6, phi = 30, theta = 30 ) ``` ```r Sys.sleep(0.2) gg4 = render_snapshot(clear = TRUE, plot = FALSE) ``` ```r rayimage::plot_image_grid(list(gg3, gg4), dim = c(1, 2)) ```