How to embed matplotlib graph in Django webpage?

前端 未结 4 1880
情歌与酒
情歌与酒 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:46

    I think you should uncoment this line:

    #canvas.print_png(response)
    

    You can easily return plot using django HttpResponse instead using some extra libs. In the matplotlib there is a FigureCanvasAgg which gives you access to canvas where plot is rendered. Finaly you can simple return it as HttpResonse. Here you have very basic example.

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from django.http import HttpResponse
    
    def plot(request):
        # Data for plotting
        t = np.arange(0.0, 2.0, 0.01)
        s = 1 + np.sin(2 * np.pi * t)
    
        fig, ax = plt.subplots()
        ax.plot(t, s)
    
        ax.set(xlabel='time (s)', ylabel='voltage (mV)',
               title='About as simple as it gets, folks')
        ax.grid()
    
        response = HttpResponse(content_type = 'image/png')
        canvas = FigureCanvasAgg(fig)
        canvas.print_png(response)
        return response
    

提交回复
热议问题