[英]R: “Coloring” plotly plots according to another variable
我正在使用 R 編程語言。 我試圖在這里復制此 Stack Overflow 帖子中提供的答案: Color Surface by variable with plotly in R
假設我有以下“數據框”(“my_grid”):
library(plotly)
library(dplyr)
#create grid and evaluate function
input_1 <- seq(0,100,1)
input_2 <- seq(0,100,1)
input_3 <- seq(0,100,1)
input_4 <- seq(0,100,1)
my_grid <- data.frame(input_1, input_2, input_3, input_4)
my_grid$final_value = sin(input_1) + cos(input_2) + input_3 + input_4
我們可以看到這個數據框的樣子:
head(my_grid)
input_1 input_2 input_3 input_4 final_value
1 0 0 0 0 1.000000
2 1 1 1 1 3.381773
3 2 2 2 2 4.493151
4 3 3 3 3 5.151128
5 4 4 4 4 6.589554
6 5 5 5 5 9.324738
問題:我想用變量“input_1”、“input_2”、“input_3”制作一個 3D 曲面圖 - 然后根據“final_value”為曲面着色
plot_ly() %>%
add_trace(data = my_grid, x=my_grid$input_1, y=my_grid$input_2, z=my_grid$input_3, type="mesh3d" )
%>% add_surface(surfacecolor = my_grid$final_value,
cauto=F,
cmax=max(my_grid$final_value),
cmin=min(my_grid$final_value)
)
但這會返回幾個錯誤,例如:
Error: unexpected SPECIAL in "%>%"
Error: unexpected ',' in " cauto=F,"
我嘗試了不同的方法來調試這段代碼,但我似乎無法弄清楚。 有人可以告訴我如何解決這些錯誤嗎?
我修復了您的一些syntax
並將z = my_grid %>% as.matrix()
到您的代碼中,現在它可以按預期工作。 見下文,
plot_ly() %>%
add_trace(data = my_grid, x=my_grid$input_1, y=my_grid$input_2, z=my_grid$input_3, type='mesh3d') %>%
add_surface(
z = my_grid %>% as.matrix(),
surfacecolor = my_grid,
cauto=F,
cmax=max(my_grid$final_value),
cmin=min(my_grid$final_value)
)
您的第一個錯誤如下,
foo()
%>% bar()
為了使%>%
按預期工作,它必須內聯結束括號。
更正syntax
,我收到Error: 'z' must be a numeric matrix
。 因此我添加了z = my_grid %>% as.matrix()
。
注意:如果它仍然不能按預期工作,請發布您的sessionInfo()
,因為代碼在syntax
更正和添加arguments.
后對我arguments.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.