【问题标题】:Writing pandas/matplotlib image directly into XLSX file将 pandas/matplotlib 图像直接写入 XLSX 文件
【发布时间】:2015-08-23 09:04:14
【问题描述】:

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

我找到的最接近的解决方案是the answer to this SO question,它建议使用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,它仍然需要文件名/U​​RL/等。

【问题讨论】:

  • 引用:insert_image() 代码中的“”是为了欺骗API,它仍然需要一个文件名/U​​RL/等。 严格来说,是Excel需要一个文件名,为了保持一致性,最好提供一个。
  • 另外,出于好奇,你为什么在这种情况下使用 matplotlib 而不是直接将图表添加到工作表中?
  • 谢谢,我会解决的。关于第二条评论,原因是我没有导出将构建图表的数据,只是一些不同的数据和图表本身:基本上是回归结果摘要和大量诊断图,如残基的正常直方图、QQ、散点图与. 残留物等。这都是为了诊断目的,而不是最终的业务报告。

标签: python excel pandas matplotlib xlsxwriter


【解决方案1】:

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

【讨论】:

  • StringIO 从 Python 3 中消失了。关于如何在 Python 3 中使其工作的任何建议?
  • 在 python 3 中,StringIOBytesIO 位于内置的 io 模块中。请通过示例查看更新的 OP 问题。
猜你喜欢
  • 2012-08-26
  • 2016-12-30
  • 2017-12-22
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多