将绘图保存到图像文件,而不是使用Matplotlib显示

这篇博客讨论如何在Python的Matplotlib库中避免显示图形界面,而是直接将绘制的图表保存为图像文件。主要内容包括使用savefig函数的不同参数和技巧,以及在不同环境(如Spyder或Jupyter Notebook)中的应用。博主提供了多个示例代码来展示如何在保存图表后关闭图形窗口,以及如何在后续处理中重新打开和编辑图形。
摘要由CSDN通过智能技术生成

我正在编写一个快速脚本来动态生成绘图。 我使用下面的代码(来自Matplotlib文档)作为起点:

from pylab import figure, axes, pie, title, show

# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})

show()  # Actually, don't show, just save to foo.png

我不想将图形显示在GUI上,而是要将图形保存到文件(例如foo.png)中,以便可以在批处理脚本中使用它。 我怎么做?


#1楼

如果您不喜欢“当前”数字的概念,请执行以下操作:

import matplotlib.image as mpimg

img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)

#2楼

正如其他人所说, plt.savefig()fig1.savefig()确实是保存图像的方法。

但是我发现在某些情况下总是显示该图 。 (例如,具有Spyder的。 plt.ion()交互模式= ON)我变通的作法迫使图窗口的关闭在我的巨环plt.close(figure_object)文档 ),所以我不”在循环中没有一百万个开放数字:

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png')   # save the figure to file
plt.close(fig)    # close the figure window

如果需要与您应该能够在以后重新打开图fig.show()没有测试自己)。


#3楼

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
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值