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

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

问题描述

我第一次通过 R 使用 plotly 并尝试从网格创建一个表面并根据计算为它着色.

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

图书馆(情节)plot_ly(z = ~volcano) %>% add_surface()

但不是基于 z 值(高度)的颜色,而是说我想根据离我家在 (20,60) 处的小台面上的距离来着色.

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

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

color_me <-function(x){colorRampPalette(c('tan','blue'))(24L)[findInterval(x,seq(0,1,length.out=25),all.inside=TRUE)]}图书馆(dplyr)图书馆(重塑2)火山%>%融化(varnames=c('y','x'),value.name='z')%>%变异( d = dist_to_house(x, y, z) ,d_rel = d/max(d),d_color = color_me(d_rel)) ->dfplot_ly(df,type='scatter3d',mode='none', # 没有标记,只是表面x=~x,y=~y,z=~z,表面轴=2,surfacecolor=~d_color) # 最后一个参数似乎不起作用

刚刚返回的:

预期的结果是将房屋区域的景观染成棕褐色,并在远离房屋的区域逐渐褪色为蓝色.

有点

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.

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

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

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

Which just returns:

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.

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

解决方案

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天全站免登陆