Saving matplotlib plots as PDF

I recently started using matplotlib together with PyQt, and I love it. It’s awesome and has many more features compared to PyQWT. However, I needed to save the plots to a PDF file. Here is how you do that:

import matplotlib.backends.backend_pdf
...
@QtCore.pyqtSlot()
def printPlots(self):
filename,_ = QtGui.QFileDialog.getSaveFileName(self, "Save plots as PDF file", "", "Portable Document File (*.pdf)")
if filename == "":
return
pp = matplotlib.backends.backend_pdf.PdfPages(filename)
pp.savefig(self.plotFigure)
pp.close()

Assuming that your figure is called self.plotFigure. You can connect the above slot to a QAction and map it to some nice menu item or shortcut.

2 thoughts on “Saving matplotlib plots as PDF”

  1. Thanks.

    With my (newer 2013) version getSaveFileName returns a list of strings, which wont be compatible as a filename. Rather put "filename,_ = QtGui.QFileDialog.getSaveFileName …" (note the comma underscore)

Leave a Reply

Your email address will not be published. Required fields are marked *