Plotly for 3d and interactive plots in R

table
stargazer
package
Published

June 25, 2024

Modified

June 25, 2024

1 Setup

Code
library(tidyverse)
library(plotly)

2 Interactive plots with Plotly

Code
p <- starwars |>  
  drop_na(height, mass, eye_color) |> 
  filter(mass < 250,
         eye_color %in% c("blue", "brown", "black", "pink", "red", "orange")) |> 
  ggplot(aes(height, mass, color = eye_color)) +
  geom_point() +
  geom_jitter(size = 6,
              alpha = .5) +
  scale_colour_manual(values = c("blue" = "blue",
                                 "brown" = "brown",
                                 "black" = "black",
                                 "pink" = "pink",
                                 "red" = "red",
                                 "orange" = "orange")) +
  theme_bw() +
  theme(legend.position = c(0.05, 0.98),
        legend.justification = c("left", "top")) +
  labs(title = "Height, mass and eye color of Star Wars characters",
       x = "Height",
       y = "Mass",
       color = "Eye color")

ggplotly(p)

3 3D plots with Plotly

3.1 3D scatter plot

Code
trees |> 
  plot_ly(x = ~Girth,
          y = ~Height,
          z = ~Volume) 

3.2 3D surface plot

Code
plot_ly(z = ~volcano, type = "surface")
Back to top