【发布时间】:2016-10-03 23:02:09
【问题描述】:
使用 matplotlib 的 hist 函数,如何让它在条形图上显示每个 bin 的计数?
例如,
import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)
我们怎样才能让每个 bin 中的计数显示在它的条上?
【问题讨论】:
标签: python matplotlib histogram
使用 matplotlib 的 hist 函数,如何让它在条形图上显示每个 bin 的计数?
例如,
import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)
我们怎样才能让每个 bin 中的计数显示在它的条上?
【问题讨论】:
标签: python matplotlib histogram
好像hist不能这样,你可以写一些像:
your_bins=20
data=[]
arr=plt.hist(data,bins=your_bins)
for i in range(your_bins):
plt.text(arr[1][i],arr[0][i],str(arr[0][i]))
【讨论】:
不是单独使用plt.hist() 的解决方案,而是添加了一些功能。
如果您不想事先指定您的 bin 并且只绘制密度条,但还想显示 bin 计数,您可以使用以下内容。
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(100)
density, bins, _ = plt.hist(data, density=True, bins=20)
count, _ = np.histogram(data, bins)
for x,y,num in zip(bins, density, count):
if num != 0:
plt.text(x, y+0.05, num, fontsize=10, rotation=-90) # x,y,str
结果如下:
【讨论】:
有一种新的plt.bar_label 方法可以自动标记条形容器。
plt.hist 返回 bar 容器作为第三个输出:
data = np.random.default_rng(123).rayleigh(1, 70)
counts, edges, bars = plt.hist(data)
# ^
plt.bar_label(bars)
如果您有一个分组或堆叠的直方图,bars 将包含多个容器(每组一个),所以迭代:
fig, ax = plt.subplots()
counts, edges, bars = ax.hist([data, data * 0.3], histtype='barstacked')
for b in bars:
ax.bar_label(b)
请注意,您也可以通过ax.containers 访问酒吧容器:
for c in ax.containers:
ax.bar_label(c)
【讨论】: