如何将计数添加到直方图? [英] How can I add the counts to the histogram plot?
本文介绍了如何将计数添加到直方图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将直方图的计数数据添加到matplotlib中的绘图中.这是我的数据;
I want to add the counts data of histogram to the plot in matplotlib. Here is my data;
import matplotlib.pyplot as plt
data = [['B', 1], ['C', 2], ['A', 3],['A', 4], ['B', 5], ['B', 6],['A', 7], ['B', 8], ['C', 9],['D',10]]
df = pd.DataFrame(data, columns = ['Name', 'Count'])
plt.hist(df['Name'])
plt.show()
结果是这样的; 结果1
我尝试使用plt.text
和value_counts()
,但是它们的排序方式有所不同...
I tried to use plt.text
and value_counts()
but their sorting are different...
import matplotlib.pyplot as plt
data = [['B', 1], ['C', 2], ['A', 3],['A', 4], ['B', 5], ['B', 6],['A', 7], ['B', 8], ['C', 9],['D',10]]
df = pd.DataFrame(data, columns = ['Name', 'Count'])
xvals = np.arange(len(df['Name'].value_counts()))
yvals = list(df['Name'].value_counts())
for i in range(len(df['Name'].value_counts())):
plt.text(x=xvals[i], y=yvals[i],s=df['Name'].value_counts(sort=False)[i])
plt.hist(df['Name'])
plt.show()
所以,我得到这样的结果; 结果2
So, I get a result like this; result2
我认为应该没那么困难,但是我找不到任何解决方案.
I think it mustn't be so difficult but I can't find any solution.
推荐答案
您可以尝试执行以下操作:
You can try something like this:
hist
返回计数,垃圾箱和补丁.
patches
是矩形的列表.然后,您可以使用面片矩形的计数和坐标来注释轴.
hist
returns counts, bins and patches.
patches
is a list of rectangles. Then you can annotate the axis using the count and coordinates of the patch rectangles.
import numpy as np
import matplotlib.pyplot as plt
# generate some random data
x = np.random.randn(10000)
x = x * 100
x = x.astype(np.int)
# plot the histogram of the data
bins = np.arange(-300,300,20)
fig = plt.figure(figsize=(15,4))
ax = plt.gca()
counts, _, patches = ax.hist(x, bins=bins,edgecolor='r')
for count, patch in zip(counts,patches):
ax.annotate(str(int(count)), xy=(patch.get_x(), patch.get_height()))
plt.show()
这篇关于如何将计数添加到直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文