如何用Python Plotly定义函数批量绘制正态分布图表?
可复用Plotly正态分布直方图函数
直接定义一个封装所有重复逻辑的函数,将每个图表的可变参数作为输入,即可避免重复编写相似代码:
import plotly.figure_factory as ff import plotly.express as px def plot_normal_distribution( dist_data_series, hist_data_df, column_name, group_label, hist_parameters, ucl_value, lcl_value, mean_value, three_sigma_limits, chart_title="Normal distribution", x_axis_title="Laser Power", y_axis3_title="Frequency" ): # 创建正态分布曲线 fig = ff.create_distplot( [dist_data_series.tolist()], group_labels=[group_label], show_hist=False, curve_type="normal", bin_size=hist_parameters["Range"] ) # 添加直方图并配置Y轴 hist_trace = px.histogram(hist_data_df, x=column_name, nbins=hist_parameters["bins"], opacity=0.8).data[0] hist_trace.yaxis = "y3" hist_trace.name = "histogram" fig.add_trace(hist_trace) # 添加UCL、LCL、均值、3σ参考线 fig.add_vline(y0=0, x=ucl_value, line_dash="longdash", annotation_text=f"UCL: <br>{format(ucl_value)}", annotation_position="bottom") fig.add_vline(y0=0, x=lcl_value, line_dash="longdash", annotation_text=f"LCL: <br>{format(lcl_value)}", annotation_position="bottom") fig.add_vline(y0=0, x=mean_value, line_dash="dashdot", annotation_text=f"µ: <br>{'{:.3f}'.format(mean_value)}", annotation_position="bottom") fig.add_vline(y0=0, x=three_sigma_limits["+3Sigma_Grenze"], line_dash="longdash", annotation_text=f"+3σ-limit: <br>{'{:.3f}'.format(three_sigma_limits['+3Sigma_Grenze'])}", annotation_position="bottom right", line_color="red") fig.add_vline(y0=0, x=three_sigma_limits["-3Sigma_Grenze"], line_dash="longdash", annotation_text=f"-3σ-limit: <br>{'{:.3f}'.format(three_sigma_limits['-3Sigma_Grenze'])}", annotation_position="bottom", line_color="red") # 更新图表布局 fig.update_layout( yaxis3={"overlaying": "y", "side": "right"}, showlegend=True, title_text=chart_title, bargap=0.2, yaxis3_title=y_axis3_title, xaxis_title=x_axis_title ) return fig
参数说明
dist_data_series: 用于生成正态分布曲线的目标列Series(例:fscl_without_outl_P2["P2"])hist_data_df: 绘制直方图的数据源DataFrame(例:without_outl_P2)column_name: 目标列的名称(例:"P2")group_label: 正态分布曲线的分组标签(例:"LP 2.4kW")hist_parameters: 直方图配置字典,需包含"Range"(bin_size)和"bins"(nbins)两个键(例:fsc_hist_parameter["P2"])ucl_value: UCL控制限值(对应原代码的OEG)lcl_value: LCL控制限值(对应原代码的UEG)mean_value: 数据均值(例:df_12m["HP LPIFS_Wert P2"].mean())three_sigma_limits: 3σ限值字典,需包含"+3Sigma_Grenze"和"-3Sigma_Grenze"两个键(例:Sigma_limit["P2_3Sigma"])chart_title: 图表标题(可选,默认值:"Normal distribution")x_axis_title: X轴标题(可选,默认值:"Laser Power")y_axis3_title: 右侧Y轴标题(可选,默认值:"Frequency")
调用示例
对应原代码的调用方式:
# 准备各参数 dist_series = fscl_without_outl_P2["P2"] hist_df = without_outl_P2 target_col = "P2" curve_label = "LP 2.4kW" hist_config = fsc_hist_parameter["P2"] ucl = OEG lcl = UEG mean_val = df_12m["HP LPIFS_Wert P2"].mean() sigma_limits = Sigma_limit["P2_3Sigma"] # 生成并显示图表 fig2 = plot_normal_distribution( dist_series, hist_df, target_col, curve_label, hist_config, ucl, lcl, mean_val, sigma_limits ) fig2.show()
后续需要绘制其他列的图表时,只需替换对应参数即可,无需重复编写整个绘图逻辑。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

