R: "Coloring" 根据另一个变量作图

R: "Coloring" plotly plots according to another variable

我正在使用 R 编程语言。我正在尝试在此处复制 Stack Overflow post 中提供的答案:

假设我有以下“数据框”(“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" - 然后根据 "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)
      )

但是这个returns几个错误,比如:

我尝试了不同的方法来调试这段代码,但我似乎无法弄明白。有人可以告诉我如何解决这些错误吗?

我修复了您的一些 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().


注意:如果仍然不能正常工作,请post你的sessionInfo(),因为代码在[=12]之后对我有效=]更正和添加arguments.