簡體   English   中英

在 R plotly 中手動查找曲面上輪廓的精確坐標和 plot

[英]Find the exact coordinates of a contour on a surface and plot it manually in R plotly

我正在繪制表面 plot 並想“手動”使用plotly繪制輪廓線。 在下面的代碼中我:

  • 模擬繪制曲面的數據 plot
  • 使用contoureR儀 package 計算特定 z 水平的等高線坐標
  • 繪制曲面 plot 和輪廓線
# Load packages
library(plotly) # for interactive visualizations
library(contoureR) # for calculating contour coordinates

# 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

# Obtain coordinates of contour for z = 5
z_level <- 5
r <- contourLines(x = x, y = y, z = z1, levels = z_level)

plot_ly(
  type = "surface",
  x = x,
  y = y,
  z = z1,
) %>%
  add_trace(
    type = "scatter3d",
    x = r[[1]]$x,
    y = r[[1]]$y,
    z = z_level
  )

輪廓線1

我知道這些都是近似值,因此我還嘗試將由contourLines()生成的xy坐標傳遞給用於在上面創建z1的公式,並將相應的值用於 plot 我的等高線(而不是使用z_level = 5 ,但我仍然沒有得到想要的結果:

plot_ly(
  x = x,
  y = y,
  z = z1,
  type = "surface"
) %>%
  add_trace(
    type = "scatter3d",
    x = r[[1]]$x,
    y = r[[1]]$y,
    z = r[[1]]$x^0.2*r[[1]]$y^0.3
  )

輪廓線2

I alo know that plotly enables me to draw specific contour lines (see my question and answer here: Add a permanent contour line to a surface plot in R plotly ). 但是,我想自己繪制我的輪廓線(在獲得他們的坐標之后),這樣它就可以通過 cursor “拉”,並在我 hover 超過它時向我顯示工具提示信息。 理想情況下,如果有辦法獲得由plotly本身計算的等高線坐標,那就太好了。

謝謝您的幫助。

我能夠找到解決此問題的兩種方法。

解決方案1:轉置z1矩陣

@nirgrahamuk 給了我第一個解決方案,它包括轉置z1矩陣:

library(plotly) # for interactive visualizations

# 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

# Obtain coordinates of contour for z = 5
z_level <- 6
r <- contourLines(x = x, 
                  y = y, 
                  z = z1, 
                  levels = z_level)

plot_ly(
  type = "surface",
  z = t(z1), # *** WE TRANSPOSE THE MATRIX HERE! ***
) %>%
  add_trace(
    type = "scatter3d",
    x = r[[1]]$x,
    y = r[[1]]$y,
    z = z_level
  )

解決方案2:使用isoband package

第二種解決方案是使用isoband::isolines() function 計算等高線坐標:

library(plotly) # for interactive visualizations
library(isoband) # for find contour lines coordinates

# 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

# Obtain coordinates of contour for z = 5
z_level <- 6
r <- isolines(x = x, # *** WE USE THE isolines() FUNCTION HERE ***
              y = y, 
              z = z1, 
              levels = z_level)

plot_ly(
  type = "surface",
  z = z1, 
) %>%
  add_trace(
    type = "scatter3d",
    x = r[[1]]$x,
    y = r[[1]]$y,
    z = z_level
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM