Python中如何为Plotly Express直方图设置自定义分箱区间?
在Plotly Express直方图中设置自定义分箱区间的简单方法
你不需要提前用pandas的IntervalIndex手动分组,Plotly Express的histogram本身支持直接传入自定义分箱边界,这样可以避免Interval对象无法JSON序列化的错误。
实现步骤:
- 定义自定义分箱边界数组
- 直接在
px.histogram中使用bins参数指定该数组
完整代码示例:
import pandas as pd import plotly.express as px # 原始数据 df = pd.DataFrame({ 'x': [0.2, -0.1, -0.04, 0.07, 0.2], 'y': ['red', 'yellow', 'orange', 'red', 'red'] }) # 自定义分箱边界 custom_bins = [-1, -0.2, -0.1, -0.05, 0, 0.05, 0.1, 0.2, 1] # 生成直方图 fig = px.histogram(df, x='x', bins=custom_bins) fig.show()
如果需要按y列分组展示不同类别(比如颜色区分),只需添加color参数:
fig = px.histogram(df, x='x', bins=custom_bins, color='y') fig.show()
原方法出错原因:
pandas的Interval对象不属于JSON可序列化类型,Plotly渲染图表时需要将数据序列化为JSON,因此直接传入Interval类型的分组会触发错误。而使用Plotly内置的bins参数,会由库内部处理分箱逻辑,无需手动生成Interval对象。
内容的提问来源于stack exchange,提问作者geds133
相关产品推荐
相关产品推荐

