0

me very new programmer, I having problem with saving bar chart to png, bars aren't showing up.

My Code:

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')

What it should look like: here I'd like to save it as a png file, but it just comes up blank without the bars.

TeemoMain
  • 105
  • 1
  • 1
  • 8

1 Answers1

1

You simply need to swap the order in which the plt.show() appears and the plt.savefig('barchart.png')

plt.savefig('barchart.png')
plt.show()

The reason that plt.savefig doesn't work after calling show is that the current figure has been reset.

Source: https://stackoverflow.com/a/21884187/1577947

Jarad
  • 17,409
  • 19
  • 95
  • 154