为什么没有图片显示 [英] why does no picture show
问题描述
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
if __name__ == "__main__":
fig1 = ...
print("start plotting")
canvas = FigureCanvasQTAgg(fig1)
canvas.draw()
canvas.show()
我已经写了一个返回matplotlib.figure对象的函数。我已经运行了上面的脚本。它使Python崩溃了。我该怎么做?
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?
我使用FigureCanvasQTAgg和matplotlib.figure而不是使用matplotlib.pyplot的原因是Figure对象还允许我做某事像
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)
写出两个副本单个pdf文件中的同一图。另外,它还允许我将多个图形写入同一PDF。我不知道有什么方法可以仅使用matplotlib.pyplot
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
推荐答案
显示图中最简单,最佳的方法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()
要以pdf文件的形式创建输出,您可以d:
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")
如果要将多个图形保存到同一pdf文件,请使用 matplotlib.backends.backend_pdf.PdfPages( output.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
是要在PyQt GUI中使用的,如果要使用它,则需要先创建它。 此问题向您展示了如何执行此操作,但似乎仅显示或保存该图形就有些过分了。
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.
这篇关于为什么没有图片显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!