我是一个非常新的程序员,我在将条形图保存到png时遇到问题,条形图没有显示出来。
我的代码:
import numpy as np
import matplotlib.pyplot as plt
N = 3
ind = np.arange(N)
width = 0.35
Start_means = (100, 50, 50)
Start_std = (2, 3, 4)
End_means = (80, 30, 30)
End_std = (3, 5, 2)
fig, ax = plt.subplots()
rects1 = ax.bar(ind, Start_means, width, color='xkcd:red', yerr=Start_std)
rects2 = ax.bar(ind+width, End_means, width, color='xkcd:black', yerr=End_std)
ax.legend((rects1[0], rects2[0]), ('Start', 'End'))
ax.set_ylabel('Available')
ax.set_title('Travel availability, by tour')
ax.set_xticks(ind + width/2)
countries = ['Italy', 'China', 'France']
ids = ['ID:12345', 'ID:13579', 'ID:24680']
xlabels = []
for i, j in zip(countries, ids):
xlabels.append(i + '\n' + j)
ax.set_xticklabels(xlabels)
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show()
plt.savefig('barchart.png')
它应该是什么样的:here 我想将它保存为png文件,但它只是空白而没有条形。
答案 0 :(得分:1)
您只需要更换plt.show()
出现的顺序和plt.savefig('barchart.png')
plt.savefig('barchart.png')
plt.show()
在调用show之后plt.savefig无法工作的原因是 目前的数字已经重置。