This post thoroughly details the process of building and customizing
2D maps using the
rayshader package. It includes
step-by-step, reproducible code examples and clearly explains the
required formatting for input data.
By following this
guide, you will learn how to create
visually appealing maps and tailor them to meet
your specific needs, ensuring your data is presented in the most
effective way possible. Additionally, the post covers various
customization options within rayshader, enabling
you to enhance your maps with different visual
styles and effects.
The rayshader package makes it simple to create shaded 2D relief maps.
Since the package is on CRAN, you can
install it with
install.packages("rayshader")
.
We also load the raster
package to
access data to work with.
The rayshader package requires input data in an elevation matrix format. This is a specific matrix where each cell holds the elevation value for the corresponding map point.
Here’s how to obtain the elevation matrix of the
Grand Canyon from a raster file using the
raster
package.
Let’s see how to create a basic 2D map with rayshader.
We use the sphere_shade()
function to create the map. It
takes the elevation matrix as input and returns a
shaded map, and then plot it with the
plot_map()
function.
rayshader includes a
specialized function to create textures:
create_texture()
. This function accepts
5 colors as input and generates a texture suitable
for use in the sphere_shade()
function.
custom_texture <- create_texture("#fff673","#55967a","#8fb28a","#55967a","#cfe0a9")
elevation_matrix %>%
sphere_shade(texture=custom_texture, sunangle = 45) %>%
plot_map()
The add_shadow()
function can be used to add a shadow to
the map. The ray_shade()
function creates a shadow based
on the sun angle, while the ambient_shade()
function
creates a shadow based on the ambient light.
elevation_matrix %>%
sphere_shade(texture="desert", sunangle = 45, zscale = 50) %>%
add_shadow(ray_shade(elevation_matrix), 0.5) %>% # Adds a ray-traced shadow
add_shadow(ambient_shade(elevation_matrix), 0) %>% # Adds an ambient shadow
plot_map()
You might be interested in
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥