首先,尽量不要用具有特殊含义的词来命名变量。名称为 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,还可以选择不同类型的统计信息。