Eight years in the making—rayshader 1.0 is here!
Be sure to read to the end for what I can guarantee is the most exciting and cinematric R package bibliography you’ve ever seen. Everything you see in the below blog post was rendered in R with the rayverse.
Eight years ago, rayshader started as a small experiment in making beautiful maps in R. The first version was based on a simple question: what if we combined raytracing and cartography? I had always been interested in learning both about mapping and pathtracing, and what better way than to combine the two ideas into a single R package? The big “aha!” moment came when I applied that method with interactive 3D terrain for the first time and took it for a spin.
The surface was no longer just a shaded map: it felt tangible and real, a 3D rectangle twirling like a Little Debbie cosmic brownie on a microwave turntable. The combination of cartographic hillshading and 3D raytraced terrain looked spectacular in a way that, at the time, mostly lived in bespoke Blender scenes or other advanced 3D modeling tools. And unlike Blender, you didn’t need to learn a whole new ecosystem to visualize your data in 3D: it lived in the same place your data did (R!), which allowed for a gentler learning curve.
But as time went on and the package and userbase expanded, I had a nagging feeling: rayshader was still too hard.
Not always, of course: plenty of people were using it, quite effectively. Simple use cases were fine: pass in a matrix, add a few layers, call plot_3d(), and suddenly you had a cool-looking 3D landscape. If that’s all you needed: great! But if the story you were trying to tell was about data within the landscape–well, that’s where the friction began to burn.
I built rayshader for people who wanted to make data beautiful without leaving R. Beauty has a real purpose in the world: it draws people’s eyes. It doesn’t matter how accurate or well-constructed your map is if the reader swipes on by: in the market for human attention, beauty and form are table stakes.
Journalists understood that quickly, and were some of rayshader’s earliest adopters.
The Wall Street Journal’s The Future of Arctic Shipping used detailed shipping, bathymetric, and ice coverage data to explain the complexities of the Northern Sea Route. The piece was recognized by the Information is Beautiful Awards, which described it as a deeply researched story built from shipping, bathymetric, and ice coverage data. It appeared only a few months after I released rayshader: talk about an introduction! Bloomberg’s 2024 Gaza rebuilding story, Gaza Reduced to 42 Million Tonnes of Rubble. What Will It Take to Rebuild?, used R, rayshader, and rayrender as part of the visual system for communicating the scale of destruction and debris in Gaza. And in June 2022, a rayshader 3D flood visualization appeared on the front page of The Sydney Morning Herald, inset into coverage of the Lismore flooding.
That last one stuck with me (and not only because a rayshader map was featured “above the fold” in a major newspaper!). Rayshader had started as a way to make beautiful data visualizations in R, but here it was being used in deadline journalism to help explain a disaster to a general audience. The package had left the domain of “fun engaging social media posts” and entered the visual language of public-interest reporting.
But getting a reader to stop scrolling is only half the problem. Working with journalists taught me how much friction stood between having the data and making the final product. A newsroom deadline is a very good detector of bad API design. If adding buildings takes half a day of coordinate fiddling, that feature might as well not exist. If a 3D path requires a hand-rolled coordinate transform pipeline, nobody is doing that 30 minutes before a deadline. If a pathtraced render looks great but takes too long to converge, it is not going to make it to print. Especially if the editor needs a slight tweak: “Oh, sure–just give me 8 hours to re-render the animation.” Ha. Nope.
Working with journalists taught me how much friction stood between having the data and making the final product.
The problem wasn’t so much with rayshader itself: it was how much spatial bookkeeping and manual fiddling you had to do to get data into rayshader before you could do all the fun stuff. And at the root of all that bookkeeping was the humble matrix, rayshader’s original choice for representing terrain.
Rayshader used matrices to represent terrain because it simplified a lot of the work that went into turning a bunch of elevation values in a 3D object. But most real data does not arrive nicely packaged as a plain rectangular numeric array. It arrives as georeferenced rasters, polygons, lines, and points. It arrives cloaked in an unknown coordinate reference system. It arrives in meters, feet, yards, degrees, or German legal metres. Choosing the matrix as the base input made it easy for me, the developer, by putting the spatial problem (mostly) on the user.
Convert the raster to a matrix. Save the extent. Transform the vector data. Save the CRS. Crop the linework. Pass the heightmap again. Pass the extent again. Wait, is the extent format lat/long/lat/long or lat/lat/long/long? I never remember–whatever, try both. The first choice is (somehow!) always wrong. Pass zscale again. Resize the overlay. Pass the CRS again. Check whether the map is oriented correctly. No? Surprise! Errant minus sign. Yuck.
This was not just annoying for beginners. It annoyed me, and I wrote the damn thing: now that’s a usability red flag! The new version of rayshader includes a series of changes that gets rid of all of this overhead and allows you to focus on presentation instead of the data processing.
The big change in rayshader 1.0 is this: rayshader no longer has short-term amnesia. Rayshader now keeps track of all the spatial details from your underlying map so you don’t have to worry about it any more.
Transform and pass in your data into an aligned matrix coordinate system, and rayshader will render it in beautiful 3D.
Transform and Pass in your data into an aligned matrix coordinate system, and rayshader will render it in beautiful 3D.
The black diamond learning curve is now a gentle bunny slope. Terrain can stay a spatial raster. Road can stay a spatial line and will automatically be converted to the correct coordinate system when plotting. Buildings can be passed in as spatial polygons and will automatically be cropped to the underlying map’s extent.
A rayshader scene now extracts and caches the important metadata from the input data: heightmap, extent, CRS, zscale, vertical exaggeration, and rendered-object metadata. That cache lets downstream render_*() calls do the thing users always wanted them to do: simply drop data into the scene.
Most of the functions can now add to the scene simply by passing the data, plus an optional argument that specifies altitude or height, either directly or through a column in an sf object. The rest of the arguments then focus on how you want to style the data.
For example, let’s load in some road and elevation data and see what the new API looks like. The code below defines the helpers and loads the data into R. There’s no rayshader in it, so you have absolutely no obligation to read it :).
Pretty straightforward… just kidding, loading geospatial data is always a pain. Nothing I can do about that! But the real question is: how complex is visualizating all this data once it’s loaded?
Not complex at all! You call the function named after the type of data… and it renders the data in the scene. Any additional arguments are just for styling the data to your liking.
And the payoff is not just less typing: it lets us get to the fun part of 3D data visualization faster. The coolest part of rayshader has always been building strikingly beautiful 3D landscapes from your data. But the third dimension raises the cognitive cost of entry: before you can play director and cinematographer, you have to build the set. When every point, path, and polygon needs the user to track the CRS and extent info themselves and transform the data appropriately, many users never get to the stage where they can experiment with lighting and composition, styling the data (costume design!), or focus on editing the overall narrative.
The third dimension raises the cognitive cost of entry: before you can play director and cinematographer, you have to build the set.
This release automates almost all of the behind-the-scenes work. The boring parts–CRS juggling, extent passing, heightmap repetition, matrix conversion, and other bookkeeping–stay in the package internals. The user is then free to jump to the enjoyable creative roles: the executive producer of the analysis, the production designer of the world, or the sound designer of a multi-sensory data experience.
Spatial data: free yourself from the matrix!
Rayshader now accepts many more spatial inputs for the heightmap. The plot_3d() function can now accept a heightmap as a matrix, a terra::SpatRaster, a raster object, or a raster filename. When the input is spatial, rayshader extracts and caches the extent and CRS. If zscale is not supplied, rayshader derives it from raster cell resolution. If the raster is geographic longitude/latitude, rayshader estimates the meter-per-cell scale at the raster center. The data was always there; it just had to be piped around to the right place! Now I do the plumbing for you.
Let’s look at an example. The same DEM and main-road data feed both versions below. The difference is who’s now doing the spatial bookkeeping (hint: it’s not you).
Internally, rayshader still converts the raster to something it can render. Externally, the scene remembers enough to let the render_*() functions just work.
There is now also a cleaner division between physical scale and visual exaggeration. zscale now describes the relationship between horizontal and vertical units, while vertical_exaggeration describes the stylistic exaggeration. For spatial rasters, rayshader can derive zscale from the raster itself, placing the data at its physical scale. You can then adjust vertical_exaggeration to emphasize the terrain without changing the underlying unit conversion.
And this spatial data directionality can now be reversed. spatialize_image() turns a rayshader image, matrix, RGB array, or RGBA array back into a georeferenced terra::SpatRaster. It can inherit the cached extent and CRS from the active scene, convert rayshader’s linear color values to sRGB, and optionally append the source heightmap as an additional raster layer. So rayshader’s output can now feed back into other GIS software, rather than just assume rayshader is the final destination itself.
This release lets rayshader fit into a real spatial workflow: spatial input, then rayshader styling, followed by spatial output. So you can generate beautiful hillshades and terrains in R, and then bring them into other spatial software like QGIS or ArcGIS. Work in the GIS interface you already know, render the terrain in R, and drop the result right back into your map.
Rayshader’s water was always a bit of an afterthought: it was good for rendering an ocean with bathymetry data, but it didn’t really work if the water was localized to one portion of the map. A lake halfway up a mountain shouldn’t require flooding everything below it to see the water, but rayshader’s old water meshing method assumed one water level for the whole map. Which was perfect if all you needed was that one large body of water: set a level and fill the scene to that height. Separate lakes, reservoirs at different elevations, and imperfect shorelines called for something more flexible.
Now water can arrive as a raster or a polygon, high in the mountains or below sea level. render_water() uses the terrain and coordinates already stored in the scene to properly place and render the water in a sane way.
Water can follow grid cells with water_render_method = "raster" or preserve polygon boundaries with the default, water_render_method = "polygon". Both draw a watertight mesh at the footprint and elevation you supply, even when that means an exposed vertical water wall where the supplied shoreline doesn’t quite meet the terrain. Fast, flexible, and suitable for the rare case where you need to visualize Moses crossing the Red Sea.
Another (much cooler, IMO) option is water_render_method = "optimized". It fits a closed shoreline to the actual 3D terrain mesh, adjusting the water elevation to match the supplied area. Using the elevations beneath your water footprint to seed candidate levels, the optimizer searches for a contour that comes as close as possible to the supplied water area without spilling out of the terrain. The animation below shows how candidate levels change the flooded area.
If no closed water body is possible—for example, the supplied water would flood the entire map—rayshader falls back to raster water.
A different problem arises when a DEM has no bathymetry: the lake bed and its surface occupy the same plane. shift_terrain() is a new function that can lower the terrain beneath a lake polygon before you add water, making room for the lake instead of letting the surfaces overlap. It can also raise terrain SimCity 2000-style (no tornados or alien invasions… yet).
Additionally, in render_highquality(), water can now use a rough dielectric material to spread reflections into the broad highlights you expect from a rippled lake. A perfectly smooth dielectric surface behaves like glass: reflected light stays coherent, so lakes and rivers can turn into polished sheets. Real water has small wind-driven ripples, each reflecting light in a slightly different direction. The microfacet material models this give a more realistic appearance to bodies of water, especially when viewed at a low angle.
Streams need to follow the terrain as they wind downhill. render_streams() takes spatial line data, samples the elevation along each path, and builds ribbons of water that hug the surface. Widths can vary by feature, and connected streams can be merged to reduce visible seams in high-quality renders. Put those streams together with lakes and you have a hydrologic scene driven by data.
Note that there’s no complex GIS concepts on the rayshader side: all the complexity is related to defining the visual style and appearance. As it should be–rayshader is a visualization package! The remaining complexity is just standard data complexity present in any analysis: get the data loaded, cleaned, and in a form that represents the thing you care about.
3D maps might seem like a fun little toy rather than a serious class of data visualization, but the third dimension is often surprisingly important for understanding geospatial data. This becomes less surprising when you realize that the most common mapping tool used by regular people–GPS apps–use 3D quite extensively. When you’re traveling through a city, buildings give you landmarks to match to your surroundings; on a walking or cycling route, the terrain shows where you’ll be climbing; and at a complex highway interchange, seeing which roads pass over one another helps you follow the right ramp and choose the right exit.
I already had surface-hugging polygons working for streams. Swap the water for asphalt and there’s a road! Easy, peasy, right?
No! What’s the issue? We’re spoiled with our GPS apps: we’re used to roads looking like roads. A strip of grey asphalt needs lane markings for someone to know it’s a road. With the help of some fun repeating UV coordinate tricks and our new spatial-first workflow, we can paint properly-sized lines on the road at the cost of a few small textures. And we can use the lane counts supplied in OpenStreetMap data to add the correct number of lanes to each road. Rayshader uses those counts to mesh and texture the road, while the scene’s spatial information keeps the markings correctly sized.
In Figure 11, each dash is 10 feet long and each gap is 30 feet. Those familiar markings do double duty: they improve the picture and act as little scale bars scattered through the scene. Beautiful! Pack it up, put a bow on it, and move on to the next feature, right?
No! Our roads are still smooshed together on one layer. At an interchange, that borders on uninterpretable.
OpenStreetMap doesn’t provide a full 3D road model. But it does carry one tiny (but extremely useful!) nugget of vertical information needed to draw roads correctly in 2D: drawing order. Draw layer 0, then layer 1, then layer 2, and the right road appears on top. That tells us which road crosses over which; it doesn’t tell us their heights or how the ramps return to ground level. Is this enough information to fully reconstruct our 3D roads?
The tempting shortcut is to turn each layer into a fixed height: find the crossings, lift each road by a standard overpass height, and ease it back toward the ground with some sort of ad hoc relaxation rule. What could go wrong?
Simple hacks? Don’t work here. Turns out the world is filled with little annoying complications like a bridge crossing a sunken highway (the highway is already below ground, so the bridge needs no change in elevation), or short segments in interchanges that are technically not stacked but fall between stacked layers, or places where the road is technically stacked over a traversable water body (which also counts as a layer!), or a thousand other pesky little details.
What are we to do then? How can we implement realistic highways? It’s not like there’s a manual with explicit guidance and standards for how roads should be built in 3D—wait, what is that? There is an explicit manual?
The American Association of State Highway and Transportation Officials (AASHTO) has a design manual for Interstate highways. Two of the things it covers are exactly what our map is missing. How much room does a truck need under a bridge? How steep can the road get on its way up there? Now that rayshader knows the scale of the scene, I can give the solver a clearance in feet and a maximum grade in percent. Here are the default settings I gave the road solver (these are customizable):
We can turn these requirements into constraints on the road heights. While the rules aren’t guaranteed to generate roads that match the real-world roads exactly, it’s going to be pretty close: excursions from the bare minimum allowable ruleset will usually only increase cost, and we’re talking government contracts here. Around each interchange, we discretize the roads into short segments and solve for their elevations together: maintain the crossing order and clearance, limit the grades, and keep the roads close to the terrain wherever possible.
It’s not like there’s a manual with explicit guidance and standards for how roads should be built in 3D—wait, what is that? There is an explicit manual?
For example, a road can weave over and under several others. Lifting one crossing changes the grades leading into the next, so solving each crossing independently won’t work–we have to solve all the linked constraints at once. We build a graph of the road connections with {igraph}, locate crossings with {sf}, and follow the constraints along connected road segments. Each connected optimization region gets a sparse quadratic problem, assembled with {Matrix} and solved with {osqp}. It turns out, R has everything you need to build and optimize road profiles.
It’s pretty cool how closely a set of road-design rules and OSM’s layer ordering can recreate a complex interchange. The layer tags tell us which road goes over which, and the rules guide how the ramps connect them. Here’s Houston, now modeled in a sane way:
Beautiful. And since I went to Houston for this year’s Posit::conf, I was able to drive over specific intersections I rendered here and confirm that yes: the roads were accurately meshed. Minus the traffic.
The novelty seeking half of my brain immediately followed this thought with: “You should put in cars now!” to which the logical, killjoy side of my brain responded “NO! STOP IT! YOU’VE IMPLEMENTED TOO MANY FEATURES ALREADY! You will never release this update if you keep indulging yourself! Stop it!”