You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly R中基于Speed设置Cone(锥图)的颜色?

如何在Plotly R中基于Speed值为锥图(Cone)着色?

问题描述

我拥有一个向量场,希望基于speed(速度)值为锥图(cone)着色,而非当前默认颜色。已查阅Plotly R官方文档,但仅找到坐标轴、颜色标度等相关颜色设置,未找到锥图基于速度着色的方法,请问是否可实现该需求?

复现代码与数据如下:

plot_dat <- structure(list(vb = structure(c(-3.02, -115.799, 203.187, 1, 
-0.715, -115.701, 202.444, 1, -3.024, -114.397, 201.275, 1, -2.058, 
-116.181, 203.556, 1, 4.437, -116.153, 205.384, 1, 4.471, -114.791, 
210.117, 1, 12.443, -105.538, 198.121, 1, 4.985, -107.238, 192.985, 
1, 5.458, -107.907, 193.987, 1, 5.061, -115.557, 207.515, 1, 
6.809, -114.172, 208.797, 1, 5.8, -115.493, 205.988, 1, 4.943, 
-111.077, 198.177, 1), dim = c(4L, 13L)), material = list(), 
    normals = NULL, texcoords = NULL, meshColor = "vertices", 
    it = structure(c(1L, 2L, 3L, 4L, 5L, 2L, 2L, 1L, 4L, 6L, 
    1L, 3L, 7L, 8L, 9L, 3L, 8L, 7L, 6L, 4L, 1L, 10L, 11L, 12L, 
    7L, 6L, 3L, 11L, 6L, 7L, 2L, 5L, 13L, 7L, 9L, 13L, 11L, 7L, 
    12L, 6L, 11L, 10L, 3L, 2L, 13L, 5L, 10L, 12L, 9L, 8L, 13L, 
    13L, 8L, 3L, 4L, 6L, 10L, 5L, 4L, 10L, 7L, 13L, 12L, 12L, 
    13L, 5L), dim = c(3L, 22L))), class = c("mesh3d", "shape3d"
))

cones <- structure(c(-0.09, -0.69, 0.383, 0.323, 0.588, 0.136, 0.097, 
0.169, 0.592, 0.058, 0.536, 0.611, 0.086, -0.994, -0.135, 0.871, 
-0.914, 0.738, 0.989, 0.703, 0.172, -0.64, 0.198, 0.842, 0.69, 
-0.971, -0.064, 0.711, 0.306, 0.244, -0.329, 0.058, -0.705, 0.971, 
0.491, -0.979, -0.064, -0.388, 0.224), dim = c(13L, 3L), dimnames = list(
    NULL, c("u", "v", "w")))

speed <- c(0.114, 0.02, 0.55, 0.514, 0.064, 0.296, 0.017, 0.634, 0.537, 
0.735, 0.339, 0.485, 0.921)

plot_ly() |>
  add_trace(
    type="cone",
    name = "CV Vectors",
    x = plot_dat$vb[1,],
    y = plot_dat$vb[2,],
    z = plot_dat$vb[3,],
    u = cones[,1],
    v = cones[,2],
    w = cones[,3],
    sizemode= 'absolute',
    sizeref= 2,
    hovertext = ~paste0("Speed (m/s) ", 
                        round(speed, 3))
  )

解决方案

可以实现,Plotly的锥图支持通过color参数指定着色依据的变量,结合colorscale和colorbar参数即可完成基于speed值的自定义着色。

修改后的完整代码如下:

plot_ly() |>
  add_trace(
    type="cone",
    name = "CV Vectors",
    x = plot_dat$vb[1,],
    y = plot_dat$vb[2,],
    z = plot_dat$vb[3,],
    u = cones[,1],
    v = cones[,2],
    w = cones[,3],
    sizemode= 'absolute',
    sizeref= 2,
    hovertext = ~paste0("Speed (m/s) ", 
                        round(speed, 3)),
    # 新增着色相关参数
    color = speed,  # 指定颜色映射为speed向量
    colorscale = "Viridis",  # 设置色阶,可选其他内置色阶如"Plasma"、"RdBu"等
    colorbar = list(title = "Speed (m/s)")  # 配置颜色条标题
  )

参数说明

  • color = speed:直接将每个锥图的颜色与对应的speed值绑定,实现基于速度的着色
  • colorscale:定义颜色渐变的范围,Plotly提供多种内置色阶,也可以通过自定义RGB数组来创建专属色阶
  • colorbar:用于配置颜色条的显示,包括标题、位置、刻度等,提升图表的可读性

内容的提问来源于stack exchange,提问作者myfatson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:15:25