我有一个包含值的数组,我想创建它的直方图。我主要对低端号码感兴趣,想把每一个300以上的号码都收集到一个箱子里。此 bin 应与所有其他(同样宽的) bin 具有相同的宽度。我怎样才能做到这一点?
注意:这个问题与这个问题有关:Defining bin width/x-axis scale in Matplotlib histogram
这是我到目前为止所尝试的:
import matplotlib.pyplot as plt
import numpy as np
def plot_histogram_01():
np.random.seed(1)
values_A = np.random.choice(np.arange(600), size=200, replace=True).tolist()
values_B = np.random.choice(np.arange(600), size=200, replace=True).tolist()
bins = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 600]
fig, ax = plt.subplots(figsize=(9, 5))
_, bins, patches = plt.hist([values_A, values_B], normed=1, # normed is deprecated and will be replaced by density
bins=bins,
color=['#3782CC', '#AFD5FA'],
label=['A', 'B'])
xlabels = np.array(bins[1:], dtype='|S4')
xlabels[-1] = '300+'
N_labels = len(xlabels)
plt.xlim([0, 600])
plt.xticks(25 * np.arange(N_labels) + 12.5)
ax.set_xticklabels(xlabels)
plt.yticks([])
plt.title('')
plt.setp(patches, linewidth=0)
plt.legend()
fig.tight_layout()
plt.savefig('my_plot_01.png')
plt.close()
这是结果,看起来不太好:
然后我在其中更改了 xlim 行:
plt.xlim([0, 325])
结果如下:
它看起来或多或少像我想要的那样,但最后一个垃圾箱现在不可见。我缺少哪个技巧来可视化宽度为 25 的最后一个 bin?