Export pie chart using python and matplotlib

Are you ever in need where you need to export certain data as a PDF or Image format? How about if you can do it within a 5 min using python3 and matplotlib library?

Prerequisite

I assume, that you have basic knowledge of python3 and its package management system, pip.

Introduction

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers, and four graphical user interface toolkits.

Installation

First, go to the directory where you want to craft this project. Open the terminal for that location. Now, run the following command.

$pip install matplotlib

Above command will take care of all required library installation for you.

Import required libraries

Add “pylab”, ” argparse” and “os” packages to your project

# Import required libraries
from pylab import figure, axes, pie, title, show, plt
import argparse
import os

Create export directory

We need a directory to export our generated output files. So first, we will define one directory name. Now we will check if directory is already exists or not. If it does not exists, system will create one.

# Default data export DIR
UPLOAD_DIR = 'export'

# Create direcotry if not exists
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

Command line argument setup

Now, we will learn different type of parameter setting to use when accepting command line arguments from the user.

This includes “type”, “is required validation”, adding help text and multiple choice option.

# Basic Command Setup
parser = argparse.ArgumentParser()

# Example for type, required and help param
# type can be string, integer number or list.
parser.add_argument('-a', '--axis', type=str, required=True, help='Provide list of different axes, i.e. 0.1, 0.1, 0.8, 0.8 etc')
parser.add_argument('-f', '--frac', type=str, required=True, help='Fraction value for chart, i.e. 0.1, 0.1, 0.8, 0.8 etc')
parser.add_argument('-l', '--labels', type=str, dest='list', required=True, help="Provide list of labels, i.e. 'Frogs', 'Hogs', 'Dogs', 'Logs' etc ")
parser.add_argument('-t', '--title', type=str, required=True, help='Title of the chart')

# Example for use of "default" and "choises" param in command
parser.add_argument('-s', '--save_as', default='png', choices=['png', 'pdf'], help='Save file as .png or .pdf ')

args = parser.parse_args()

Dynamic setup using variables

Now all set. We have imported required libraries. We also setup commands to accept user input. So, now we will store user inputs into variables to make it function dynamically.

In below code, we will save input into appropriate variables.

# Let's save result into variables
# Save AXIS as a list. Conver it using split and comma seprator. 
# The delimiter can be a space, too, which would though enforce quotes around the argument value
AXIS = [float(item) for item in args.axis.split(',')]
fracs = [float(item) for item in args.frac.split(',')]

labels = args.list.split(',')
TITLE = args.title
SAVE_AS = args.save_as

Create pie chart

Now we have everything we need to create pie chart. We will utilize matplotlib library to create pie chart with dynamic values set in variables.

First, we will create square figure to plot our chart. then we will plot the axis on it. In below code, you can see how we’ve created the plot and crafted a pie chart over it.

# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes(AXIS)

explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title(TITLE, bbox={'facecolor': '0.8', 'pad': 5})

# Final step, save generated output into directory with user selected export type
plt.savefig(UPLOAD_DIR + '/foo.' + SAVE_AS)

Execute the code

Run following command to execute the code and export the result.

python piechart.py -a="0.1,0.1,0.8,0.8" -f="15, 30, 45, 10" -l="Frogs,Hogs,Dogs,Logs" -t="Test title" -s=png

Conclusion

Matplotlib is very powerful and feature reach graph library. What we created above is just one type of basic graph. We will create more available graphs with in more developer friendly way.

Download

Source code is available to download under MIT license. Please visit my GitHub page for all available repositories. Visit Python Matplotlib Basic Example repository for download above source code.

More Articles for You

AWS EC2: Recover data from inaccessible Instance or EBS (Storage)

\n\n\n\nBefore getting started further, kindly check your AWS free tire eligibility here, https://aws.amazon.com/free/\n\n\n\nSo now, let’s jump to the tutorial and …

— Featured —

Getting Started with AWS and EC2 Instance

\n\n\n\nBefore getting started further, kindly check your AWS free tire eligibility here, https://aws.amazon.com/free/\n\n\n\nSo now, let’s jump to the tutorial and …

— Featured —