如何在Python Plotly子图直方图中添加箱线图与均值竖线
Plotly 三列子图:直方图+均值竖线+顶部箱线图
实现思路
- 构建2行3列的子图网格,顶部行放置箱线图(占比20%高度),底部行放置直方图(占比80%高度)
- 为每个世代分别添加箱线图、直方图,并插入指定均值的红色虚线标注
- 统一对齐x轴、调整布局样式,保证视觉一致性
完整代码
import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # 示例数据(替换为你的实际数据) data = { "Generation": ["Millenials"]*100 + ["Generation X"]*100 + ["Boomers"]*100, "NumCompaniesWorked": list(pd.Series([2,3,1,2,4]).sample(100, replace=True)) + list(pd.Series([3,4,2,5,3]).sample(100, replace=True)) + list(pd.Series([4,5,3,6,4]).sample(100, replace=True)) } df = pd.DataFrame(data) # 各世代指定均值 mean_values = { "Millenials": 2.2, "Generation X": 3.4, "Boomers": 4.1 } # 创建子图布局 fig = make_subplots( rows=2, cols=3, shared_xaxes=True, vertical_spacing=0.05, subplot_titles=("Millenials", "Generation X", "Boomers"), row_heights=[0.2, 0.8] ) # 遍历添加每个世代的图表 generations = ["Millenials", "Generation X", "Boomers"] for col_idx, gen in enumerate(generations, 1): gen_data = df[df["Generation"] == gen]["NumCompaniesWorked"] # 添加顶部箱线图 fig.add_trace( go.Box(y=gen_data, boxpoints=False, fillcolor="#cce5ff"), row=1, col=col_idx ) # 添加底部直方图 hist_trace = px.histogram(gen_data, nbins=10).data[0] hist_trace.fillcolor="#99c2ff" fig.add_trace(hist_trace, row=2, col=col_idx) # 添加均值竖线及标注 fig.add_vline( x=mean_values[gen], line_dash="dash", line_color="#ff4d4d", annotation_text=f"均值: {mean_values[gen]}", annotation_position="top right", row=2, col=col_idx ) # 调整整体样式 fig.update_layout( height=600, width=1000, title_text="各世代就职公司数量分布", showlegend=False, title_x=0.5 ) # 隐藏顶部箱线图的x轴(与底部共享) fig.update_xaxes(visible=False, row=1) # 设置底部直方图的y轴标题 fig.update_yaxes(title_text="人数", row=2, col=1) fig.update_yaxes(title_text="人数", row=2, col=2) fig.update_yaxes(title_text="人数", row=2, col=3) fig.show()
核心细节说明
- 子图比例:通过
row_heights控制箱线图与直方图的高度占比,突出直方图的分布展示 - 均值标注:红色虚线配合右上角文本标注,清晰展示各世代的指定均值
- 样式优化:箱线图隐藏离群点标记,统一填充色,提升视觉简洁度
- 轴对齐:
shared_xaxes=True保证三个子图的x轴刻度完全对齐,避免视觉混乱
内容的提问来源于stack exchange,提问作者WF30
相关产品推荐
相关产品推荐

