gpt4 book ai didi

python - 如何在直方图中居中标签

转载 作者:太空狗 更新时间:2023-10-29 19:34:46 29 4
gpt4 key购买 nike

我有一个 numpy 数组 results 看起来像

[ 0.  2.  0.  0.  0.  0.  3.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  0.
0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.
0. 1. 1. 0. 0. 0. 0. 2. 0. 3. 1. 0. 0. 2. 2. 0. 0. 0.
0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0.
0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 3. 1. 0. 0. 0. 0. 0.
0. 0. 0. 1. 0. 0. 0. 1. 2. 2.]

我想绘制它的直方图。我试过了

import matplotlib.pyplot as plt
plt.hist(results, bins=range(5))
plt.show()

这给了我一个直方图,x 轴标记为 0.0 0.5 1.0 1.5 2.0 2.5 3.0。 3.5 4.0

我希望 x 轴标记为 0 1 2 3,而不是在每个条形的中心标记。你怎么做到的?

最佳答案

其他答案只是不适合我。使用 plt.bar 而不是 plt.hist 的好处是 bar 可以使用 align='center':

import numpy as np
import matplotlib.pyplot as plt

arr = np.array([ 0., 2., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0.,
0., 0., 2., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1., 1.,
0., 0., 0., 0., 2., 0., 3., 1., 0., 0., 2., 2., 0.,
0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0.,
0., 0., 2., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 3., 1., 0., 0., 0., 0., 0., 0.,
0., 0., 1., 0., 0., 0., 1., 2., 2.])

labels, counts = np.unique(arr, return_counts=True)
plt.bar(labels, counts, align='center')
plt.gca().set_xticks(labels)
plt.show()

centering labels in a histogram

关于python - 如何在直方图中居中标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23246125/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com