R:“着色"根据另一个变量绘图 [英] R: "Coloring" plotly plots according to another variable

查看:30
本文介绍了R:“着色"根据另一个变量绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 R 编程语言.我试图在这里复制这篇 Stack Overflow 帖子中提供的答案:

注意:如果它仍然不能按预期工作,请发布您的 sessionInfo(),因为代码在 syntax 修正和添加参数.

I am working with the R programming language. I am trying to replicate the answer provided in this Stack Overflow post over here: Color surface by variable with plotly in R

Suppose I have the following "data frame" ("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

We can see how this data frame looks like:

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

Question: I want to make a 3D surface plot with variables "input_1", "input_2", "input_3" - And then color the surface according to "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)
      )

But this returns several errors, such as:

  • Error: unexpected SPECIAL in "%>%"
  • Error: unexpected ',' in " cauto=F,"

I have tried different ways to debug this code, but I can't seem to figure it out. Can someone please show me how to fix these errors?

解决方案

I fixed some of your syntax and added z = my_grid %>% as.matrix() to your code, and it works as intended now. See below,

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)
        )

Your first error were the following,

foo()
%>% bar()

In order for the %>% to work as intended, it has to be inline of ending parenthesis.

When the syntax were corrected, I got the Error: 'z' must be a numeric matrix. And therefore I added z = my_grid %>% as.matrix().


Note: If it still doesn't work as intended, please post your sessionInfo(), as the code worked for me after syntax correction and addition of arguments.

这篇关于R:“着色"根据另一个变量绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆