1

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.

Mahesh G
  • 1,226
  • 4
  • 30
  • 57
Hassan Eid
  • 19
  • 3
  • I don't think matplotlib writes HTML. You need to write the HTML yourself. – Stop harming Monica Sep 22 '18 at 18:52
  • How would I go about doing this? I found a library called mpld3 and it allows me to convert it to html. When I return the code of html it converts to, it does not properly display which I am starting to get lost in. – Hassan Eid Sep 22 '18 at 19:26
  • What do you mean by _"not properly display"_? – schrodingerscatcuriosity Sep 22 '18 at 19:29
  • I ended up solving my own question. With mpld3.fig_to_html, the call was returning the html text instead of the graph. I found another thread linked here: https://stackoverflow.com/questions/44924890/django-rendering-matplotlib-chart-in-html-using-mpld3 – Hassan Eid Sep 22 '18 at 20:02
  • @HassanEid I though you wanted a static image. If you want help with mpld3 be specific describing your issue in the question. – Stop harming Monica Sep 22 '18 at 20:12

2 Answers2

2

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

schrodingerscatcuriosity
  • 1,780
  • 1
  • 16
  • 31
0

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

Hassan Eid
  • 19
  • 3