Jim Blum
Jim Blum

Reputation: 2646

Saving a plot in python creates only an empty pdf document

I am using the example code that exists at the official matplotlib page http://matplotlib.org/examples/api/barchart_demo.html

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

def autolabel(rects):
    # attach some text labels
    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()

This plot, is shown absolutely correctly. However, if I want to save it, using the following command exactly at the bottom of the code, it does not save the plot.

plt.savefig("result.pdf")

Is it something I make wrong?

Upvotes: 3

Views: 6938

Answers (1)

CT Zhu
CT Zhu

Reputation: 54380

Move the plt.savefig("result.pdf") line before plt.show() should save the plot correctly as a pdf file.

You might be using a interactive backend. After plt.show(), a window containing the plot pops up. If you then close the window, the plot is gone (similar to a plt.close() call). Therefore, plt.savefig() has nothing to save if you do that after closing the plot window.

Upvotes: 7

Related Questions