SaralGyaan, Saral Gyaan, Saral Gyan is website which provides free tutorials of Python for absolute beginners in English and Hindi, Learn Python in Hindi, Learn Python for absolute beginners, Learn Python, bootstrap, django, git

Hari S
Author: Hari S


Matplotlib Tutorial in Python | Chapter 1 | Introduction

  • Aug. 24, 2019, 5:25 p.m.
  • 8 minutes read
  • 238 Views
Matplotlib Tutorial in Python | Chapter 1 | Introduction

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.

matplotlib_tutorial_.png

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_1.png

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_2.png

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_3.png

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:-

matplotlib_tutorial_4.png

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_5.png

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_tutorial_ggplot.png

Matplotlib Style - xkcd

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

matplotlib_tutorial_xkcd.png

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.

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook,twitter and youtube.

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.

Table of Contents of Matplotlib Tutorial in Python

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

If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.

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

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



Related Posts

Use Python to send Email
By Hari S | 1 month ago

Use Python to send Emails

In this tutorial we will learn to use Python to send emails. If you are new to python, you can see our beginner’s series. In case you are having trouble installing Python, you can see our posts on installing python on MacOS ...

Read More
Python Histograms | Matplotlib Tutorial in Python | Chapter 6
By Hari S | 3 weeks, 2 days ago

Matplotlib Tutorial in Python

Python Histograms | Chapter 6

A Python Histogram/Matplotlib Histogram is an accurate representation of the distribution of numerical data. Bar graphsrelates to two variables, however a Python Histogram relates to only one variable and shows it distribution in different range of the ...

Read More
Chapter 4 - Print function
By Hari S | 7 months, 2 weeks ago

In the early days of your python, one function that you are going to use the most is the print() function. So, I have decided to add it in the opening chapter of this tutorial. In addition to the print function, you will be learning about commenting out and escape ...

Read More
Search