问题描述
我在pandas / matplotlib中生成图,希望将它们写入XLSX文件。我不打算创建本机Excel图表;我只是将图形写成非交互式图像。我正在使用。我找到的最接近的解决方案是,其中建议使用方法。但是,该方法似乎以文件名作为其输入。我试图以编程方式传递来自pandas / matplotlib plot()
调用的直接输出,例如如下所示:
h = results.resid.hist()
worksheet.insert_image(row,0,h )#不工作
或这个:
s = df.plot(kind =scatter,x =some_x_variable,y =resid)
worksheet.insert_image(row,0,s) #不工作
有没有办法完成这个,没有写出图像的解决方法到一个磁盘文件?
更新
下面的答案让我在正确的轨道上接受。我需要做一些修改,主要是(我认为),因为我使用的是Python 3和一些API的更改。这是解决方案:
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 / etc。
您可以将图像作为文件对象(而不是磁盘)保存到内存中,然后在插入Excel文件时使用该图像:
import matplotlib.pyplot as plt
from cStringIO import StringIO
imgdata = StringIO()
fig,ax = plt.subplots()
#使你的情节参考在
之前创建的ax results.resid.hist(ax = ax)
fig.savefig(imgdata)
worksheet.insert_image (row,0,imgdata)
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.
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:
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:
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.
You can save the image to memory as a file object (not to disk) and then use that when inserting to Excel file:
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)
这篇关于将pandas / matplotlib图像直接写入XLSX文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!