0

I want to generate a plot and save to memory and then pass it flask as a variable but I am stuck. I have written this code and it seems to work in google colab, when the function is called it generates the plot. However I want now to pass the variable buffer to flask render template but I am totally stuck

import io

def image_plot():
             plt.figure()
             my_ax = sns.violinplot(x=df_tweet["compound"])
             plt.title('this is the twitter sentiment analysis for')
             buffer = io.BytesIO()
             my_ax.figure.savefig(buffer, format="png")
             buffer.seek(0)
             return buffer


return render_template("index.html", buffer=.....)

and the html part should be...

<body>
    <img id="picture" src="{{ buffer }}">
</body>
Emilia Delizia
  • 333
  • 3
  • 14
  • Maybe [this](https://towardsdatascience.com/how-to-easily-show-your-matplotlib-plots-and-pandas-dataframes-dynamically-on-your-website-a9613eff7ae3) article can help you with it. And this [gist](https://gist.github.com/illume/1f19a2cf9f26425b1761b63d9506331f) – charchit Jul 07 '21 at 16:34

1 Answers1

0

I have figured out the following and it seems to work basing it this tutorial

https://buraksenol.medium.com/pass-images-to-html-without-saving-them-as-files-using-python-flask-b055f29908a

import io
import base64



plt.figure()
my_ax = sns.violinplot(x=df_tweet["compound"])
plt.title('this is saved to memory')
buffer = io.BytesIO()
my_ax.figure.savefig(buffer, format="png")
buffer.seek(0)
image_memory = base64.b64encode(buffer.getvalue())

return render_template("index.html", img_data=image_memory.decode('utf-8'))

on the html page


<img id="picture" src="data:image/png;base64,{{ img_data }}">

Emilia Delizia
  • 333
  • 3
  • 14