Show Sidebar Hide Sidebar # 3D Line Plots in R

How to make interactive 3D line plots in R.

### New to Plotly?

Plotly's R library is free and open source!
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

### Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

library(plotly)
packageVersion('plotly')

##  '4.5.5.9000'


### Basic 3D Line Plot

library(plotly)

data$color <- as.factor(data$color)

p <- plot_ly(data, x = ~x, y = ~y, z = ~z, type = 'scatter3d', mode = 'lines',
opacity = 1, line = list(width = 6, color = ~color, reverscale = FALSE))

# Set up API credentials: https://plot.ly/r/getting-started


### 3D Line and Markers Plot

library(plotly)

x <- c()
y <- c()
z <- c()
c <- c()

for (i in 1:62) {
r <- 20 * cos(i / 20)
x <- c(x, r * cos(i))
y <- c(y, r * sin(i))
z <- c(z, i)
c <- c(c, i)
}

data <- data.frame(x, y, z, c)

p <- plot_ly(data, x = ~x, y = ~y, z = ~z, type = 'scatter3d', mode = 'lines+markers',
line = list(width = 6, color = ~c, colorscale = 'Viridis'),
marker = list(size = 3.5, color = ~c, colorscale = 'Greens', cmin = -20, cmax = 50))

# Set up API credentials: https://plot.ly/r/getting-started


### Custom Color Scale

library(plotly)

count <- 3000

x <- c()
y <- c()
z <- c()
c <- c()

for (i in 1:count) {
r <- i * (count - i)
x <- c(x, r * cos(i / 30))
y <- c(y, r * sin(i / 30))
z <- c(z, i)
c <- c(c, i)
}

data <- data.frame(x, y, z, c)

p <- plot_ly(data, x = ~x, y = ~y, z = ~z, type = 'scatter3d', mode = 'lines',
line = list(width = 4, color = ~c, colorscale = list(c(0,'#BA52ED'), c(1,'#FCB040'))))

# Set up API credentials: https://plot.ly/r/getting-started


### 3D Random Walk Plot

library(plotly)

p <- plot_ly(data, x = ~x1, y = ~y1, z = ~z1, type = 'scatter3d', mode = 'lines',
line = list(color = '#1f77b4', width = 1)) %>%
add_trace(x = ~x2, y = ~y2, z = ~z2,
line = list(color = 'rgb(44, 160, 44)', width = 1)) %>%
add_trace(x = ~x3, y = ~y3, z = ~z3,
line = list(color = 'bcbd22', width = 1))

# Set up API credentials: https://plot.ly/r/getting-started


### 3D Density Plot

library(plotly)

dens <- with(diamonds, tapply(price, INDEX = cut, density))
data <- data.frame(
x = unlist(lapply(dens, "[[", "x")),
y = unlist(lapply(dens, "[[", "y")),
cut = rep(names(dens), each = length(dens[]\$x)))

p <- plot_ly(data, x = ~x, y = ~y, z = ~cut, type = 'scatter3d', mode = 'lines', color = ~cut) 