如何在Plotly中组合带箱线边际的直方图与折线图为上下子图?
解决方案
错误原因
你直接用fig.append_trace()传入Plotly Express生成的整个Figure对象,而该方法仅接受单个go.Trace对象,因此触发ValueError。此外,go.Histogram本身不支持marginal参数,所以需要提取Plotly Express生成的带边际箱线图的所有Trace,再整合到自定义子图中。
实现代码
import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd def Plot_Continuous(df, column_group, target): df = df.copy() # 计算按分组列聚合的目标列平均值 df_agg = df.groupby(column_group)[target].mean().sort_index().reset_index() df_agg.rename(columns={target: 'Average Selling Price'}, inplace=True) # 生成带边际箱线图的直方图Figure hist_fig = px.histogram(df, x=column_group, marginal="box", hover_data=df.columns) # 创建3行1列的子图,前两行共享X轴 fig = make_subplots( rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.05, row_heights=[0.2, 0.4, 0.4] # 调整行高,边际箱线图占比更小 ) # 将边际箱线图和直方图分别添加到前两行 fig.add_trace(hist_fig.data[1], row=1, col=1) fig.add_trace(hist_fig.data[0], row=2, col=1) # 添加折线图到第三行 line_fig = px.line(df_agg, x=column_group, y="Average Selling Price") fig.add_trace(line_fig.data[0], row=3, col=1) # 配置坐标轴标题 fig.update_xaxes(title_text=column_group, row=3, col=1) fig.update_yaxes(title_text="样本数量", row=2, col=1) fig.update_yaxes(title_text="", row=1, col=1) # 边际箱线图隐藏Y轴标题 fig.update_yaxes(title_text="平均售价", row=3, col=1) # 调整整体布局 fig.update_layout( height=800, width=1000, title_text=f"{column_group} 分布与{target}平均值趋势" ) fig.show() # 调用示例(假设你的数据集名为dataframe) Plot_Continuous(dataframe, 'Year', 'Selling_Price')
关键说明
- 提取Trace:Plotly Express生成的带
marginal="box"的直方图包含两个Trace:主图的直方图(hist_fig.data[0])和上方的边际箱线图(hist_fig.data[1]),需分别添加到子图的对应行。 - 共享X轴:通过
shared_xaxes=True让前两行的箱线图、直方图与第三行的折线图共享X轴,保证交互时坐标轴同步缩放。 - 行高调整:通过
row_heights设置边际箱线图的高度占比,还原原生marginal参数的紧凑效果。
内容的提问来源于stack exchange,提问作者Ernesto Lopez Fune
相关产品推荐
相关产品推荐

