You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何为Plotly Express直方图设置自定义分箱区间?

在Plotly Express直方图中设置自定义分箱区间的简单方法

你不需要提前用pandas的IntervalIndex手动分组,Plotly Express的histogram本身支持直接传入自定义分箱边界,这样可以避免Interval对象无法JSON序列化的错误。

实现步骤:

  1. 定义自定义分箱边界数组
  2. 直接在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:15:07