What is Matplotlib and how to use it in Python

In this Python tutorial, we will discuss the matplotlib library, What is matplotlib, How to use it and we shall also cover the following topics:

  • What is matplotlib
  • Features of matplotlib
  • Matplotlib environment setup
  • Importing matplotlib library
  • Matplotlib pyplot API
  • Types of plots in matplotlib
  • Image functions in matplotlib
  • Axis functions in matplotlib
  • Figure functions in matplotlib

What is matplotlib

There are numerous libraries present in Python. And Matplotlib is one of the most successful and commonly used libraries, that provide various tools for data visualization in Python.

It is one of the most powerful plotting libraries in Python. It is a cross-platform library that provides various tools to create 2D plots from the data in lists or arrays in python.

It was created and coded by John D. Hunter in Python programming language in 2003. The current stable version of matplotlib is 3.4.2, that released on 8 May 2021. It makes use of NumPy, a library that provides the numerical mathematical extension for Python.

It also provides an object-oriented API that enables it, in extending the functionality to put the static plots in applications by using various Python GUI toolkits available (Tkinter, PyQt, etc).

It provides a user to visualize data using a variety of different types of plots to make data understandable. You can use, these different types of plots (scatterplots, histograms, bar charts, errorcharts, boxplots, etc.) by writing few lines of code in python.

You can use the matplotlib package in any Python shell, IPython shell, Jupyter notebook, jupyter lab, cloud (IBM Watson studio, Google collab, etc), and web application servers (flask, Django using pycharm or anaconda).

Read Matplotlib increase plot size

Features of matplotlib

  • It is used as a data visualization library for the Python programming language.
  • It provides quite the simplest and most common way to plot data in python.
  • It provides such tools that can be used to create publication-standard plots and figures in variety of export formats and various environments (pycharm, jupyter notebook) across platforms.
  • It provides a procedural interface called Pylab, which is used designed to make it work like MATLAB, a programming language used by scientists, researchers. MATLAB is a paid application software and not open source.
  • It is similar to plotting in MATLAB, as it allows users to have a full control over fonts, lines, colors, styles, and axes properties like MATLAB.
  • Matplotlib along with NumPy can be treated as the open source equivalent of MATLAB.
  • It provides excellent way to produce quality static-visualizations that can be used for publications and professional presentations.
  • It also provides compatibility with various of other third-party libraries and packages, that extend its functionality. For example, seaborn, ggplot that provide more features for plotting, and basemap and cartopy, that are used to plot geospatial data.
  • Matplotlib is a cross-platform library that can be used in various python scripts, any python shell (available in IDLE, pycharm, etc) and IPython shells (cond, jupyter notebook), the web application servers (Django, flask), and various GUI toolkits (Tkinter, PyQt, WxPythonotTkinter).
  • It is clear that, matplotlib with its various of compatible third-party libraries provide user the powerful tools to visualize a variety of data.

Read Matplotlib 1.3.1 requires nose which is not installed

Matplotlib environment setup

Matplotlib and its dependency packages are available in the form of wheel packages on the standard Python package repositories and you can install them easily on Windows, Linux, and macOS systems using the pip package manager, once you have installed the python in your system. You can do it so, by executing the following command:

pip3 install matplotlib

If the Python package is not installed for all users in your system then, you have to install Microsoft Visual C++ 2008 (64 bit or 32 bit for Python 2.7) or Microsoft Visual C++ 2010 (64 bit or 32 bit for Python 3.4).

  • In windows, you can easily download and install the above dependency package from any browser.
  • If you are using Python 2.7 on a MacOS then, execute the following command:
xcode-select –install

When the above command is executed, a dependency of the package, subprocess32 may be compiled.

  • And if you are working on some old version of Linux with Python 2.7 installed in it, you have to install the master version of subprocess32.

The above steps for various OS, set the environment for the matplotlib package to be installed and used.

Read What is add_axes matplotlib

Importing matplotlib library

You can use matplotlib and utilize its functionalities in python by simply importing it into your environment (Jupiter notebook, google collab, IDLE, etc). The code to import matplotlib is as follows:

-- Importing the matplotlib library
import matplotlib

-- Importing the matplotlib library and alias it with a shorter name
import matplotlib as plt

In the above code, reference name (alias) can be any of your choices, but the most commonly used name is plt. So, we will also use it. A reference name gives a convenient and easy use of the library, you have to type less code to reference it in the further codes.

Two important things to remember, whenever you plot with matplotlib in python:

  • Type of graph: Where you have to define the type of the plot, can be a bar chart, line chart, histogram, etc.
  • And show the graph: Here, you will display the graph.

Read Matplotlib unknown projection ‘3d’

Matplotlib pyplot API

matplotlib.pyplot is a state-based interface to matplotlib. It is a collection of command-style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to the plot (figure).

  • A function can create a figure: matplotlib.pyplot.figure(), Another function that creates a plotting area in a figure: matplotlib.pyplot.plot().
  • Plots some lines in a plotting area,
  • Decorates the plot with labels, annotations, etc.

You can import the pyplot API in python by the following code:

import matplotlib.pyplot as plt

-- OR

from matplotlib import pyplot as plt

In the above code, the pyplot API from the matplotlib library is imported into the program and referenced as the plt. You can give any name, but plt is standard and most commonly used.

Read: Matplotlib 2d surface plot

Types of plots in matplotlib

There are a variety of plots available in matplotlib, the following are some most commonly used plots:

S.No.Plot functionsDescription
1plot()You can plot markers and/or lines to the axes.
2scatter()It creates a scatter plot of x VS y.
3bar()It creates a bar plot.
4barh()It creates a horizontal bar plot.
5hist()It plots a histogram.
6hist2d()It creates a 2D histogram plot.
7boxplot()It creates a box-with-whisker plot.
8pie()It plots a pie chart.
9stackplot()It creates a stacked area plot.
10polar()It creates a polar plot.
11stem()It creates a stem plot.
12step()It creates a step plot.
13quiver()It plots a 2D field of arrows.
Types of plots in matplotlib

Plots are a way to understand patterns, trends, and correlations of data provided. We can say that these are the tools to have an insight into some quantitative information.

Let’s see how to implement some of the basic plots mentioned above on some sample data, so open up jupyter notebook or any Ipython shell and let’s do some examples:

  • Line plot:
# Importing the pyplot API from matplotlib library
from matplotlib import pyplot as plt

# x-axis values in a list
x = [3, 8, 1, 9, 7]

# y-axis values in a list
y = [7, 4, 2, 5, 10]

# function to plot line in matplotlib
plt.plot(x, y)

# Function to show the plot
plt.show()
Line plot in matplotlib
Line plot in matplotlib
  • Scatter plot:
# Importing the pyplot API from matplotlib library
from matplotlib import pyplot as plt

# x-axis values in a list
x = [3, 8, 1, 9, 7]

# y-axis values in a list
y = [7, 4, 2, 5, 10]

# function to plot scatter in matplotlib
plt.scatter(x, y)

# Function to show the plot
plt.show()
Scatter plot in matplotlib
Scatter plot in matplotlib
  • Bar plot:
# Importing the pyplot API from matplotlib library
from matplotlib import pyplot as plt

# x-axis values in a list
x = [3, 8, 1, 9, 7]

# y-axis values in a list
y = [7, 4, 2, 5, 10]

# function to plot bar graph in matplotlib
plt.bar(x, y)

# Function to show the plot
plt.show()
Bar plot in matplotlib
Bar plot in matplotlib
  • Histogram:
# Importing the pyplot API from matplotlib library
from matplotlib import pyplot as plt

# y-axis values in a list
y = [7, 4, 2, 5, 10]

# function to plot histogram in matplotlib
plt.hist(y)

# Function to show the plot
plt.show()
Histogram in matplotlib
Histogram in matplotlib
  • Pie chart:
# Importing the pyplot API from matplotlib library
from matplotlib import pyplot as plt

# x-axis values in a list
x = [7, 4, 2, 5, 10]

# y-axis values in a list
names = ['Sam', 'Aron', 'Bence', 'Hegrad', 'kristina']

# function to plot pie chart in matplotlib
plt.pie(y, labels=names)

# Function to show the plot
plt.show()
Pie chart in matplotlib
Pie chart in matplotlib

Read: Matplotlib is currently using agg a non-gui backend

Image functions in matplotlib

The Image functions available in matplotlib are as follows:

S.No.Image functionsDescription
1imread()It reads an image from a file into an array.
2imsave()It saves an array as in image file.
3imshow()It displays an image on the axes.
Image functions in matplotlib

Axis functions in matplotlib

You can customize the axes properties by using the image functions available in matplotlib which are mentioned as follows:

S.No.Axis functionsDescription
1axes()It adds axes to the figure.
2text()It adds text to the axes.
3title()It sets a title for the current axes.
4xlabel()It sets the label of the x-axis of the current axes.
5ylabel()It sets the label of the y-axis of the current axes.
6xlim()It gets or sets the x-axis limits of the current axes.
7ylim()It gets or sets the y-axis limits of the current axes.
8xscale()It sets the scaling of the x-axis of the current axes.
9yscale() It sets the scaling of the y-axis of the current axes.
10xticks()It gets or sets the x-limits of the current tick locations and labels.
11yticks()It gets or sets the y-limits of the current tick locations and labels.
Axis functions in matplotlib

Read Matplotlib time series plot

Figure functions in matplotlib

You can create, save, and display a figure in matplotlib by using the given following functions:

S.No.Figure functionsDescription
1figure()It creates a new figure.
2show()It displays a specified figure.
3figtext()It adds text to the figure.
4savefig()It saves the current figure.
5close()It closes a figure window.
Figure functions in matplotlib

You may like the following Python Matplotlib tutorials:

In this Python tutorial, we have discussed what is matplotlib library, and how to use it in Python and also covered the following topics:

  • What is matplotlib
  • Features of matplotlib
  • Matplotlib environment setup
  • Importing matplotlib library
  • Matplotlib pyplot API
  • Types of plots in matplotlib
  • Image functions in matplotlib
  • Axis functions in matplotlib
  • Figure functions in matplotlib