簡體   English   中英

將pandas / matplotlib映像直接寫入XLSX文件

[英]Writing pandas/matplotlib image directly into XLSX file

我在pandas / matplotlib中生成圖並希望將它們寫入XLSX文件。 我不打算創建原生Excel圖表; 我只是把這些情節寫成非交互式圖像。 我正在使用XlsxWriter庫/引擎

我找到的最接近的解決方案是這個SO問題的答案 ,它建議使用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,它仍然需要文件名/ 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM