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

如何基于阈值范围为Plotly散点图标记配置自定义颜色

按阈值范围自定义Plotly散点图颜色的解决方案

我来帮你搞定这个颜色映射的问题!核心思路是先根据你的阈值范围给每个数据点分配对应的颜色,再把这个颜色列表传给Plotly的marker.color参数,就能实现你想要的多颜色标记效果了。

步骤1:给DataFrame添加颜色映射列

我们可以用numpy.select()来根据阈值区间匹配颜色,这个方法比pd.cut更直观,能直接指定你想要的颜色值。

步骤2:修改Plotly绘图代码

把原来固定的marker_color替换成我们刚生成的颜色列,同时修正你代码里的语法问题(比如列名需要用引号包裹,hovertemplate的写法也要调整)。

完整的代码示例如下:

import pandas as pd
import numpy as np
import plotly.graph_objects as go

# 构造你的DataFrame
data = {
    'cpu node': ['node 1', 'node 2', 'node 3', 'node 4', 'node 5', 'node 6'],
    'threshold': [20, 30, 50, 59, 65, 95]
}
df = pd.DataFrame(data)

# 定义阈值条件和对应的颜色
conditions = [
    df['threshold'] <= 25,
    (df['threshold'] > 25) & (df['threshold'] <= 50),
    (df['threshold'] > 50) & (df['threshold'] <= 75),
    df['threshold'] > 75
]
colors = ['green', 'lightgreen', 'yellow', 'red']

# 新增颜色列
df['point_color'] = np.select(conditions, colors)

# 修改后的绘图代码
fig = go.Figure(go.Scatter(
    mode="markers",
    x=df['cpu node'],  # 修正列名引用方式
    y=df['threshold'],
    marker_symbol='triangle-up',
    marker_line_color="midnightblue",
    marker_color=df['point_color'],  # 使用映射后的颜色列
    marker_line_width=2,
    marker_size=15,
    hovertemplate='CPU节点: %{x}<br>阈值: %{y}%<extra></extra>'  # 修复hover模板格式
))

# 可以添加一些图表美化设置
fig.update_layout(
    title='CPU节点阈值分布',
    xaxis_title='CPU节点',
    yaxis_title='阈值(%)',
    yaxis_range=[0, 100]
)

fig.show()

代码说明

  • numpy.select()会按顺序匹配每个数据点的条件,给它分配对应的颜色,完全符合你设定的区间规则:
    • 0-25% → 绿色(green)
    • 25-50% → 浅绿色(lightgreen)
    • 50-75% → 黄色(yellow)
    • 75%以上 → 红色(red)
  • 修正了你原代码里的变量引用问题:列名需要用df['列名']的方式调用,不能直接写空格分隔的名称
  • 优化了hovertemplate,让悬浮提示更清晰规范

运行这段代码后,你就能看到每个节点的标记颜色根据阈值范围自动变化啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 14:37:28