将 pandas/matplotlib 图像直接写入 XLSX 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30716911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing pandas/matplotlib image directly into XLSX file
提问by sparc_spread
I am generating plots in pandas/matplotlib and wish to write them to an XLSX file. I am not looking to create native Excel charts; I am merely writing the plots as non-interactive images. I am using the XlsxWriter library/engine.
我在 pandas/matplotlib 中生成图并希望将它们写入 XLSX 文件。我不打算创建本机 Excel 图表;我只是将绘图写成非交互式图像。我正在使用XlsxWriter 库/引擎。
The closest solution I have found is the answer to this SO question, which suggests using the XlsxWriter.write_image()method. However, this method appears to take a filename as its input. I am trying to programmatically pass the direct output from a pandas/matplotlib plot()call, e.g. something like this:
我找到的最接近的解决方案是这个 SO question 的答案,它建议使用XlsxWriter.write_image()方法。但是,此方法似乎将文件名作为其输入。我正在尝试以编程方式传递来自 Pandas/matplotlibplot()调用的直接输出,例如这样的东西:
h = results.resid.hist()
worksheet.insert_image(row, 0, h) # doesn't work
or this:
或这个:
s = df.plot(kind="scatter", x="some_x_variable", y="resid")
worksheet.insert_image(row, 0, s) # doesn't work
Is there any way to accomplish this, short of the workaround of writing the image to a disk file first?
除了先将图像写入磁盘文件的解决方法之外,有什么方法可以做到这一点?
Update
更新
Answer below got me on the right track and am accepting. I needed to make a few changes, mainly (I think) because I am using Python 3 and perhaps some API changes. Here is the solution:
下面的答案让我走上了正确的道路,我接受了。我需要进行一些更改,主要是(我认为)因为我使用的是 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}
)
The ""in the insert_image()code is to trick Excel, which is still expecting a filename/URL/etc.
将""在insert_image()代码欺骗Excel中,这仍然是期待一个文件名/ URL /等。
回答by Primer
You can save the image to memory as a file object (not to disk) and then use that when inserting to Excel file:
您可以将图像作为文件对象(而不是磁盘)保存到内存中,然后在插入 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)

