• HOME
  • ABOUT US
  • JOBS
    • Find Jobs
    • Job Dashboard
    • Post a Job
  • SERVICES
  • BLOG
    • VIDEOS
    • DOWNLOADS
  • SEARCH
  • SHOP
  • Log In
Toggle navigation Hey! Homeworx
  • HOME
  • ABOUT US
  • JOBS
    • Find Jobs
    • Job Dashboard
    • Post a Job
  • SERVICES
  • BLOG
    • VIDEOS
    • DOWNLOADS
  • SEARCH
  • SHOP
  • Log In

Create graph using Matplotlib in Django

December 28, 2020December 28, 2020 Hey! Admin 0
Posted in Home School, Learning, Linux, School, Technology

Create graph using Matplotlib in Django

December 28, 2020December 28, 2020 Hey! Admin 0

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>

Articles By Hey! Admin

Author Archives Author Website
Posted in Home School, Learning, Linux, School, Technology

Post navigation

How To Set Up Django with Nginx in CentOS and RedHat 7
Top 3 affordable store to purchase Desktop PC parts and laptop

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Appreciation Gift

Thank you for sending your gift. It would help me a lot to maintain and update this site.

Follow us ProKids shop on instagram
Follow us ProKids shop on instagram
Bentoshibox like and subscribe to youtube channel
Hey! HomeWorx official logo

Developed by Code Themes .