How to create piechart with matplotlib in django 3

Hello World, Welcome to Today I am going to discuss how to create a piechart with the Matplotlib in Django 3. We will create a piechart 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 piechart view method
  • Show piechart 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 piechart

In this step, we will create a method to create a piechart with the matplotlib package. Add the following method in file.

# MatPlotLib
import matplotlib
from matplotlib import pyplot as plt
import numpy as np

# Pie Chart
def piechart(request):
    # Pie chart, where the slices will be ordered and plotted counter-clockwise:
    labels = 'Sale', 'Purchase'
    sizes = [random.randint(10,30), random.randint(30,50)]
    explode = (0.1, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
    return render(request,'piechart.html')

In the above code, We are passing random numbers for sale and purchase value. Every time you refresh you will see the different piechart. You can replace the random number with dynamic values. We are showing a piechart as an image so we will do the following things to show the image.

  • Add the following code to the file.
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 as root because we are saving the image in this folder.

Show piechart in the template view

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

  • Create a piechart.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>PieChart with Matplotlib</title>
    <h3>Sale Purchase Via PieChart</h3>
    <img src="./media/sale_purchase_peichart.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 *