Python Forum

Full Version: Show a plot from matplotlib in a webpage
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like to create a dashboard webpage with plots. I'm using Visual Studio Code IDE. I went through the tutorials to generate a webpage with variable inputs (the tutorial uses text input). And I went thorugh the Matplotlib example to create a plot. But when I go to my webpage it creates the plot in a new window. I'm not sure how to get it into my webpage.

In Visual Studio Code file:
from django.http import HttpResponse
from django.shortcuts import render
from datetime import datetime

import matplotlib.pyplot as plt
import numpy as np
# matplotlib

def dashboard(request):

    x = np.arange(0.0, 50.0, 2.0)
    y = x**1.3 + np.random.rand(*x.shape) * 30.0
    s = np.random.rand(*x.shape) * 800 + 500

    plt.scatter(x, y, s, c="g", alpha=0.5, marker=r'$\clubsuit$', label='luck')
    plt.legend(loc='upper left')
    return render(
            'plotDisp': plt
in the webpage template I'm not sure what format to show the plot. For instance: <img src={{ plotDisp }} /> or some sort of frame object?

My web address brings up the plot as a popup window (from And when I close that window the webpage is shown but can't find the plot reference. So obviously 'plotDisp': plt is not correct .
To get this worked, you need do either:
1) save the figure as a file and render the template with appropriate file path, i.e. insert <img src='path/to/plot/saved.png'> somewhere in your template; 'path/to/plot/saved.png' could be passed to django template using variable, e.g. <img src="{{path_to_plot}}">.
2) encode entire image as base64 and pass this to your template. You would probably need to use BytesIO, like here; Note: this is suitable for relatively small images

IMHO, it would be better to use bokeh or render the plot using
a javascript library (nvd3, d3.js etc). In these cases, all computations are performed on the server side. Furhter, you just need to send the data, e.g. as json, and render it as a plot by means of some js-lib.
Thanks for the help scidam. I never did get the <img... option to work but I did implement bokeh. The key here was to make sure the bokeh version in the html file was the most current version.