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

我正在pandas / matplotlib中生成图表,并希望将它们写入XLSX文件。 我不想创build本机Excel图表; 我只是把这些情节写成非交互式的图像。 我正在使用XlsxWriter库/引擎 。

我find的最接近的解决scheme是这个SO问题的答案 ,build议使用XlsxWriter.write_image()方法。 但是,此方法似乎将文件名作为其input。 我试图以编程方式传递来自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的变化。 这是解决scheme:

 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,它仍然期待着一个文件名/ URL /等。

您可以将图像作为文件对象(不是磁盘)保存到内存中,然后在插入到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)