gpt4 book ai didi

python - 如何在 reportlab Canvas 中绘制 matplotlib 图?

转载 作者:太空狗 更新时间:2023-10-29 17:47:45 25 4
gpt4 key购买 nike

我想使用 drawImage 方法将使用 matplotlib 生成的图形添加到 reportlab Canvas ,而不必先将图形保存到硬盘驱动器。

我的问题是: Is there a matplotlib flowable for ReportLab? ,这很好地解决了。但是,我不想使用 DocTemplates、Stories、Flowables 等。如前所述,我想使用 drawImage 将它放在 Canvas 中的某个位置。

我尝试使用以下方法将 matplotlib 图转换为 PIL 图像:

1) http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image

2) http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server

例如,一些无法工作的代码是:

import Image
import matplotlib.pyplot as plt
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm

fig = plt.figure(figsize=(4, 3))
plt.plot([1,2,3,4])
plt.ylabel('some numbers')

imgdata = cStringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data
im = Image.open(imgdata)

c = canvas.Canvas('test.pdf')
#c.drawImage(imgdata, cm, cm, inch, inch)
c.drawImage(im, cm, cm, inch, inch)
c.save()

尝试绘制 imgdata 导致错误:

AttributeError: 'cStringIO.StringO' object has no attribute 'rfind'

在绘制 im 时给出:

AttributeError: rfind

现在有人如何解决这个问题?任何帮助将不胜感激。

最佳答案

问题是 drawImage 需要 ImageReader 对象或文件路径,而不是文件句柄。

以下应该有效:

import Image
import matplotlib.pyplot as plt
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm

from reportlab.lib.utils import ImageReader

fig = plt.figure(figsize=(4, 3))
plt.plot([1,2,3,4])
plt.ylabel('some numbers')

imgdata = cStringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data

Image = ImageReader(imgdata)

c = canvas.Canvas('test.pdf')
c.drawImage(Image, cm, cm, inch, inch)
c.save()

关于python - 如何在 reportlab Canvas 中绘制 matplotlib 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com