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

如何在Python的Plotly箱线图中用线条连接同颜色的数据点

Connecting Same-Color Points with Lines in Plotly Strip + Box Plot

Hey there! I see you've got a solid start with your box and strip plot combo, and you want to add lines connecting points that share the same color to highlight matching groups across your traces. That's a great way to make relationships between your data points more visible—let's get that working for you.

First, note your original code was missing the import for plotly.graph_objects as go (you’re using go.Box but hadn’t imported it), so we’ll fix that first. The core trick here is to iterate over each unique color value, pull out all points with that color, and add a line trace connecting them across your two x-axis categories ("trace 0" and "trace 1").

Here’s the modified code that delivers your desired effect:

import plotly.express as px
import plotly.graph_objects as go  # Added missing import
import numpy as np
import pandas as pd

np.random.seed(1)
y0 = np.random.randn(50) - 1
y1 = np.random.randn(50) + 1

# Create your original dataframe
df = pd.DataFrame({
    'graph_name': ['trace 0']*len(y0) + ['trace 1']*len(y1),
    'value': np.concatenate([y0, y1], 0),
    'color': np.random.choice([0,1,2,3,4,5,6,7,8,9], size=100, replace=True)
})

# Build the base strip and box plots as before
fig = px.strip(df, x='graph_name', y='value', color='color', stripmode='overlay')
fig.add_trace(go.Box(y=df.query('graph_name == "trace 0"')['value'], name='trace 0'))
fig.add_trace(go.Box(y=df.query('graph_name == "trace 1"')['value'], name='trace 1'))

# Convert string x categories to numerical values for line plotting
df['x_num'] = df['graph_name'].map({'trace 0': 0, 'trace 1': 1})

# Iterate over each unique color to add connecting lines
for color_val in df['color'].unique():
    # Filter data to only include this color
    color_data = df[df['color'] == color_val]
    # Skip colors with only one point (nothing to connect)
    if len(color_data) < 2:
        continue
    # Grab the matching color from Plotly's default qualitative palette
    color = px.colors.qualitative.Plotly[color_val % len(px.colors.qualitative.Plotly)]
    # Add a line trace connecting the points
    fig.add_trace(go.Scatter(
        x=color_data['x_num'],
        y=color_data['value'],
        mode='lines',
        line=dict(color=color, width=1),
        showlegend=False  # Hide lines from legend to keep it clean
    ))

# Update layout + restore original x-axis category labels
fig.update_layout(
    autosize=False,
    width=600,
    height=600,
    legend={'traceorder':'normal'},
    xaxis=dict(
        tickmode='array',
        tickvals=[0, 1],
        ticktext=['trace 0', 'trace 1']
    )
)

fig.show()

Key Changes Explained:

  • Numerical x-axis mapping: We converted your string x categories to numbers so Plotly can draw lines between points across the two groups.
  • Color-matched lines: We use Plotly’s default qualitative color palette to ensure lines perfectly match the strip plot points of the same color.
  • Clean legend: Line traces are hidden from the legend to avoid clutter—only your original color groups and box plots appear.
  • Skipped single-point colors: We skip any color that only has one data point, since there’s nothing to connect.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:02:28