首页 > 解决方案 > Plotly:如何为 plotly 直方图自定义不同的 bin 宽度?

问题描述

我正在尝试使用具有不同/可自定义宽度的 bin 显示直方图。似乎 Plotly 只允许使用xbins = dict(start , end, size).

例如,我希望一组整数在 1 到 10 之间的数据显示一个直方图,其中的 bin 表示 [1,5[、[5,7[ 和 [7,11[] 中元素的份额。使用 Matplotlib,您可以使用表示 bin 间隔的数组来完成此操作,但使用 plotly 似乎我必须选择一个统一的宽度。

顺便说一句,我没有使用 Matplotlib,因为 Plotly 允许我使用 Matplotlib 没有的功能。

非常感谢。

标签: pythonplotlywidthhistogrambins

解决方案


如果您愿意在外面处理分箱,您可以设置go.bar对象中的宽度go.Bar(width=<widths>)来获得这个:

在此处输入图像描述

完整代码

import numpy as np
import plotly.express as px
import plotly.graph_objects as go

# sample data
df = px.data.tips()

# create bins
bins1 = [0, 15, 50]
counts, bins2 = np.histogram(df.total_bill, bins=bins1)
bins2 = 0.5 * (bins1[:-1] + bins2[1:])

# specify sensible widths
widths = []
for i, b1 in enumerate(bins1[1:]):
    widths.append(b1-bins2[i])

# plotly figure
fig = go.Figure(go.Bar(
    x=bins2,
    y=counts,
    width=widths # customize width here
))

fig.show()

推荐阅读