Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active December 30, 2021 23:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/3895534f18c15e9c5433599e79e2cd82 to your computer and use it in GitHub Desktop.
Save matt-dray/3895534f18c15e9c5433599e79e2cd82 to your computer and use it in GitHub Desktop.
Create a 3D ggplot with {ggrgl} and colour the extrusion by some variable
# Create a 3D ggplot with {ggrgl} and colour the extrusion by some variable
#
# Motivation via @geoff_tewierik:
# https://twitter.com/geoff_tewierik/status/1476662279437369346?s=20
# See blog about the {gpx3d} package:
# https://www.rostrum.blog/2021/12/30/gpx3d/
# See {gpx3d} package source:
# https://github.com/matt-dray/gpx3d
library(gpx3d)
library(ggplot2)
library(ggrgl)
library(devoutrgl)
library(RColorBrewer)
# Read local GPX file and extract data
route <- extract_gpx3d(
"~/Downloads/apple_health_export/workout-routes/route_2021-12-25_9.31am.gpx"
)
# I couldn't seem to get the ggrgl::scale_extrude_*() functions to work, so
# this is a low-tech workaround (palette as per https://stackoverflow.com/a/6183993)
my.col <- colorRampPalette(brewer.pal(9, "YlOrRd"))(diff(range(route$ele)))
pal <- my.col[route$ele]
# Create 3D plot
route_plot <- ggplot() +
geom_path_3d(
aes(route$lon, route$lat, z = route$ele),
extrude = TRUE,
extrude_face_fill = pal,
extrude_edge_colour = pal
) +
theme_void()
# Plot to external device
rgldev(fov = 30, view_angle = -30); route_plot; invisible(dev.off())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment