如何在reportlab画布中绘制matplotlib图形? [英] How to drawImage a matplotlib figure in a reportlab canvas?

查看:37
本文介绍了如何在reportlab画布中绘制matplotlib图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add a figure generated with matplotlib to a reportlab canvas using the method drawImage and without having to save the figure to the hard drive first.

我的问题与以下方面有关:是否有适合 ReportLab 的 matplotlib flowable?,很好地解决了这个问题.但是,我不希望使用 DocTemplates、Stories、Flowables 等.如上所述,我想使用 drawImage 将其放在画布中的某个位置.

My question is related to: Is there a matplotlib flowable for ReportLab?, which was nicely solved. However, I do not wish to use DocTemplates, Stories, Flowables, etc. As said, I would like put it at a certain position in the canvas using drawImage.

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

I have tried to convert the matplotlib figure to a PIL image using the following methods:

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/常见问题解答/howto_faq.html#matplotlib-in-a-web-application-server

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

For example, some code that fails to work is:

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

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

Does somebody now how to solve this issue? Any help would be greatly appreciated.

推荐答案

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

The problem is that drawImage expects either an ImageReader object or a filepath, not a file handle.

以下应能工作:

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()

这篇关于如何在reportlab画布中绘制matplotlib图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆