super9
super9

Reputation: 30131

How to output a graph from Matplotlib in Django templates?

Given this example taken from here:

def simple(request):
    import random

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

How can I write the view in such a way that uses a template and variable like: return render_to_response ('template.html',{'graph': <graph generated by matplotlib> }

Upvotes: 1

Views: 3253

Answers (1)

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5733

When I had a similar situation, I used two views. One used matplotilb to generate a PNG, while the other used used django templates to create an HTML page that presented the PNG (and some other data). The param sent to the template was just the PNG filename. The other view is then attached to he appropriate .png URLs.

One problem is if you want to calculate some parameters which are used both for generating the HTML and PNG. I encoded such information in the filename. This is painful, and slightly hacky, but it's s also good for the user if all the info is in the filename when she saves it.

Upvotes: 2

Related Questions