python - 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 没有的功能。
非常感谢。
解决方案
如果您愿意在外面处理分箱,您可以设置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()
推荐阅读
- sql - 带有额外数据的 SQL 表破坏了 SELECT 语句
- c# - 当 TabControl 中的选项卡更改时,对 ItemsControl 的 ItemsSource 的更改未在 UI 中更新
- xcode - XCTest:由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“参数“test”不得为 nil。
- spring-boot - Spring Boot 微服务 - Kafka Kerberos - PCF 中的 krb5 和 jaas 配置文件 - PCF 中的部署
- c# - 如何在动态选择中使用表达式创建“内联 if 语句”以进行空值检查
- javascript - 检查一个javascript数组是否包含另一个数组的所有元素或部分元素值
- javascript - 在 webpack 捆绑库上模拟 fbasyncInit 行为
- reactjs - 在哪里调用将在渲染之前发生的 Ajax 请求?
- postgresql - 在命令行中执行postgresql命令时如何将参数与文件一起传递?
- biztalk - 根据源的存在向目标添加额外的节点