【问题标题】:Plotly: How to customize different bin widths for a plotly histogram?Plotly:如何为 plotly 直方图自定义不同的 bin 宽度?
【发布时间】:2020-10-23 01:58:12
【问题描述】:

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

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

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

非常感谢。

【问题讨论】:

  • @Adrien 如果您的回答对您有用,请考虑投票和/或接受它。
  • @Adrien 我的建议对你有什么效果?
  • @vestland 感谢您的快速回答。您的建议确实有效,但如果您使用 go.bar 则不能使用 plotly histogram 方法。我认为您必须在自定义数据分箱或使用绘图直方图的所有功能和方法之间做出选择。

标签: python plotly width histogram bins


【解决方案1】:

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

完整代码

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()

【讨论】: