直方图条不以pyplot.hist中的xticks为中心

时间:2017-12-08 10:00:09

标签: python matplotlib histogram

我想我只是没有使用正确的关键字,因为这可能之前已被问过,但我找不到解决方案。无论如何,我有一个问题,直方图的条形不与xticks排列。我希望条形图在它们对应的xticks上居中,但是它们被放置在刻度线之间以均匀地填充中间的空间。

enter image description here

import matplotlib.pyplot as plt  

data = [1, 1, 1, 1.5, 2, 4, 4, 4, 4, 4.5, 5, 6, 6.5, 7, 9,9, 9.5]

bins = [x+n for n in range(1, 10) for x in [0.0, 0.5]]+[10.0]

plt.hist(data, bins, rwidth = .3)
plt.xticks(bins)
plt.show()

1 个答案:

答案 0 :(得分:0)

请注意,您在此处绘制的不是直方图。直方图将是

import matplotlib.pyplot as plt  

data = [1, 1, 1, 1.5, 2, 4, 4, 4, 4, 4.5, 5, 6, 6.5, 7, 9,9, 9.5]

bins = [x+n for n in range(1, 10) for x in [0.0, 0.5]]+[10.0]

plt.hist(data, bins, edgecolor="k", alpha=1)
plt.xticks(bins)
plt.show()

enter image description here

此处,条形区间的范围如预期。例如。您在1 <= x < 1.5区间内有3个值。

从概念上讲,您想要做的是获取数据值计数的条形图。这根本不需要任何箱子,可以按如下方式完成:

import numpy as np
import matplotlib.pyplot as plt  

data = [1, 1, 1, 1.5, 2, 4, 4, 4, 4, 4.5, 5, 6, 6.5, 7, 9,9, 9.5]

u, inv = np.unique(data, return_inverse=True)
counts = np.bincount(inv)

plt.bar(u, counts, width=0.3)

plt.xticks(np.arange(1,10,0.5))
plt.show()

enter image description here

当然你可以&#34;误用&#34;直方图以获得类似的结果。这需要将条形图的中心移动到左边框边缘plt.hist(.., align="left")

import matplotlib.pyplot as plt  

data = [1, 1, 1, 1.5, 2, 4, 4, 4, 4, 4.5, 5, 6, 6.5, 7, 9,9, 9.5]

bins = [x+n for n in range(1, 10) for x in [0.0, 0.5]]+[10.0]

plt.hist(data, bins, align="left", rwidth = .6)
plt.xticks(bins)
plt.show()

这导致与上面相同的情节。

相关问题