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
   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

   # Add the legend, title, and x,y labels.

   # 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
   b64png = base64.b64encode(

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

   # Clean up

   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: Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: