提问人:ngawanglhamu 提问时间:10/25/2023 最后编辑:Tranbingawanglhamu 更新时间:10/26/2023 访问量:78
当与 plt.cla() 、plt.clf() 和 plt.close() 结合使用时,如何使 matplotlib 正确保存图形/绘图?
How to make matplotlib save a figure/plot correctly when used in conjuction with plt.cla() , plt.clf() and plt.close()?
问:
我有一个绘图函数脚本,用于绘制折线图并将绘图保存在字符串缓冲区中。为了测试绘图,我在循环中调用绘图方法。我正在使用“Agg”后端,因为我只是保存绘图而不是在窗口中显示它。我的脚本和对方法的调用如下所示:
def plot_linechart(year, month, data, annotate=False):
....plotting data formatting ....
linechart_fig = plt.figure(figsize=(15,6), layout='tight')
ax = linechart_fig.subplots()
ax.plot(x_axis_data, y_axis_data)
... plt.fill_between()... // to color weekends/holidays
if annotate:
...annotate some more things in plot
buffer = io.StringIO()
plt.savefig(buffer, format='svg', bbox_inches = 'tight', pad_inches = 0.1)
plt.cla()
plt.clf()
plt.close(linechart_fig)
return buffer
for month in range(1, 13, 1):
chart_without_annotation = plot_linechart(2013, month , data, False)
chart_with_annnotation = plot_linechart(2013, month , data, True)
...send these plots to somewhere else in my application that displays them in a pdf viewer...
我调用 plt.cla()、plt.clf() 和 plt.close() 来清除内存,也因为如果没有它们,绘图有时会混合并生成不稳定的绘图。
但是由于我添加了plt.cla()。plt.clf() 方法,我不再将两个图混淆。但是对于我的第一个情节,有时我会得到一个空的情节。
难道是因为 plt.savefig 有时在我清除数字之前无法足够快地保存绘图吗?这不太可能,因为 savefig() 本质上是同步的,正如这里接受的答案中提到的。
plt.cla()/plt.clf() 是否以某种方式清除/覆盖已保存在我的缓冲区中的内容?
答:
0赞
Tranbi
10/26/2023
#1
buffer
将仅返回您保存的地块的内存地址。如果你想把你的svg作为字符串,你可以使用getvalue
:
def plot_linechart(year, month, data, annotate=False):
....plotting data formatting ....
linechart_fig = plt.figure(figsize=(15,6), layout='tight')
ax = linechart_fig.subplots()
ax.plot(x_axis_data, y_axis_data)
... plt.fill_between()... // to color weekends/holidays
if annotate:
...annotate some more things in plot
buffer = io.StringIO()
plt.savefig(buffer, format='svg', bbox_inches = 'tight', pad_inches = 0.1)
plt.cla()
plt.clf()
plt.close(linechart_fig)
return buffer.getvalue()
评论
0赞
ngawanglhamu
10/26/2023
感谢您的回复。在我进行方法调用后,我确实使用 returned_buffer.getvalue() 获取了该值,使用 bs4 提取 <svg></svg> 标签中的内容并将它们发送到 pdf 生成器。
0赞
Tranbi
10/27/2023
你是说问题仍然存在?如果是这样,请在您的问题中添加一个最小的可重复示例。
0赞
ngawanglhamu
10/27/2023
我无法在@符号后附加Tranbi的用户名来回复他的评论。但我似乎通过在 plt.savefig() 语句之后使用 plt.show() 和 plt.close(linechart_fig) 解决了这个问题。我的印象是 plt.show() 不会在这里做任何事情,因为我只是保存了绘图,而不是实际在窗口中显示它。
0赞
moken
10/28/2023
不需要在这里的评论中包含@Tranbi,他会自动收到通知,以对他的答案发表评论。虽然不知道为什么你不能在@符号后面写他的名字。
评论