title: Matplotlib graphic image to base64
body: <p><strong>Problem :</strong> Need to transform a graphic image of matplotlib to a base64 image</p>
  
  <p><strong>Current Solution :</strong> Save the matplot image in a cache folder and read it with read() method and then convert to base64</p>
  
  <p><strong>New Problem : Annoyance :</strong> Need a workaround so I dont need to save the graphic as image in any folder. I want to just use the image in the memory. Doing unnecessary I/O is a bad practice.</p>
  
  <pre><code>def save_single_graphic_data(data, y_label="Loss", x_label="Epochs", save_as="data.png"):
      total_epochs = len(data)
      plt.figure()
      plt.clf()
  
      plt.plot(total_epochs, data)
  
      ax = plt.gca()
      ax.ticklabel_format(useOffset=False)
  
      plt.ylabel(y_label)
      plt.xlabel(x_label)
  
      if save_as is not None:
          plt.savefig(save_as)
  
      plt.savefig("cache/cached1.png")
  
      cached_img = open("cache/cached1.png")
  
      cached_img_b64 = base64.b64encode(cached_img.read())
  
      os.remove("cache/cached1.png")
  
      return cached_img_b64
  </code></pre>