将 pandas/matplotlib 图像直接写入 XLSX 文件

Writing pandas/matplotlib image directly into XLSX file

我正在 pandas/matplotlib 中生成图并希望将它们写入 XLSX 文件。我不想创建原生 Excel 图表;我只是将情节写成非交互式图像。我正在使用 XlsxWriter library/engine.

我找到的最接近的解决方案是 the answer to this SO question, which suggests using the XlsxWriter.write_image() 方法。但是,此方法似乎将文件名作为其输入。我正在尝试以编程方式传递 pandas/matplotlib plot() 调用的直接输出,例如像这样:

h = results.resid.hist()
worksheet.insert_image(row, 0, h) # doesn't work

或者这个:

s = df.plot(kind="scatter", x="some_x_variable", y="resid")
worksheet.insert_image(row, 0, s) # doesn't work

除了先将图像写入磁盘文件之外,还有什么方法可以完成此操作吗?

更新

下面的回答让我走上了正确的轨道,我接受了。我需要进行一些更改,主要是(我认为)因为我正在使用 Python 3,也许还有一些 API 更改。这是解决方案:

from io import BytesIO
import matplotlib.pyplot as plt

imgdata = BytesIO()
fig, ax = plt.subplots()
results.resid.hist(ax=ax)
fig.savefig(imgdata, format="png")
imgdata.seek(0)

worksheet.insert_image(
    row, 0, "",
    {'image_data': imgdata}
)

insert_image()代码中的""是为了欺骗Excel,仍然期待filename/URL/etc。

您可以将图像作为文件对象保存到内存(而不是磁盘),然后在插入到 Excel 文件时使用它:

import matplotlib.pyplot as plt
from cStringIO import StringIO
imgdata = StringIO()

fig, ax = plt.subplots()

# Make your plot here referencing ax created before
results.resid.hist(ax=ax)

fig.savefig(imgdata)

worksheet.insert_image(row, 0, imgdata)