使用reportlab将matplotlib条形图保存为pdf

问题描述 投票:0回答:1

所以我尝试使用下面的代码使用reportlab将matplotlib生成的图保存到pdf文件中

import matplotlib.pyplot as plt
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
from svglib.svglib import svg2rlg
...
objects = [str(col[1]) for col in data3.columns][1:]
y_pos = np.arange(len(objects))
performance = data[5][1:]
fig = plt.figure()
plt.bar(y_pos, performance, align='center', alpha=0.5, color=['blue', 'blue',     'blue', 'yellow','yellow'], edgecolor='blue')
plt.xticks(y_pos, objects)
plt.ylabel('USD $Billions')
plt.title('Revenue')
fig = plt.figure()
imgdata = BytesIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)  # rewind the data
drawing = svg2rlg(imgdata)

renderPDF.draw(drawing, pdf, 10, 40)
pdf.save()

但我收到以下错误:

Traceback (most recent call last):
  File "./main.py", line 94, in <module>
    renderPDF.draw(drawing, pdf, 10, 40)
  File "/usr/lib/python3/dist-packages/reportlab/graphics/renderPDF.py", line 29, in draw
    R.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary)
  File "/usr/lib/python3/dist-packages/reportlab/graphics/renderbase.py", line 172, in renderScaledDrawing
    renderScale = d.renderScale
AttributeError: 'NoneType' object has no attribute 'renderScale'
python matplotlib reportlab
1个回答
0
投票

这是我的做法(基于我发现的帖子评论):

from io import BytesIO
from reportlab.pdfgen.canvas import Canvas
from svglib.svglib import svg2rlg
def one_page_pdf(file_name, fig):
    canvas = Canvas(filename=file_name)
    img_data = BytesIO()
    figs.savefig(img_data, format="svg")
    img_data.seek(0)
    drawing = svg2rlg(img_data)
    renderPDF.draw(drawing, canvas, 10, 100)
    canvas.showPage()
    canvas.save()

您只需为该函数提供 PDF

filepath
matplotlib
图即可。

© www.soinside.com 2019 - 2024. All rights reserved.