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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: