pyplot x轴刻度线间距不以所有列为中心

pyplot x-axis tick mark spacing is not centered with all columns

我正在努力解决我希望是 pyplot 直方图函数的错误指定。正如您在图像中看到的,根据 align='mid' 参数,x 轴刻度线未始终居中在列上。如有必要,我会将数据文件上传到 Dropbox。 感谢您的帮助!

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

data = DRA_size_males_s

fig, ax = plt.subplots(nrows=1, ncols=1)
ax.hist(data, facecolor='blue', edgecolor='gray', bins=25, rwidth=1.10, align='mid')


bins=[1.4,1.5,1.6,1.7,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.1,3.2,3.5,3.6,3.8] 
ax.set_xticks(bins)

ax.set_ylabel('Frequency')
ax.set_xlabel('DRA Sizes(mm)')

ax.set_title('Frequencies of DRA Sizes in Males (mm)')

plt.show()

这是用于创建直方图的数据数组: 1.4, 1.4, 1.4, 1.5, 1.5, 1.6, 1.7, 1.7, 1.7, 1.9, 1.9, 1.9, 1.9, 2.0, 2.0, 2.0, 2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.3, 2.3, 2.3, 2.4, 2.5, 2.6, 2.7, 2.7, 2.8, 2.8, 2.8, 2.9, 2.9, 3.1, 3.1, 3.2, 3.2, 3.5, 3.6, 3.8

尝试将 binsrange 值减去一个小的偏移量一起使用,如下例所示。

In [100]: x = np.array([1, 2, 3, 4, 0, 3, 1, 7, 4, 5, 8, 8, 9, 7, 7, 3])

In [101]: len(x)
Out[101]: 16

In [102]: bins = np.arange(10) - 0.5

In [103]: plt.hist(x, facecolor='blue', edgecolor='gray', bins=bins, rwidth=2, alpha=0.75)

现在,bin 编号将 center 对齐。

plt.histalign="mid" 参数将直方图的条形居中放置在 bin 边缘之间的中间 - 这实际上是绘制直方图的常用方法。

为了使直方图使用预定义的 bin 边缘,您需要将这些 bin 边缘提供给 plt.hist 函数。

import matplotlib.pyplot as plt
import numpy as np

data = [1.4, 1.4, 1.4, 1.5, 1.5, 1.6, 1.7, 1.7, 1.7, 1.9, 1.9, 1.9, 1.9, 2.0, 
        2.0, 2.0, 2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.3, 2.3, 2.3, 2.4, 2.5, 2.6, 
        2.7, 2.7, 2.8, 2.8, 2.8, 2.9, 2.9, 3.1, 3.1, 3.2, 3.2, 3.5, 3.6, 3.8]

fig, ax = plt.subplots(nrows=1, ncols=1)

bins=[1.4,1.5,1.6,1.7,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3.1,3.2,3.5,3.6,3.8]

ax.hist(data, bins=bins, facecolor='blue', edgecolor='gray', rwidth=1, align='mid') 
ax.set_xticks(bins)

ax.set_ylabel('Frequency')
ax.set_xlabel('DRA Sizes(mm)')
ax.set_title('Frequencies of DRA Sizes in Males (mm)')

plt.show()