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

Plotly:如何为每个Y误差条设置与对应标记一致的独立颜色

Fix: Match Error Bar Colors to Marker Colors in Plotly Graph Objects

Got it, I ran into this exact issue before too! Since Plotly Graph Objects doesn't let you pass a color list directly to error bars in a single Scatter trace, here's a straightforward workaround that keeps you in full control without needing Plotly Express:

The Core Idea

Instead of adding one trace for all data points, we'll create a separate Scatter trace for each individual point. This way, we can set a unique color for both the marker and error bar of each trace, ensuring they match perfectly.

Working Code

import numpy as np
import plotly.graph_objects as go

x_data = ['10 days', '20 days', '30 days']
y_data = [0.5, 0.8, 0.4]
err_y_data = [0.1, 0.2, 0.05]
colors = ['rgba(93, 164, 214, 0.7)', 'rgba(255, 144, 14, 0.7)', 'rgba(44, 160, 101, 0.7)']

fig = go.Figure()

# Loop through each data point to create a separate trace
for x, y, err, color in zip(x_data, y_data, err_y_data, colors):
    fig.add_trace(go.Scatter(
        x=[x],  # Wrap in list to treat as single data point
        y=[y],
        text=[np.round(y, 1)],
        mode='markers+text',
        textposition='top center',
        error_y=dict(
            type='data',
            color=color,  # Now we can set individual error bar color
            array=[err],
            visible=True
        ),
        marker=dict(color=color, size=12)
    ))

# Optional: Adjust layout to keep the clean look
fig.update_layout(
    xaxis_title='Time Period',
    yaxis_title='Value',
    showlegend=False  # Hide legend since each trace is a single point
)

fig.show()

Key Details

  • We use zip() to iterate through each set of x, y, error, and color values together
  • Each trace is limited to one data point by wrapping x, y, text, and err in lists
  • The error_y.color parameter now accepts a single color per trace, which matches the marker's color
  • We disable the legend since having a legend entry for every single point isn't useful here (you can re-enable it if needed)

This approach works seamlessly even when adding subplots—you just apply the same loop logic to each subplot's figure object, keeping full control over all plot elements.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:02:54