How to create Bar Chart image with Matplotlib in Django

Hello World, Welcome to Today I am going to discuss how to create a bar chart image with the Matplotlib in Django 3. We will create a bar chart according to data and save a png image and then display this image in the Django template. I have divided this tutorial into the following parts:

  • Matplotlib introduction
  • Install Matplotlib
  • Create a bar chart view method
  • Show bar chart in the template view

Matplotlib Introduction

According to the official website: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

Install Matplotlib

First of all, we will install the Matplotlib package with the following command.

pip install matplotlib

Add this package to your project-level  in the installed apps list.

Create a view method for bar chart

In this step, we will create a method to create a bar chart with the Matplotlib package. Add the following method in file.

from django.shortcuts import render
import random
# MatPlotLib
import matplotlib
from matplotlib import pyplot as plt
import numpy as np

# Pie Chart
def barchart(request):
    objects = ['12/10/2019','12/11/2020','15/10/2020']
    y_pos = np.arange(len(objects))
    qty = [10,20,25], qty, align='center', alpha=0.5)
    plt.xticks(y_pos, objects)
    return render(request,'barchart.html')

In the above code, We are assigning dates and qty list for sales. Every time you refresh you will see the different colors of the bar chart. You can replace the dates and qty with dynamic values. We are showing a bar chart as an image so we will do the following things to show the image.

Add the following code to the file.

from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Create a media directory at the root because we are saving the image in this folder.

Show bar chart in the template view

Till now we have saved the bar chart image in the folder. In this step, we will show the image in the Django template.

Create a barchart.html file in the templates folder and add the following code.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BarChart with Matplotlib</title>
    <h3>Barchart of Sales</h3>
    <img src="./media/barchart.png" />

When you will run the application in the browser, you will see the following screen.

Leave a Reply

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