Hassan Eid
Hassan Eid

Reputation: 19

Embedding pyplot graph into html on django framework

I am new to python and Django but have a bit of code that works in displaying my graph but as a separate popup window. I am calling this line of code from my HTML page:

{% block content %}
<h1>Title: {{ report.title }}</h1>

<div>
{{ report.show_graph }}  //THIS PORTION IS CALLING THE GRAPH WHICH IS RESULTING IN A POPUP OF IT IN A SEPARATE WINDOW
</div>

<p><strong>Summary:</strong> {{ report.summary }}</p>
<p>Date Created: {{ report.date_created }}</p>

{% endblock %}

It triggers a request and calls the graph but as a separate standalone window. The code I am calling is:

class Report(models.Model):
"""Model representing a report"""
title = models.CharField(max_length=200)
date_created = models.DateField("Date", default=datetime.date.today)
summary = models.TextField(max_length=1000, help_text='Enter a brief summary of the report.')

def __str__(self):
    """String for representing the Model Object"""
    return self.title

def get_absolute_url(self):
    """Returns the url to access a digital record of this Report"""
    return reverse('report-detail', args=[str(self.id)])

def show_graph(self):
    style.use('ggplot')
    pfizer_data = quandl.get("NSE/PFIZER", authtoken="....")
    pfizer_data['Close'].plot()
    return plt.show()

I am trying to have the graph be returned as HTML so it is embedded in the div instead of a separate window. Thanks.

Upvotes: 1

Views: 1584

Answers (2)

schrodingerscatcuriosity
schrodingerscatcuriosity

Reputation: 1860

Well I tried with the library mpld3 that you mention. It uses jinja2, so you have to install it, but there's no need to add it in settings.py BACKEND. Here's an example of what I accomplish:

import matplotlib
import matplotlib.pyplot as plt, mpld3
import numpy as np

from django.shortcuts import render


def matplotlib_graph(request):

    # HERE I USE AN EXMAMPLE FROM MATPLOTLIB SITE

    # 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()
    g = mpld3.fig_to_html(fig)
    fig.savefig("test.png")

    context = {'g': g}

    return render(request, 'myhtml.html', context)

And in the html template:

<h1>My graph</h1>

{% autoescape off %}
<div>{{ g }}</div>
{% endautoescape %}

The result:

enter image description here

Upvotes: 3

Hassan Eid
Hassan Eid

Reputation: 19

Took a different route and used mpld3 library. Reference to alternate solution: Django Rendering Matplotlib chart in HTML using mpld3

Upvotes: 0

Related Questions