简体   繁体   中英

R: Plot_ly 3d graph with trace line

I am using plotly 4.7.0. I am trying to add a 3d line to a 3d plot_ly surface plot. When I don't add the add_lines() function inside of the plot_ly call it looks fine. As soon as I do add the add_lines, the graph gets all messed up and doesn't add the 3d line graph.

library(plotly)
m_x = seq(-2, 2, .01)
m_y = seq(-2, 2, .01)
df = expand.grid(m_x, m_y)
df['matrix'] = exp(-(df$Var1^2+df$Var2^2))
m_z = matrix(df$matrix, nrow = length(m_x), ncol = length(m_y))
m_df = list(m_x, m_y, m_z)

x1 = seq(-2, 0, by=0.0202)
y1 = runif(100, min=-0.03,max=0.03)
z1 = exp(-(x1^2+y1^2))
df = data.frame(x1, y2, z2)
names(df) <- c("df_x", "df_y", "df_z")


colors = c( "Blue",  "Cyan", "Green", "Yellow", "Orange", "Red")
p1 <- plot_ly(x = m_df[[1]], y = m_df[[2]], z = m_df[[3]],
              colors = colors, color = m_df[[3]]) %>% add_surface()  %>%
  add_lines(x = df$df_x, y = df$df_y, z = df$df_z, data = df, 
            line = list(color = 'red', width = 1)) %>%
  layout(title = "Hike_Example",
       scene = list(aspectratio = list(x = 4, y = 4, z = 1)))

p1

Here is the code of the surface plot with the 3D line.
I plotted the 3D line using add_trace in place of add_lines .

library(plotly)
m_x = seq(-2, 2, .01)
m_y = seq(-2, 2, .01)
df = expand.grid(m_x, m_y)
df['matrix'] = exp(-(df$Var1^2+df$Var2^2))
m_z = matrix(df$matrix, nrow = length(m_x), ncol = length(m_y))
m_df = list(m_x, m_y, m_z)

x1 = seq(-2, 0, by=0.0202)
y1 = runif(100, min=-0.03,max=0.03)
z1 = exp(-(x1^2+y1^2))
df = data.frame(x1, y1, z1)
names(df) <- c("df_x", "df_y", "df_z")

colors = c( "Blue",  "Cyan", "Green", "Yellow", "Orange", "Red")
p1 <- plot_ly(x = m_df[[1]], y = m_df[[2]], z = m_df[[3]],
              colors = colors, color = m_df[[3]]) %>% add_surface()  %>%
  add_trace(x = ~df_x, y = ~df_y, z = ~df_z, data = df, 
            type="scatter3d", mode="lines",
            line = list(color = "red", width = 4)) %>%
  layout(title = "Hike_Example",
       scene = list(aspectratio = list(x = 4, y = 4, z = 1)))

p1

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM