What would be the best way to insert a matplotlib barplot into a PDF. The barplot should first be rendered to an HTML and after that sent to PDF. PS: I am using pandas, numpy, matplotlib, jinja2 and weasyprint. The reason I am doing it this way is that I have a Pandas DataFrames as well that I already added to the PDF.
Here's how the things currently work:
This is the html file.
<!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>
This is the example plot:
# 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?')
And this is how I have created the 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"]))
The stylesheet can be found here: http://www.blueprintcss.org/blueprint/src/typography.css
Probably those libraries are needed as well:
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
import matplotlib.pyplot as plt
I know that the plt.savefig() method is not the one that should be called there. But what would be the best way to send the image to the html as shown above?
I suspect that you want to create the image in HTML
<h2>Produced services plot:</h2>
<img src="{{ produced_services_plot }}">
then in python save the image
filename = "myfilename.png"
plt.savefig(filename)
and send the filename to the template
template_vars = {"title": "Test",
"produced_services_plot": filename
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With