# Matplotlib Tutorial in Python | Chapter 1 | Introduction

• 537 Views

Matplotlib Tutorial in Python

Chapter 1 | Introduction

In this series of Matplotlib Tutorials in Python, we will cover all concepts of matplotlib from beginners to expert. Starting with how to install Matplotlib to how to create matplotlib plots, this series is the only matplotlib tutorial which you will need.

Matplotlib - Introduction

Matplolib is a plotting library which is used to generate 2D figures/graphs from data in Python. Matplolib is extensively used in data sciences as it produces high quality images which can be used in Publication also. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers etc.

Installation

Matlplotlib can be easily installed using pip. You can read more about installing matplotlib from here

\$ pip install matplotlib


Matplotlib Tutorial in Python - Creating your first plot

Let us start with creating line plot as our first plot in Matplolib. Create an empty file matplotlib_tutorial.py and start editing it in your favourite editor. (I like to use Sublime Text as my editor). You can read more about the editors/shell here. First of all, we will need to import matplotlib. Then I have taken age-wise data of Indian popluation from here. It is in excel format so for the sake of this tutorial I have just extracted a part of it as lists.

# matplotlib_tutorial.py

import matplotlib.pyplot as plt #This is the general convention

ages = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

total_population = [27877307, 24280683, 25258169, 25899454, 24592293, 21217467, 27958147, 20859088, 28882735, 19978972]

plt.plot(ages, total_population)
plt.show()


Creating a line plot in Matplotlib is as simple as passing the x-axis and y-axis data in plt.plot() and then calling plt.show() and we will get the following plot.

As you can see in the plot, the x-axis denotes the ages and the y-axis denotes the total population. Even, the simple Matplotlib Plot comes with so many inbuit functions:-

1. Home Button - It takes back to the home/basic position, if you have used other options and moved/zoomed/panned your plot.
2. Left Arrow - It moves the plot left-wards.
3. Right Arrow - It moves the plot right-wards.
4. Pan - It helps you to move the plot by panning.
5. Zoom- It helps you to select a rectagular portion of the map and zoom into it.
6. Configuration tool - It is used to set top/bottom/left/right padding and width and height space.
7. Save - It saves the plot as a png at your desired location.

Matplotlib Tutorial in Python - Setting titles/labels of the Matplotlib Plot

Adding lables, titles to the Matplotlib Plots in Python is as easy as adding plt.xlabel() , plt.ylabel() , plt.title() plt.show()

# matplotlib_tutorial.py

plt.xlabel("Age")
plt.ylabel("Total Population")
plt.title("Age-wise population of India")
plt.show()


Just by using these options, now our Matplotlib Plot have more information vis-a-vis a title and labels on both the axis.

Matplotlib Tutorial in Python- Plots with multiple data

Previously, we had plotted the data for the total population, now we will add data for male population and female populateion of that age. We will be sharing the ages on x-axis of the Matplotlib Tutorial.

# matplotlib_tutorial.py

# Male Population
male_population = [14637892, 12563775, 13165128, 13739746, 13027935, 11349449, 15020851, 10844415, 14892165, 10532278]

#Female Population
female_population = [13239415, 11716908, 12093041, 12159708, 11564358, 9868018, 12937296, 10014673, 13990570, 9446694]

plt.plot(ages, total_population)
plt.plot(ages, male_population)
plt.plot(ages, female_population)


Matplotlib will automatically draw plots of different colors for this data.

Matplotlib Tutorial in Python - Adding legends to matplotlib plot

Though all the three plots above are of different color, but still it is not clear, what each plot represents. So, we will be adding legends as under:-

# matplotlib_tutorial.py

plt.plot(ages, total_population, label = "Total Population")
plt.plot(ages, male_population, label = "Male Population")
plt.plot(ages, female_population, label = "Female Population" )
plt.legend()
plt.show()


Matplotlib Tutorial in Python - Setting Markers, line-style and colors of the Matplotlib Plot

You can also set the markers, line-style and colors of the Matplotlib Plot by using the format method. The details of the same can be found here

Setting up the markers, line-style and colors of the plot is as easy as providing the following format in plt.plot() method.

# matplotlib_tutorial.py

fmt = '[marker][line][color]'


You can choose from the following markers :-

Markers

character   description
'.'         point marker
','         pixel marker
'o'         circle marker
'v'         triangle_down marker
'^'         triangle_up marker
'<'         triangle_left marker
'>'         triangle_right marker
'1'         tri_down marker
'2'         tri_up marker
'3'         tri_left marker
'4'         tri_right marker
's'         square marker
'p'         pentagon marker
'*'         star marker
'h'         hexagon1 marker
'H'         hexagon2 marker
'+'         plus marker
'x'         x marker
'D'         diamond marker
'd'         thin_diamond marker
'|'         vline marker
'_'         hline marker


Following line-styles:-

Line Styles

character   description
'-'         solid line style
'--'        dashed line style
'-.'        dash-dot line style
':'         dotted line style


And following colors:-

Colors

The supported color abbreviations are the single letter codes

character   color
'b'         blue
'g'         green
'r'         red
'c'         cyan
'm'         magenta
'y'         yellow
'k'         black
'w'         white


If the color is the only part of the format string, you can additionally use any matplotlib.colors spec, e.g. full names (‘green’) or hex strings (‘#008000’).

Let us add the this feauture to our plot.

# matplotlib_tutorial.py

plt.plot(ages, total_population, '.-b', label="Total Population")
plt.plot(ages, male_population, 'o--g', label="Male Population")
plt.plot(ages, female_population, '^-r', label="Female Population")


We will get the following Matplotlib Plot with markers, line-styles and colors:-

However, if you find the above notation less-readable and want your code to be more explicit, you can pass all these as arguments. The following code will produce the same plot:-

# matplotlib_tutorial.py

plt.plot(ages, total_population, color='b', linestyle='-', marker='.', label="Total Population")
plt.plot(ages, male_population, color='g', linestyle='--', marker='o', label="Male Population")
plt.plot(ages, female_population, color='r', linestyle='-', marker='^', label="Female Population")


Matplotlib Tutorial in Python - Adding grids and setting line-width of Matplotlib Plots

You can easily set the linewidth of the plot by passing linewidth, which takes a float as argument, to plt.plot().
Also to make plot more readable, we can add grids by passing plt.grid().

# matplotlib_tutorial.py

plt.plot(ages, total_population, color='b', linestyle='-', marker='.', linewidth=4, label="Total Population")
plt.plot(ages, male_population, color='g', linestyle='--', marker='o', linewidth=3, label="Male Population")
plt.plot(ages, female_population, color='r', linestyle='-', marker='^', linewidth=2, label="Female Population")
plt.grid()


Matplotlib Tutorial in Python - Inbuilt Styles

There are many inbuilt styles in Matplotlib, which can be used to style your plots. To get the list of the available styles:-

print(plt.style.available)

# Output
['seaborn-dark', 'seaborn-darkgrid', 'seaborn-ticks', 'fivethirtyeight', 'seaborn-whitegrid', 'classic', '_classic_test', 'fast', 'seaborn-talk', 'seaborn-dark-palette', 'seaborn-bright', 'seaborn-pastel', 'grayscale', 'seaborn-notebook', 'ggplot', 'seaborn-colorblind', 'seaborn-muted', 'seaborn', 'Solarize_Light2', 'seaborn-paper', 'bmh', 'tableau-colorblind10', 'seaborn-white', 'dark_background', 'seaborn-poster', 'seaborn-deep']


So, we can use the in-built styles of matplotlib by simply using the plt.style.use(). :-

plt.style.use('ggplot')


Matplotlib Style- ggplot

Matplotlib Style - xkcd

You can also draw plots with the comic style of xkcd by simply passing plt.xkcd() instead of plt.style.use().

Saving the Matplotlib plot as png

Instead of using the save button on the matplotlib plot, you can directly save the image from the code by using plt.savefig(‘yourfilename.png’).

plt.savefig('myplot.png') #this will save the plot in the current directory.
plt.savefig('path\to\my\directory\myplot.png') # this will save the plot to the desired directory.


In case of any query, you can leave the comment below.

In the next chapter , we will learn about extracting data from csv (instead of passing lists) and bar charts.

Matplotlib Tutorial in Python | Chapter 1 | Introduction

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter 6

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Chart | Matplotlib Tutorial | Chapter 11

In case of any query, you can leave the comment below.

If you want to support our work. You can do it using Patreon.

By Udit Vashisht

# Python unittest module

Why to unit test your python source code?

All programmers want their code to be impeccable, but as the saying goes, to err is human, we make mistakes and leave bugs in our source code. Here is where the unit testing comes to our rescue. If you ...

##### Chapter 2 - Quick setup
By Udit Vashisht

It doesn’t matter which OS you are using, Python3 comes with multiple OS compatibility.

Install on Windows PC

Follow the steps in this post to install on Windows PC.

Install on MacOS/Linux

Follow the steps in this post to install on MacOS or Linux.

Ditching IDLE

...