0

I am using a package called matplotlib to create some graphs, based on user input. Creating these graphs can be done like so

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
some_plot = plt.figure()

Moreover it is possible to then save these graphs as images,

some_plot.savefig(path, format='png')

The problem is that I don't really want to save every single user generated graph, but rather I would like to just display them. I have tried to look up some solutions for related problems. One such solution was to use IoBytes. Following along these answer I get something like

from io import BytesIO
some_plot_io = BytesIO()

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
some_plot = plt.figure()
some_plot.savefig(some_plot_io, format='png')

Is it possible to somehow pass on the BytesIO object to the template and serve the image or does this method not work? Would there be some other method to do this?

Omar Einea
  • 2,410
  • 6
  • 21
  • 34
DisneylandSC
  • 766
  • 4
  • 17
  • I can use plt.show() locally. I'm not sure how I would use this method to dynamically embed graphs in a website. – DisneylandSC Jan 16 '18 at 18:33
  • 1
    Possibly useful - https://stackoverflow.com/questions/22739592/how-to-embed-an-interactive-matplotlib-plot-in-a-webpage – DavidG Jan 16 '18 at 18:50
  • 1
    Use base64-image https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html – swatchai Jan 16 '18 at 19:19

1 Answers1

4

After searching for quite a while and fiddling with my code I managed to find an answer. I have included a complete example of my working code below as most of the answers I could find online were very short and cryptic.

Imports

from io import BytesIO
import base64
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

views

plt.plot(range(10))
buf = BytesIO()
plt.savefig(buf, format='png')
image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
buf.close()

You can then pass on image_base64 to your template and display it using

template

<img src="data:image/png;base64, {{ image_base64 }}" alt="somealt" />

Thanks to comments by DavidG and swatchai for pointing me in the right direction to search for.

DisneylandSC
  • 766
  • 4
  • 17