How to Create a GGPlot-like 3D Scatter Plot using Plotly



How to Create a GGPlot-like 3D Scatter Plot using Plotly

In this article you will learn how to create a ggplot-like 3D scatter plot using the plotly R package.

Contents:

Related Book

GGPlot2 Essentials for Great Data Visualization in R

Prerequisites

Load required R packages

library(tidyverse)
library(plotly)

Data preparation:

df <- mtcars %>%
  rownames_to_column() %>%
  as_data_frame() %>%
  mutate(am = ifelse(am == 0, "Automatic", "Manual")) %>%
  mutate(am = as.factor(am))
df
## # A tibble: 32 x 12
##   rowname   mpg   cyl  disp    hp  drat    wt  qsec    vs am    gear  carb
##   <chr>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <fc> <dbl> <dbl>
## 1 Mazda …  21       6   160   110  3.9   2.62  16.5     0 Man…     4     4
## 2 Mazda …  21       6   160   110  3.9   2.88  17.0     0 Man…     4     4
## 3 Datsun…  22.8     4   108    93  3.85  2.32  18.6     1 Man…     4     1
## 4 Hornet…  21.4     6   258   110  3.08  3.22  19.4     1 Aut…     3     1
## 5 Hornet…  18.7     8   360   175  3.15  3.44  17.0     0 Aut…     3     2
## 6 Valiant  18.1     6   225   105  2.76  3.46  20.2     1 Aut…     3     1
## # ... with 26 more rows

Basic 3D Scatter Plot

# Create the plot
p <- plot_ly(
  df, x = ~wt, y = ~hp, z = ~qsec, 
  color = ~am, colors = c('#BF382A', '#0C4B8E')
  ) %>%
  add_markers() %>%
  layout(
    scene = list(xaxis = list(title = 'Weight'),
        yaxis = list(title = 'Gross horsepower'),
        zaxis = list(title = '1/4 mile time'))
        )
p

3D Scatter Plot with Color Scaling

Point markers will be colored according to the mpg variable:

# Point colors
marker <- list(color = ~mpg, colorscale = c('#FFE1A1', '#683531'), 
              showscale = TRUE)
# Create the plot
p <- plot_ly(df, x = ~wt, y = ~hp, z = ~qsec, marker = marker) %>%
  add_markers() %>%
  layout(
    scene = list(xaxis = list(title = 'Weight'),
        yaxis = list(title = 'Gross horsepower'),
        zaxis = list(title = '1/4 mile time'))
        )
p

Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments