我正在尝试将matplotlib图形放到reportlab画布上。我可以使用此问题的代码做一个简单的图表:How to drawImage a matplotlib figure in a reportlab canvas? 但是当我尝试使用子图或使用多个图时,它将无法正常工作。这样做会导致相同的图像被绘制两次,即使我添加了imgdata.close()或删除图形:
from matplotlib.figure import Figure
import cStringIO
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
can = canvas.Canvas()
self.f = Figure()
plot(x,y)
xlabel(xlbl)
ylabel(ylbl)
imgdata=cStringIO.StringIO()
savefig(imgdata,format='png')
imgdata.seek(0)
Image = ImageReader(imgdata)
can.drawImage(Image,100,250, width=400,height=350)
self.g = Figure()
plot(x,y)
xlabel(xlbl)
ylabel(ylbl)
secondimgdata = cStringIO.StringIO()
savefig(secondimgdata,format='png')
secondimgdata.seek(0)
Image2 = ImageReader(secondimgdata)
can.drawImage(Image2,100,150, width=400,height=350)
尝试使用子图时,它只会生成一个空白图,我不知道该去哪里:
self.f = Figure()
self.a = self.f.add_subplot(111)
self.a.plot(x,y)
self.a2 =self.a.twinx()
self.a2.plot(x,y2,'r')
self.a2.set_ylabel(ylbl2)
self.a.set_xlabel(xlbl)
self.a.set_ylabel(ylbl)
非常感谢对此问题的任何解决方案或建议。
答案 0 :(得分:1)
关键是您必须在添加完图像后使用plt.close()
。这是一个快速的例子,适用于我使用seaborn和barplot。假设我有一个数据框,其中包含我想要绘制的几个数字的不同数据。
import matplotlib.pyplot as plt
import seaborn as sns
import cStringIO
from reportlab.platypus import Image
my_df = <some dataframe>
cols_to_plot = <[specific columns to plot]>
plots = []
def create_barplot(col):
sns_plot = sns.barplot(x='col1', y=col, hue='col2', data=my_df)
imgdata = cStringIO.StringIO()
sns_plot.figure.savefig(imgdata, format='png')
imgdata.seek(0)
plots.append(Image(imgdata))
plt.close() # This is the key!!!
for col in cols_to_plot:
create_barplot(col)
for barplot in plots:
story.append(barplot)
答案 1 :(得分:0)
这不是一个理想的解决方案,因为它必须将文件保存为图像而不是使用StringIO,但它可以工作。
import Image as image
from matplotlib.pyplot import figure
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
can = canvas.Canvas()
self.f = figure()
self.a = self.f.add_subplot(2,1,1)
self.a.plot(x,y)
self.a2 =self.a.twinx()
self.a2.plot(x,y2,'r')
self.a2.set_ylabel(ylbl2,color='r')
self.a.set_xlabel(xlbl)
self.a.set_ylabel(ylbl,color='b')
self.f.savefig('plot.png',format='png')
image.open('plot.png').save('plot.png','PNG')
can.drawImage('plot.png',100,250, width=400,height=350)