如何使matplotlib在与plt.cla(),plt.clf()和plt.close()结合使用时正确保存图形/绘图?

aor9mmx1  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

我有一个plotting函数脚本,可以绘制一个线性图,并将图保存在字符串缓冲区中。为了测试图,我在循环中调用plotting方法。我使用“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()本质上是同步的,正如公认的答案here所提到的那样。
plt.cla()/plt.clf()是否以某种方式清除/覆盖已经保存在缓冲区中的内容?
我试图清除接受的答案here和这里后面的图,但仍然无法正确保存我的图。

ac1kyiln

ac1kyiln1#

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()

字符串

相关问题