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:
這對我有效! –