Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlaying line on contour plot using Plotly

Tags:

r

plotly

r-plotly

I'd like to overlay a line on top a Plotly contour plot, similar to overlaying a line on an image of a matrix in which the intensity represents position in z within R3:

# Generate an arbitrary matrix
m <- matrix(sin(1:6^2) * 1:6, nrow = 6)

# Define a path
path <- data.frame(x = c(0:7), y = c(0, 1, 2, 2, 3, 3, 4, 6))

image(x = 1:6, y = 1:6, z = m, col = gray.colors(20), xlab = "x", ylab = "y")
lines(path$x, path$y)

Which renders:

Line and matrix plot

Using Plotly, I have attempted

library(plotly)
plot_ly(x = 1:6, y = 1:6, z = t(m), type = "contour") %>% 
  add_lines(x = path$x, y = path$y)

Which generates a contour plot overlaid with a wireframe of empty R3 space rather than a line:

enter image description here

like image 217
mduprey Avatar asked Jun 09 '18 13:06

mduprey


Video Answer


1 Answers

You could try this:

plot_ly(x = 1:6, y = 1:6, z = t(m), type = "contour") %>% 
  add_trace(x = c(1, 2, 3, 4, 5, 6), y = c(1, 2, 3, 3, 4, 5), type = "scatter", mode = "line")

It gives you almost what you want. Hope it helps!

enter image description here

like image 73
MLavoie Avatar answered Sep 18 '22 06:09

MLavoie