Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

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_pdf

fig1= 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_pdf

def plot(data):
    fig= plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(data)
    return fig

fig1 = 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...