通过变量在R中绘制颜色表面

时间:2019-06-11 06:45:10

标签: r plotly r-plotly

使用volcano数据,我想用另一个变量为火山的表面着色,变量是矩阵MatrixForColor,其大小与volcano相同,并且仅包含1和2(二进制)。对于MatrixForColor = 1MatrixForColor = 2,我想分别设置蓝色和红色。

Formatting of persp3d plot的启发,我设法使用persp3d包中的rgl实现了这一目标,如下所示:

library(rgl)    
color = c("blue", "red")
type  = MatrixForColor
persp3d(volcano, theta=50, phi=25, expand=0.75, col=color[type],
        ticktype="detailed", xlab="", ylab="", zlab="", axes=TRUE)

并获得此图:

enter image description here

我还尝试通过plotly(在plotly - different colours for different surfaces的响应之后进行调整)来实现此目标,如下所示:

library(plotly)
plot_ly(colors = c('blue', 'red')) %>%
  add_surface(z = volcano,
              opacity = 0.8,
              surfacecolor=MatrixForColor,
              cauto=F,
              cmax=1,
              cmin=0
  )

但是我得到这个数字:

enter image description here

这不是我想要的,因为它在MatrixForColor之后没有显示为红色和蓝色。

有人知道如何使用plotly来做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您需要为cmincmax设置正确的值:

library(plotly)

MatrixForColor <- matrix(1, nrow = nrow(volcano), ncol = ncol(volcano))
MatrixForColor[, 1:30] <- 2

plot_ly(colors = c('blue', 'red')) %>%
  add_surface(z = volcano,
              opacity = 0.8,
              surfacecolor = MatrixForColor,
              cauto=F,
              cmax=max(MatrixForColor),
              cmin=min(MatrixForColor)
  )

enter image description here