How to Embed Matplotlib Graph in Django Webpage

How to pass matplotlib graph in django template?

Repeat - this question was answered here

Basically, you'll need to save your image as a file (e.g. png)

buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
buffer.close()

graphic = base64.b64encode(image_png)
graphic = graphic.decode('utf-8')

return render(request, 'graphic.html',{'graphic':graphic})

and then use that image in your template:

<img src="data:image/png;base64,{{ graphic|safe }}">

How to use Matplotlib in Django?

You need to remove the num parameter from the figure constructor and close the figure when you're done with it.

import matplotlib.pyplot

def test_matplotlib(request):
f = figure(figsize=(6,6))
....
matplotlib.pyplot.close(f)

By removing the num parameter, you'll avoid using the same figure at the same time. This could happen if 2 browsers request the image at the same time. If this is not an issue, another possible solution is to use the clear method, i.e. f.clear().

Matplotlib image not displaying in Django template

I discarded the idea of using matplotlib and went to use Highcharts https://www.highcharts.com/ instead to plot my graph and display it on the webpage.

The data displayed was done by using Django's ORM and Query API.

Trying to display image in web page generated by django view

First of all, your views.py is returning the image in case of POST. The following part will tell the browser that the "page" you return is actually an image and asks the browser to show the image. That's why the browser only shows the image.

            response = HttpResponse(content_type='image/jpg')
canvas = FigureCanvasAgg(fig)
canvas.print_jpg(response)
return response

So, in both cases you should return the template rendered. return render(request, 'gtdefault.html', context)

I understood you want to show the image in the web page (gtdefault.html)? It would mean something like this.

{% if submitted %}
<img src="you need source here" />
{% else %}

Now, the tricky part is getting the source url into the context. You can either upload the generated image to django meda files or some external storage (like AWS S3) for a while and use the url you get from there.

Or you can follow this to deliver the image inside the page: How to display picture from memory in Django?

In the first method you can use browser caching if the image is something that will be looked again later. With the latter case you can ignore the storage but it is "fiddlier" to implement.



Related Topics



Leave a reply



Submit