这将在GUI中显示图形:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

但我如何将图形保存到文件(例如foo.png)中?


当前回答

由于服务器上没有gui,因此使用“agg”。使用gui和VSC在ubuntu 21.10上进行调试。在调试中,尝试显示绘图,然后保存到web UI的文件。

发现显示前需要保存,否则保存的绘图为空。我想这场演出会因为某种原因使剧情明朗化。执行以下操作:

plt.savefig(imagePath) 
plt.show()
plt.close(fig)

而不是:

plt.show()
plt.savefig(imagePath) 
plt.close(fig)

其他回答

使用plot()和其他函数创建所需的内容后,可以使用如下子句在绘制到屏幕或文件之间进行选择:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))       # size in inches
# use plot(), etc. to create your plot.

# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)  

if save_file:
    plt.savefig(save_file)
    plt.close(fig)
else:
    plt.show()
import matplotlib.pyplot as plt
plt.savefig("image.png")

在Jupyter Notebook中,您必须在一个单元格中删除plt.show()并添加plt.savefig()以及其他plt代码。图像仍将显示在笔记本中。

我使用了以下方法:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show() 
plt.close()

我发现保存图片后使用plt.show非常重要,否则它将无法工作。图片以png格式导出

使用matplotlib.pyplot时,必须先保存绘图,然后使用以下两行关闭绘图:

fig.savefig('plot.png') # save the plot, place the path you want to save the figure in quotation
plt.close(fig) # close the figure window
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()