1
将matplotlib barplot插入PDF的最佳方式是什么? barplot应首先呈现给HTML,然后发送到PDF。 PS:我使用熊猫,numpy,matplotlib,jinja2和weasyprint。我这样做的原因是我有一个熊猫数据框,以及我已经添加到PDF中。将matplotlib barplot添加到PDF
以下是目前工作的方式:
这是html文件。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Produced services plot:</h2>
{{ produced_services_plot }}
</body>
</html>
这是示例图:
# Fixing random state for reproducibility
np.random.seed(19680801)
plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
ax.barh(y_pos, performance, xerr=error, align='center',
color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
这是我如何创建的PDF:
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("pdf_report_template.html")
template_vars = {"title": "Test",
"produced_services_plot": plt.savefig("fig.png")
# Some other stuff here that goes to the HTML.
}
html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("report.pdf", stylesheets=["pdf_report_style.css"]))
样式表可以在这里找到:http://www.blueprintcss.org/blueprint/src/typography.css
可能这些库也是需要的:
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
import matplotlib.pyplot as plt
我知道plt.savefig()方法不是应该在那里调用的方法。但是,如上所示,将图像发送到html的最佳方式是什么?
图像没有出现在PDF中。我还得到了以下的警告:警告:没有基础URI的相对URI引用:在行无 –
E:这对我有效! –