xyzio

Generating Charts with Python and matplotlib as Base64 images for embedding in HTML webpages

leave a comment »

This is code used to create the charts for my ‘Compare Expense Ratios‘ microsite. It uses matplotlib to generate a chart which is converted to a Base64 to be embedded directly into a webpage. This way there is no need to save an intermediate image.

#Inputs are a dictionary of lists that contains points to plot (points), the title, and the x and y-axis labels.
def mathPlotLib(points, title, xlabel, ylabel):
   import matplotlib
   matplotlib.use('Agg')
   from matplotlib import pyplot
   import base64
   import cStringIO
   import natsort

   #The two funds are the keys to the dicitonary
   fundOrder = []
   for fund in natsort.natsorted(points.keys()):
      #Plot the points and keep track of the order they are added for the legend
      pyplot.plot(points[fund])
      fundOrder.append(fund)

   # Add the legend, title, and x,y labels.
   pyplot.legend(fundOrder)
   pyplot.title(title)
   pyplot.xlabel(xlabel)
   pyplot.ylabel(ylabel)

   # Convert the image as png as a byte-string object
   my_stringIObytes = cStringIO.StringIO()
   pyplot.savefig(my_stringIObytes, format='png')

   # Seek to the beginning of the file and encode it as Base64
   my_stringIObytes.seek(0)
   b64png = base64.b64encode(my_stringIObytes.read())

   # Add the html wrapper to embed it as base64
   html = '<img src="image/png;base64,' + b64png + '" />'

   # Clean up
   my_stringIObytes.close()
   pyplot.clf()
   pyplot.close()

   return html

 

Written by M Kapoor

December 24, 2019 at 8:04 pm

Posted in Programming, python

Tagged with , ,

Leave a comment