在绘图表面上使用条件着色 [英] Use conditional coloring on a plotly surface

查看:82
本文介绍了在绘图表面上使用条件着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用R绘图,并尝试根据网格创建一个表面并根据计算对其进行着色.

I am using plotly via R for the first time and trying to create a surface from a grid and color it based on a calculation.

例如,我想使用data(volcano)中的表面,如

For example, I would like to use the surface from data(volcano), as in

library(plotly)
plot_ly(z = ~volcano) %>% add_surface()

但是,不是基于z值(高度)为颜色,而是要基于距我的房子在小台面上的距离(20,60)进行着色.

But instead of color based on the z-value (altitude), let's just say I wanted to color based on distance from my house on the little mesa at (20,60) .

house_loc <- c(20,60,150) # (x,y,z) of my house
dist_to_house <- Vectorize(function(x,y,z){sqrt(sum( (c(x,y,z)-house_loc)^2 ))})

到目前为止,我已经尝试过:

So far I have tried:

color_me <-function(x){
  colorRampPalette(c('tan','blue')
  )(24L)[findInterval(x,seq(0,1,length.out=25),
                      all.inside=TRUE)]
} 

library(dplyr)
library(reshape2)
volcano %>% 
     melt( varnames=c('y','x'),value.name='z' ) %>%
     mutate( d = dist_to_house(x, y, z) ,
             d_rel = d/max(d),
             d_color = color_me(d_rel) 
     ) -> df

plot_ly(df,
        type='scatter3d',
        mode='none', # no markers, just surface
        x=~x,
        y=~y,
        z=~z,
        surfaceaxis=2,
        surfacecolor=~d_color) # last argument seems not to work

哪个会返回:

所需的结果将使房屋区域的棕褐色变色,并在远离房屋的区域逐渐变淡为蓝色.

The desired result would color the landscape tan in the region of the house and gradually fade to blue in the regions far from the house.

有些相关问题使用在其他地方找到的mesh3d代码并且不解释如何计算(i,j,k)

Somewhat related question uses mesh3d code found elsewhere and doesn't explain how to calculate (i, j, k)

推荐答案

您的代码实际上具有所需的一切,只需使用surface图并将距离数组用作color.

Your code virtually has everything you need, just use a surface plot and use your distance array as the color.

library(plotly)
library(dplyr)
library(reshape2)

house_loc <- c(20,60,150)
dist_to_house <- Vectorize(function(x,y,z){sqrt(sum( (c(x,y,z)-house_loc)^2 ))})

volcano %>% 
  melt( varnames=c('y','x'),value.name='z' ) %>%
  mutate( d = dist_to_house(x, y, z) ,
          d_rel = d/max(d)
  ) -> df

color <- df$d_rel
dim(color) <- dim(volcano)

plot_ly(df,
        type='surface',
        z=volcano,
        surfacecolor=color,
        colors=c('tan','blue'))

这篇关于在绘图表面上使用条件着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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