【问题标题】:How can I use a float for the bin size in a histogram plot?如何在直方图中使用浮点数作为 bin 大小?
【发布时间】:2021-06-10 21:54:21
【问题描述】:

我有一个列表,我想在 Python 中使用 0.01 的 bin 大小制作直方图:

plt.hist(list, bins = 0.01)

我不断收到一个类型错误,说 bin 只能是整数、字符串或数组。无论如何在 Python 中使用浮点数作为 binsize 绘制直方图?

【问题讨论】:

  • 您的问题现在回答了吗?还是未解决?

标签: python python-3.x matplotlib histogram


【解决方案1】:

首先,尽量不要用具有特殊含义的词来命名变量。名称为 list 的变量会阻止在代码中进一步使用 list 命令。

bins= 参数可以是单个数字,在这种情况下,它被解释为 bin 的数量。所以,它必须是一个严格的正整数。如果要设置特定的 bin 大小,则需要提供所需 bin 边缘的完整列表。最简单的方法是使用np.arange(start, stop, step)。

import matplotlib.pyplot as plt
import numpy as np

mylist = np.random.randn(1000) / 10
plt.hist(mylist, bins=np.arange(min(mylist), max(mylist)+0.01, step=0.01), color='turquoise')

如果最小值不是一个很好的整数,np.arange 将遵循该模式。要获得 bin 边缘的“好”值,您可以舍入 start 的 np.arange。例如:

import matplotlib.pyplot as plt
import numpy as np

mylist = np.random.randn(10, 1000).cumsum(axis=1).ravel() / 500
step = 0.01
start = np.floor(min(mylist) / step) * step
stop = max(mylist) + step
bin_edges = np.arange(start, stop, step=step)
plt.hist(mylist, bins=bin_edges, color='crimson', ec='white')
plt.xticks(bin_edges, rotation=90)
plt.tight_layout()
plt.show()

PS:请注意,seaborn 的 sns.histplot 支持的参数比 matplotlib 的 plt.hist 更多。 sns.histplot 可以选择binwidth 和/或binrange,还可以选择不同类型的统计信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2011-10-22
    • 2016-12-25
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多