Reputation: 5897
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?
Upvotes: 0
Views: 208
Reputation: 1945
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.
Upvotes: 1