from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
if __name__ == "__main__":fig1 = ...print("start plotting")canvas = FigureCanvasQTAgg(fig1)canvas.draw()canvas.show()
I have written to function which returns a matplotlib.figure object. I have run the above script. It has crashed Python. How do I do this?
The reasons I have worked with FigureCanvasQTAgg and matplotlib.figure instead of working with matplotlib.pyplot is that the Figure object also allow me to do something like
with PdfPages(...) as pdf_writer:canvas = FigureCanvasPDF(fig1)pdf_writer.savefig(fig1)pdf_writer.savefig(fig1)
which writes out two copies of the same figure in a single pdf file. Also it would allow me to write write multiple figures into the same PDF. I am unaware of any way we can do this using only matplotlib.pyplot
The easiest and best way to show a figure in matplotlib is to use the pyplot interface:
import matplotlib.pyplot as plt
fig1= plt.figure()
plt.show()
For creating the output in the form of a pdf file, you'd use:
import matplotlib.pyplot as plt
fig1= plt.figure()
plt.savefig("filename.pdf")
If you want to save multiple figures to the same pdf file, use matplotlib.backends.backend_pdf.PdfPages("output.pdf")
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdffig1= plt.figure()
ax=fig1.add_subplot(111)outfile = "output.pdf"
with matplotlib.backends.backend_pdf.PdfPages(outfile) as pdf_writer:pdf_writer.savefig(fig1)pdf_writer.savefig(fig1)
A complete example of how to save multiple figures created from the same function would be
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdfdef plot(data):fig= plt.figure()ax = fig.add_subplot(111)ax.plot(data)return figfig1 = plot([1,2,3])
fig2 = plot([9,8,7])outfile = "output.pdf"
with matplotlib.backends.backend_pdf.PdfPages(outfile) as pdf_writer:pdf_writer.savefig(fig1)pdf_writer.savefig(fig2)
FigureCanvasQTAgg
is meant to be used in a PyQt GUI, which you will need to create first, if you want to use that. This question shows you how to do that but it seems a bit of an overkill for just showing or saving the figure.