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

如何用Plotly创建与Seaborn样式一致的子图?

Plotly实现2行1列共享X轴的分组折线子图

参考Seaborn实现效果(模拟你的原有代码)

先确认你用Seaborn实现的核心逻辑,以下是同逻辑的示例代码:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 生成示例数据
np.random.seed(42)
dates = pd.date_range(start='2023-01-01', periods=30)
groups = ['A', 'B', 'C']
data = []
for date in dates:
    for group in groups:
        value = np.random.normal(loc=10 if group == 'A' else 20 if group == 'B' else 30, scale=2)
        data.append({'date': date, 'group': group, 'value': value})
df = pd.DataFrame(data)

# Seaborn实现2行1列共享X轴分组折线图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
sns.lineplot(data=df[df['group'].isin(['A', 'B'])], x='date', y='value', hue='group', ax=ax1)
sns.lineplot(data=df[df['group'] == 'C'], x='date', y='value', ax=ax2)
ax1.set_title('Group A & B')
ax2.set_title('Group C')
ax2.set_xlabel('Date')
plt.tight_layout()
plt.show()

Plotly正确实现代码

针对你尝试失败的问题,核心是要正确开启子图X轴共享,并匹配分组数据的轨迹添加逻辑:

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np

# 使用与Seaborn一致的示例数据
np.random.seed(42)
dates = pd.date_range(start='2023-01-01', periods=30)
groups = ['A', 'B', 'C']
data = []
for date in dates:
    for group in groups:
        value = np.random.normal(loc=10 if group == 'A' else 20 if group == 'B' else 30, scale=2)
        data.append({'date': date, 'group': group, 'value': value})
df = pd.DataFrame(data)

# 创建2行1列子图,开启X轴共享
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=('Group A & B', 'Group C'))

# 第一行子图添加A、B组折线
for group in ['A', 'B']:
    group_data = df[df['group'] == group]
    fig.add_trace(
        go.Scatter(x=group_data['date'], y=group_data['value'], name=group, mode='lines'),
        row=1, col=1
    )

# 第二行子图添加C组折线
c_data = df[df['group'] == 'C']
fig.add_trace(
    go.Scatter(x=c_data['date'], y=c_data['value'], name='C', mode='lines'),
    row=2, col=1
)

# 布局优化:仅底部子图显示X轴标签,调整整体尺寸
fig.update_layout(height=600, width=1000, title_text='共享X轴的分组折线子图')
fig.update_xaxes(title_text='Date', row=2, col=1)
fig.show()

核心注意点

  • 必须在make_subplots中设置shared_xaxes=True,确保两个子图的X轴缩放、平移完全同步
  • 通过row和col参数明确指定每个折线轨迹所属的子图位置
  • 用subplot_titles设置子图标题,通过update_xaxes仅在底部子图添加X轴标签,避免重复显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:10:45