How to embed matplotlib graph in Django webpage?

前端 未结 4 1885
情歌与酒
情歌与酒 2021-02-04 12:00

So, bear with me as I\'m VERY new to Django, Python, and web-development in general. What I want to do is display a graph that I\'ve made using matplotlib. I had it working to w

4条回答
  •  情深已故
    2021-02-04 12:47

    I searched quite a bit until I found a solution that worked for me when it comes to rendering a matplotlib image on a Django page. Often, simply a lengthy string was printed instead of a visualization being produced. So, what finally worked for me was the following:

    First, the imports:

    import matplotlib.pyplot as plt
    from io import StringIO
    import numpy as np
    

    The dummy function returning a graphic is the following:

    def return_graph():
    
        x = np.arange(0,np.pi*3,.1)
        y = np.sin(x)
    
        fig = plt.figure()
        plt.plot(x,y)
    
        imgdata = StringIO()
        fig.savefig(imgdata, format='svg')
        imgdata.seek(0)
    
        data = imgdata.getvalue()
        return data
    

    This one can be called by some other function using and rendering the image returned by return_graph():

    def home(request):
        context['graph'] = return_graph()
        return render(request, 'x/dashboard.html', context)
    

    And in the dashboard.html file, the graphic is embedded by the following command:

    {{ graph|safe }}
    

提交回复
热议问题