x 轴介于 0 和 1 之间的条形图

barchart with x-axis between 0 and 1

我有一个非常愚蠢的问题,我不知道为什么会这样。我只是尝试创建一个非常简单的条形图,但结果不是预期的那样:

import operator
hist = {1.0: 16173, 0.99: 2597, 0.98: 1162, 0.97: 765, 0.96: 533, 0.95: 422, 0.94: 369, 0.93: 280, 0.92: 258, 0.91: 231, 0.9: 207, 0.89: 199, 0.88: 184, 0.87: 177, 0.86: 155, 0.85: 152, 0.84: 140, 0.83: 140, 0.82: 126, 0.81: 116, 0.8: 113, 0.77: 105, 0.79: 97, 0.75: 94, 0.71: 94, 0.76: 86, 0.65: 85, 0.72: 85, 0.74: 83, 0.63: 83, 0.54: 82, 0.66: 77, 0.52: 77, 0.59: 76, 0.78: 76, 0.73: 75, 0.68: 75, 0.53: 73, 0.55: 73, 0.69: 72, 0.7: 72, 0.58: 72, 0.57: 70, 0.62: 70, 0.6: 68, 0.67: 64, 0.51: 63, 0.64: 61, 0.56: 59, 0.61: 50, 0.5: 34}

total = sum(hist.values())
sorted_seq = sorted(hist.iteritems(), key= operator.itemgetter(0))
x = [i[0] for i in sorted_seq]
y = [i[1]/float(total) for i in sorted_seq]
plt.figure() 
ax = plt.subplot()
bins = ax.bar(x,y,align='center')

ax.set_ylim((min(y),max(y)+0.01))
ax.autoscale(True,'x',True)

x 轴应限制为 0,并且 1.but 仍然更进一步,看起来非常有线。使用 ax.set_xlim(0,1) 没有解决问题。知道为什么会这样吗?

我认为是自动缩放覆盖了 set_xlim 命令。另外,请注意,xlim 采用元组(如 set_ylim!)。这是我试过的代码:

import matplotlib.pylab as plt
import operator

from collections import Counter

hist = Counter({1.0: 16173, 0.99: 2597, 0.98: 1162, 0.97: 765, 0.96: 533, 0.95: 422, 0.94: 369, 0.93: 280, 0.92: 258, 0.91: 231, 0.9: 207, 0.89: 199, 0.88: 184, 0.87: 177, 0.86: 155, 0.85: 152, 0.84: 140, 0.83: 140, 0.82: 126, 0.81: 116, 0.8: 113, 0.77: 105, 0.79: 97, 0.75: 94, 0.71: 94, 0.76: 86, 0.65: 85, 0.72: 85, 0.74: 83, 0.63: 83, 0.54: 82, 0.66: 77, 0.52: 77, 0.59: 76, 0.78: 76, 0.73: 75, 0.68: 75, 0.53: 73, 0.55: 73, 0.69: 72, 0.7: 72, 0.58: 72, 0.57: 70, 0.62: 70, 0.6: 68, 0.67: 64, 0.51: 63, 0.64: 61, 0.56: 59, 0.61: 50, 0.5: 34})

total = sum(hist.values())
sorted_seq = sorted(hist.iteritems(), key= operator.itemgetter(0))
x = [int(i[0]) for i in sorted_seq]
print(x)
y = [i[1]/float(total) for i in sorted_seq]
print(y)
plt.figure() 
ax = plt.subplot(1, 1, 1)
bins = ax.bar(x,y,align='center')

ax.set_ylim((min(y),max(y)+0.01))
ax.set_xlim((0, 1))
ax.set_xlabel('conf',fontsize=15)
ax.set_ylabel('freq',fontsize=15)
#ax.autoscale(True,'x',True)

plt.show()

结果是:

希望这能回答您的问题!

你需要给ax.bar参数width,否则它被设置为默认值0.8

bins = ax.bar(x,y,width=0.01,align='center')

当你没有设置 width 时你有 xmax = 1.4 的原因是因为 align = 'center'(意思是你的 xmax1 + 0.8/2 = 1.4