R:Plot_ly带有跟踪线的3d图

时间:2017-06-18 20:22:08

标签: r plotly

我正在使用4.7.0。我正在尝试将3d线添加到3d plot_ly曲面图中。当我没有在plot_ly调用中添加add_lines()函数时,它看起来很好。只要我添加add_lines,图表就会全部搞砸,并且不会添加3d线图。

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

1 个答案:

答案 0 :(得分:1)

以下是带有3D线的曲面图的代码 我使用add_trace代替add_lines绘制了3D线。

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

enter image description here