我有一个非常愚蠢的问题,我不知道为什么会这样。我只试图创建一个非常简单的条形图,但结果不是预期的结果:
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.但仍然是非常有线的外观。使用ax.set_xlim(0,1)
没有解决问题。知道为什么会这样吗?
答案 0 :(得分:4)
你需要给ax.bar
width
参数,否则它被设置为默认值0.8
bins = ax.bar(x,y,width=0.01,align='center')
您未设置xmax = 1.4
时width
的原因是align = 'center'
(意味着您的xmax
为1 + 0.8/2 = 1.4
)
答案 1 :(得分:-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()
结果是:
希望这能回答你的问题!