如何用Plotly将不同API组的变更趋势图并排展示
Plotly Subplot 实现多API组变更趋势图并排展示
实现步骤与代码示例
1. 前期准备与数据预处理
先确保数据格式正确,提取所有唯一的API组,确定子图布局:
import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # 确保日期字段为datetime格式 df['commit_date'] = pd.to_datetime(df['commit_date']) # 获取所有API组 api_groups = df['api_group'].unique() group_count = len(api_groups) # 定义子图布局:每行2个图,自动计算行数 cols = 2 if group_count >=2 else 1 rows = (group_count + 1) // 2
2. 创建Subplot容器
初始化子图对象,设置共享轴、子图标题等:
fig = make_subplots( rows=rows, cols=cols, subplot_titles=[f"API Group: {g}" for g in api_groups], shared_xaxes=True, # 共享X轴方便时间趋势对比 vertical_spacing=0.1 # 子图间垂直间距 )
3. 循环填充子图数据
遍历每个API组,在对应子图中绘制Breaking/Non-Breaking两条折线:
for idx, group in enumerate(api_groups, 1): # 筛选当前组数据 group_data = df[df['api_group'] == group] breaking = group_data[group_data['type_of_change'] == 'Breaking'] non_breaking = group_data[group_data['type_of_change'] == 'Non-Breaking'] # 计算当前子图的行列位置 row = (idx - 1) // cols + 1 col = (idx - 1) % cols + 1 # 添加Breaking趋势线 fig.add_trace( go.Scatter( x=breaking['commit_date'], y=breaking['count'], name='Breaking', mode='lines+markers', line_color='red' ), row=row, col=col ) # 添加Non-Breaking趋势线 fig.add_trace( go.Scatter( x=non_breaking['commit_date'], y=non_breaking['count'], name='Non-Breaking', mode='lines+markers', line_color='blue' ), row=row, col=col )
4. 调整整体布局并展示
统一设置图表样式,优化显示效果:
fig.update_layout( height=400 * rows, # 根据行数动态调整高度 width=1000, title_text="各API组变更趋势对比", legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1) ) # 统一设置轴标签 for i in range(1, rows+1): fig.update_yaxes(title_text='变更次数', row=i, col=1) if cols >=2: fig.update_yaxes(title_text='变更次数', row=i, col=2) fig.update_xaxes(title_text='提交日期', row=rows, col=1) if cols >=2: fig.update_xaxes(title_text='提交日期', row=rows, col=2) # 渲染图表 fig.show()
关键细节说明
- 若API组数量较多,可将
cols改为3,对应行数计算为rows = (group_count + 2) // 3 shared_xaxes可根据需求关闭,让每个子图独立显示X轴- 可通过修改
mode参数切换折线/标记点的显示样式
内容的提问来源于stack exchange,提问作者Brie MerryWeather
相关产品推荐
相关产品推荐

