【问题标题】:Add a permanent contour line to a surface plot in R plotly将永久等高线添加到 R plotly 中的曲面图
【发布时间】:2021-03-28 16:23:32
【问题描述】:

我正在使用 R 中的plotly 包来绘制曲面图和等高线图:

# Load package
library(plotly)

# Simulate the data for plotting
x <- y <- seq(from = 0, to = 100, by = 1)
z1 <- outer(X = x, Y = y, FUN = function(x, y) x^0.2 * y^0.3) # data for surface plot

# Draw surface plot (3D)
plotly::plot_ly(z = z1) %>%
  plotly::add_surface(
    contours = list(
      z = list(
        show = TRUE,
        usecolormap = TRUE,
        highlightcolor = "#ff0000",
        project = list(z = TRUE)
      ) 
    )    
  ) 

# Draw contour plot (2D)
plot_ly(z = z1) %>%
  add_contour()

这两个图的渲染包含等高线,显示了xy 的组合,它们产生了一个常数z 水平。在 3D 曲面图的情况下,将鼠标悬停在其上会动态绘制一条等高线,鼠标所在的位置会在 3 维空间的一侧上投影等高线。

我想做的是通过自己指定z 的值(例如z = 5)在两个图上手动绘制一条或多条等高线。

【问题讨论】:

标签: r plotly contour r-plotly surface


【解决方案1】:

感谢@IRTFM 的评论,我能够找到我的问题的答案。答案更具体到等高线图。用户需要将contours 参数下的startend 属性设置为所需的z 值。下面,我绘制了z = 5 的等高线:

# Load package
library(plotly)

# Simulate the data for plotting
x <- y <- seq(from = 0, to = 100, by = 1)
z1 <- outer(X = x, Y = y, FUN = function(x, y) x^0.2 * y^0.3) # data for surface plot

plot_ly(
  z = z1,
  type = "contour",
  autocontour = FALSE,    
  colorscale = "RdBu",
  
  contours = list(
    start = 5,
    end = 5,
    showlabels = TRUE,
    showlines = TRUE,
    coloring = "lines"
  )
  
) %>%
 hide_guides()

如果想要绘制 2 条特定的等高线,他们需要一个额外的参数:ncontours = 2。不这样做可能会导致绘制超过 2 条等高线 - z 值介于 startend 之间的线。

plot_ly(
  z = z1,
  type = "contour",
  autocontour = FALSE,
  
  ncontours = 2,
  
  colorscale = "RdBu",
  
  contours = list(
    start = 5,
    end = 7,
    showlabels = TRUE,
    showlines = TRUE,
    coloring = "lines"
  )
  
) %>%
 hide_guides()

最后,对于2个以上的特定等高线,我们需要使用add_contour()函数。让我们绘制 4 个特定的等高线图:

plot_ly(
  z = z1,
  type = "contour",
  autocontour = FALSE,
  
  ncontours = 2,
  
  colorscale = "RdBu",
  
  contours = list(
    start = 5,
    end = 7,
    showlabels = TRUE,
    showlines = TRUE,
    coloring = "lines"
  )
  
) %>% 
  
  add_contour(
    
    ncontours = 2,
    
    contours = list(
      start = 4,
      end = 6,
      showlabels = TRUE,
      showlines = TRUE,
      coloring = "lines"
    )
    
  ) %>%
  
  hide_guides()

【讨论】:

    猜你喜欢
    • 2010-12-26
    • 2018-05-06
    • 2021-07-08
    • 2020-08-24
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2018-08-31
    • 2017-02-08
    相关资源
    最近更新 更多