如何获取Plotly Express直方图的分箱大小并设置X轴刻度?
问题描述
需要在Plotly中绘制概率密度直方图,获取分箱大小并将分箱刻度标记在X轴上,但现有设置X轴刻度的代码无效。现有Plotly代码如下:
fig = px.histogram(df_de["len_job_task"], histnorm='probability density') bin_edges = fig['data'][0]['xbins']['end'] fig.update_layout(xaxis=dict(tickmode='array', tickvals=bin_edges)) fig.update_traces(marker_line_color='black', marker_line_width=1) fig.show()
期望实现类似Matplotlib的效果:指定分箱数量后获取分箱边缘,再设置X轴刻度,对应Matplotlib代码:
n, bins, patches = plt.hist(df_de["len_job_task"], bins=20, edgecolor='black') plt.xticks(bins[::2]) plt.xlabel("Bins") plt.ylabel("Length")
解决方案
问题原因
之前的代码仅提取了xbins['end'],这只是最后一个分箱的边界值(单个数值),而非完整的分箱边缘数组,因此X轴刻度设置无效。
实现步骤
- 指定分箱数量:在Plotly绘图时通过
nbins参数指定分箱数,对应Matplotlib的bins=20。 - 生成完整分箱边缘数组:从Plotly直方图的
xbins属性中提取分箱起始值、结束值和宽度,生成完整的分箱边缘数组。 - 设置X轴刻度:将生成的分箱边缘数组(可按需间隔选取)设置为X轴刻度,并配置轴标签。
完整代码
import plotly.express as px import numpy as np # 绘制概率密度直方图,指定分箱数量为20 fig = px.histogram(df_de["len_job_task"], histnorm='probability density', nbins=20) # 获取分箱的起始、结束位置及宽度 xbins = fig['data'][0]['xbins'] start = xbins['start'] end = xbins['end'] bin_width = xbins['size'] # 生成完整的分箱边缘数组,与Matplotlib返回的bins一致 bin_edges = np.arange(start, end + bin_width, bin_width) # 设置X轴刻度(间隔选取刻度,对应Matplotlib的bins[::2]) fig.update_layout( xaxis=dict( tickmode='array', tickvals=bin_edges[::2], ticktext=[f'{val:.2f}' for val in bin_edges[::2]] # 可选:格式化刻度文本,保留两位小数 ), xaxis_title="Bins", yaxis_title="Length" ) # 设置直方图边框样式 fig.update_traces(marker_line_color='black', marker_line_width=1) fig.show()
额外说明
如果需要更精确地控制分箱范围,也可以直接手动定义分箱边缘数组,传递给px.histogram的bins参数:
# 手动定义分箱边缘(20个分箱对应21个边缘点) custom_bins = np.linspace(df_de["len_job_task"].min(), df_de["len_job_task"].max(), 21) fig = px.histogram(df_de["len_job_task"], histnorm='probability density', bins=custom_bins) # 后续设置刻度的代码与上述一致
内容的提问来源于stack exchange,提问作者Christian01
相关产品推荐
相关产品推荐

