Create graph using Matplotlib in Django
How to show matplotlib graph into Django template
In this example, the project has been already created named as “myproject” and django application was named as “myapplication”.
Install Matplotlib
I am going to use “pip3” command since pip binary is being linked to python2 in my environment.
pip3 install matplotlib
Configure Django
You need to include Matplotlib application to your Django’s settings.py. This will allow you to call Matplotlib’s methods.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'matplotlib',
'myapplication',
]
Setup models.py and urls.py
Setup your application’s models.py and urls.py. This will be use to draw Matplotlib’s graph.
from django.db import models
class ReplicationStatus(models.Model):
statusid = models.IntegerField(primary_key=True)
server = models.CharField(max_length=20)
mirrorpercent = models.IntegerField(null=True, blank=True)
status_updatedate = models.CharField(max_length=30, null=True, blank=True)
addeddate = models.DateTimeField()
updatedate = models.DateTimeField()
class Meta:
verbose_name_plural = 'Replication_Status'
def __str__(self):
return self.server
from django.urls import path, re_path, include
from . import views
urlpatterns = [
path('', views.index, name='My Application'),
path('status_details/<str:servername>',
]
Create Graph
In my application, I have an argument that is being send to my views.py which is “servername”. Basically, the idea is to fetch data from database and draw a graph specific for that server.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.db.models import Max, Min, Subquery, Count
from django.contrib.auth.decorators import login_required
from myapplication.models import ReplicationStatus
import matplotlib.pyplot as plt
from io import BytesIO
import numpy as np
import base64
import matplotlib.dates as mdates
def statusdetails(request, servername):
x_data = ReplicationStatus.objects.all().filter(server=str(servername)).values_list('status_updatedate', flat=True).order_by('-statusid')[:10][::-1]
x_data = list(x_data)
y_data = ReplicationStatus.objects.all().filter(server=str(servername)).values_list('mirrorpercent', flat=True).order_by('-statusid')[:10][::-1]
y_data = list(y_data)
ycount = len(y_data)
ax = plt.gca()
ax.set_ylim([0,100])
if ycount >= 10:
ax.set_xlim([0,10])
else:
ax.set_xlim([0,ycount])
ax.set_ylabel('Mirroring Percentage (%)')
ax.grid(True)
locator = mdates.DayLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_data, y_data, 'o-')
degrees = 70
plt.xticks(rotation=degrees)
plt.tight_layout()
buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
buffer.close()
plt.clf()
drawgraph = base64.b64encode(image_png)
drawgraph = drawgraph.decode('utf-8')
context = {'drawgraph': drawgraph}
return render(request, 'myapplication/status_details/status_details.html', context)
Include Matplotlib graph to Django template
<div class="matplotlibgraph">
{% autoescape off %}
<img class="graphimg" src="data:image/png;base64,{{ drawgraph|safe }}" style="height: 50%;width: 50%">
{% endautoescape %}
</div>
