I thought everyone knew about but i was surprised this this little feature of matplotlib is not that known as widely as I assumed.

We all know we can save a plot from matplotlib to pdf but there other little feature hiding in the backends where we can write out a multiple page pdf

Here’s a simple code to write out multiple page pdf using matplotlib.


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

pdf=PdfPages('matplotlibplot.pdf')

fig=plt.figure()
plt.plot(np.random.rand(10));
pdf.savefig(fig)

fig=plt.figure()
plt.hist(np.random.randn(1000));
pdf.savefig(fig)

pdf.close()

So easy. Instantiate pdfpages, Open the pdf file, save figures. Works from version 0.99 of matplotlib.
With little use of plt.text, plt.annotate, can be used to produce quick pdf reports. In fact,I have pandas and matplotlib workflow to pump out full blown management report on continuous improvement initiative.
Here’s a simple full example of creating a simple pdf report using the above feature


textpdf='''1 ProjectA PO01 Python 67184 0 46770.4 20413.6 62580.42 0.01
1 ProjectB RTFund Fortran 487350 0 81730.4 405619.6 111188 0'''

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
def PlotProject(text):
text=text.split(" ")
poNum=text[2]
project=text[1]
taskNo=text[3]
baselineAmt=float(text[4])
invoicedAmt=float(text[6])
revenueAmt=float(text[8])
testNames = ['Baseline', 'Revenue','Invoiced']

pos = np.arange(3)+0.5
fig=plt.figure(figsize=(9,4))
plt.barh(pos,[baselineAmt,revenueAmt,invoicedAmt],color=['blue','green','orange'],alpha=0.5,align='center', height=0.5)
plt.yticks(pos, testNames)
plt.title("Project: "+ str(project)+" Task: "+str(taskNo))
plt.grid()
return fig

def TitleSlide(text='Thank You'):
fig=plt.figure(figsize=(9,4))
plt.text(0.50,0.5,text,fontsize=15)
plt.axis('off')
return fig

textlist=textpdf.split('\n')
pdf=PdfPages('report.pdf')
fig=TitleSlide(text='Project Report')
pdf.savefig(fig)

for tx in textlist:
fig=PlotProject(tx)
pdf.savefig(fig)

fig=TitleSlide()
pdf.savefig(fig)
pdf.close()

Have you used anything like this? With little imagination, the possibilities are endless.

One response to “Pdf With Matplotlib”

  1. Magic! Great demo. Thanks

    Like

Leave a comment

Trending