Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Matplotlib 3.0 Cookbook
Matplotlib 3.0 Cookbook

Matplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Matplotlib 3.0 Cookbook

Getting Started with Basic Plots

In this chapter, we will cover recipes for plotting the following graphs:

  • Line plot
  • Bar plot
  • Scatter plot
  • Bubble plot
  • Stacked plot
  • Pie plot
  • Table chart
  • Polar plot
  • Histogram
  • Box plot
  • Violin plot
  • Heatmap
  • Hinton diagram
  • Images
  • Contour plot
  • Triangulations
  • Stream plot
  • Path

Introduction

A picture is worth a thousand words, and the visualization of data plays a critical role in finding hidden patterns in the data. Over a period of time, a variety of graphs have been developed to represent different relationships between different types of variables. In this chapter, we will see how to use these different graphs in different contexts and how to plot them using Matplotlib.

Line plot

The line plot is used to represent a relationship between two continuous variables. It is typically used to represent the trend of a variable over time, such as GDP growth rate, inflation, interest rates, and stock prices over quarters and years. All the graphs we have seen in Chapter 1, Anatomy of Matplotlib are examples of a line plot.

Getting ready

We will use the Google Stock Price data for plotting time series line plot. We have the data (date and daily closing price, separated by commas) in a .csv file without a header, so we will use the pandas library to read it and pass it on to the matplotlib.pyplot function to plot the graph.

Let's now import required libraries with the following code:

import matplotlib...

Bar plot

Bar plots are the graphs that use bars to compare different categories of data. Bars can be shown vertically or horizontally, based on which axis is used for a categorical variable. Let's assume that we have data on the number of ice creams sold every month in an ice cream parlor over a period of one year. We can visualize this using a bar plot.

Getting ready

We will use the Python calendar package to map numeric months (1 to 12) to the corresponding descriptive months (January to December).

Before we plot the graph, we need to import the necessary packages:

import matplotlib.pyplot as plt
import numpy as np
import calendar
...

Scatter plot

A scatter plot is used to compare distribution of two variables and see whether there is any correlation between them. If there are distinct clusters/segments within the data, it will be clear in the scatter plot.

Getting ready

Import the following libraries:

import matplotlib.pyplot as plt
import pandas as pd

We will use pandas to read the Excel files.

How to do it...

The following code block draws a scatter plot that depicts the relationship between the age and the weight of people:

  1. Set the figure size (width and height) to (10, 6) inches:
plt.figure(figsize...

Bubble plot

A bubble plot is drawn using the same plt.scatter() method. It is a manifestation of the scatter plot, where each point on the graph is shown as a bubble. Each of these bubbles can be displayed with a different color, size, and appearance.

Getting ready

Import the required libraries. We will use pandas to read the Excel file:

import matplotlib.pyplot as plt
import pandas as pd

How to do it...

The following code block plots a bubble plot, for which we have seen a scatter plot earlier:

  1. Load the Iris dataset:
iris = pd.read_csv('iris_dataset.csv',...

Stacked plot

A stacked plot represents the area under the line plot, and multiple line plots are stacked one over the other. It is used to provide a visualization of the cumulative effect of multiple variables being plotted on the y axis.

We will plot the number of product defects by a defect reason code, for three months stacked together to give a cumulative picture for the quarter.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt

How to do it...

The following are the steps to plot a stacked plot:

  1. Define the data for the...

Pie plot

A pie plot is used to represent the contribution of various categories/groups to the total. For example, the contribution of each state to the national GDP, contribution of a movie to the total number of movies released in a year, student grades (A, B, C, D, and E) as a percentage of the total class size, or a distribution of monthly household expenditure on groceries, vegetables, utilities, apparel, education, healthcare, and so on.

Getting ready

Import the required library:

import matplotlib.pyplot as plt

How to do it...

The following code block plots a pie...

Table chart

A table chart is a combination of a bar chart and a table, representing the same data. So, it is a combination of pictorial representation along with the corresponding data in a table.

Getting ready

We will consider an example of the number of batteries sold in each year, with different ampere hour (Ah) ratings. There are two categorical variables: year and Ah ratings, and one numeric variable: the number of batteries sold.

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt

How to do it...

The following code block draws a table...

Polar plot

The polar plot is a chart plotted on the polar axis, which has coordinates as angle (in degrees) and radius, as opposed to the Cartesian system of x and y coordinates. We will take the example of planned versus the actual expense incurred by various departments in an organization. This is also known as a spider web plot.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt

How to do it...

Since it is a circular spider web, we need to connect the last point to the first point, so that there is a circular flow of the...

Histogram

The histogram plot is used to draw the distribution of a continuous variable. Continuous variable values are split into the required number of bins and plotted on the x axis, and the count of values that fall in each of the bins is plotted on the y axis. On the y axis, instead of count, we can also plot percentage of total, in which case it represents probability distribution. This plot is typically used in statistical analysis.

Getting ready

We will use the example of data on prior work experience of participants in a lateral training program. Experience is measured in number of years.

Import the required libraries:

import matplotlib.pyplot as plt
import numpy as np
...

Box plot

The box plot is used to visualize the descriptive statistics of a continuous variable. It visually shows the first and third quartile, median (mean), and whiskers at 1.5 times the Inter Quartile Range (IQR)—the difference between the third and first quartiles, above which are outliers. The first quartile (the bottom of rectangular box) marks a point below which 25% of the total points fall. The third quartile (the top of rectangular box) marks a point below which 75% of the points fall.

If there are no outliers, then whiskers will show min and max values.

This is again used in statistical analysis.

Getting ready

We will use an example of wine quality dataset for this example. We will consider three attributes...

Violin plot

The violin plot is a combination of histogram and box plot. It gives information on the complete distribution of data, along with mean/median, min, and max values.

Getting ready

We will use the same data that we used for the box plot for this example also.

Import the required libraries:

import matplotlib.pyplot as plt
import pandas as pd

How to do it...

The following is the code block that draws violin plots:

  1. Read the data from a CSV file into a pandas DataFrame:
wine_quality = pd.read_csv('winequality.csv', delimiter=';')

  1. Prepare the...

Reading and displaying images

Matplotlib.pyplot has features that enable us to read .jpeg and .png images and covert them to pixel format to display as images.

Getting ready

Import the required library:

 import matplotlib.pyplot as plt

How to do it...

Here is the code block that reads a JPEG file as a pixel-valued list and displays it as an image on the screen:

  1. Read the image louvre.jpg into a three-dimensional array (color images have three channels, whereas black and white images have one channel only):
image = plt.imread('louvre.jpg')
  1. Print the dimensions...

Heatmap

A heatmap is used to visualize data range in different colors with varying intensity. Here, we take the example of plotting a correlation matrix as a heatmap. Elements of the correlation matrix indicate the strength of a linear relationship between the two variables, and the matrix contains such values for all combinations of the attributes in the given data. If the data has five attributes, then the correlation matrix will be a 5 x 5 matrix.

Getting ready

We will use the Wine Quality dataset for this example also. It has 12 different attributes. We will first get a correlation matrix and then plot it as a heatmap. There is no heatmap function/method as such, so we will use the same imshow method that we used to read...

Hinton diagram

The Hinton diagram is a 2D plot for visualizing weight matrices in deep-learning applications. Matplotlib does not have a direct method to plot this diagram. So, we will have to write code to plot this. The weight matrix for this is taken from one of the machine learning algorithms that classifies images.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

How to do it...

The following code block defines the function and makes a call to the function to plot the Hinton diagram:

  1. Read the weight...

Contour plot

The contour plot is typically used to display how the error varies with varying coefficients that are being optimized in a machine learning algorithm, such as linear regression. If the linear regression coefficients are theta0 and theta1, and the error between the predicted value and the actual value is a Loss, then for a given Loss value, all the values of theta0 and theta1 form a contour. For different values of Loss, different contours are formed by varying the values of theta0 and theta1.

Getting ready

The data for Loss, theta0, theta1, and theta (optimal values of theta0 and theta1 that give the lowest error) are taken from one of the regression problems for plotting the contour plot. If theta0 and theta1...

Triangulations

Triangulations are used to plot geographical maps, which help with understanding the relative distance between various points. The longitude and latitude values are used as x, y coordinates to plot the points. To draw a triangle, three points are required; these are specified with the corresponding indices of the points on the plot. For a given set of coordinates, Matplotlib can compute triangles automatically and plot the graph, or optionally we can also provide triangles as an argument.

Getting ready

Import the required libraries. We will introduce the tri package for triangulations:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
...

Stream plot

Stream plots, also known as streamline plots are used to visualize vector fields. They are mostly used in the engineering and scientific communities. They use vectors and their velocities as a function of base vectors to draw these plots.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

How to do it...

The following code block creates a stream plot:

  1. Prepare the data for the stream plot:
x, y = np.linspace(-3,3,100), np.linspace(-2,4,50)
  1. Create the mesh grid:
X, Y = np.meshgrid...

Path

Path is a method provided by Matplotlib for drawing custom charts. It uses a helper function patch that is provided by Matplotlib. Let's see how this can be used to draw a simple plot.

Getting ready

Import the required libraries. Two new packages, Path and patches, will be introduced here:

import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

How to do it...

The following code block defines points and associated lines and curves to be drawn to form the overall picture:

  1. Define the points along with the first curve...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Master Matplotlib for data visualization
  • Customize basic plots to make and deploy figures in cloud environments
  • Explore recipes to design various data visualizations from simple bar charts to advanced 3D plots

Description

Matplotlib provides a large library of customizable plots, along with a comprehensive set of backends. Matplotlib 3.0 Cookbook is your hands-on guide to exploring the world of Matplotlib, and covers the most effective plotting packages for Python 3.7. With the help of this cookbook, you'll be able to tackle any problem you might come across while designing attractive, insightful data visualizations. With the help of over 150 recipes, you'll learn how to develop plots related to business intelligence, data science, and engineering disciplines with highly detailed visualizations. Once you've familiarized yourself with the fundamentals, you'll move on to developing professional dashboards with a wide variety of graphs and sophisticated grid layouts in 2D and 3D. You'll annotate and add rich text to the plots, enabling the creation of a business storyline. In addition to this, you'll learn how to save figures and animations in various formats for downstream deployment, followed by extending the functionality offered by various internal and third-party toolkits, such as axisartist, axes_grid, Cartopy, and Seaborn. By the end of this book, you'll be able to create high-quality customized plots and deploy them on the web and on supported GUI applications such as Tkinter, Qt 5, and wxPython by implementing real-world use cases and examples.

Who is this book for?

The Matplotlib 3.0 Cookbook is for you if you are a data analyst, data scientist, or Python developer looking for quick recipes for a multitude of visualizations. This book is also for those who want to build variations of interactive visualizations.

What you will learn

  • Develop simple to advanced data visualizations in Matplotlib
  • Use the pyplot API to quickly develop and deploy different plots
  • Use object-oriented APIs for maximum flexibility with the customization of figures
  • Develop interactive plots with animation and widgets
  • Use maps for geographical plotting
  • Enrich your visualizations using embedded texts and mathematical expressions
  • Embed Matplotlib plots into other GUIs used for developing applications
  • Use toolkits such as axisartist, axes_grid1, and cartopy to extend the base functionality of Matplotlib

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 23, 2018
Length: 676 pages
Edition : 1st
Language : English
ISBN-13 : 9781789138665
Category :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Oct 23, 2018
Length: 676 pages
Edition : 1st
Language : English
ISBN-13 : 9781789138665
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 125.97
Matplotlib for Python Developers
$43.99
Mastering Matplotlib 2.x
$32.99
Matplotlib 3.0 Cookbook
$48.99
Total $ 125.97 Stars icon

Table of Contents

16 Chapters
Anatomy of Matplotlib Chevron down icon Chevron up icon
Getting Started with Basic Plots Chevron down icon Chevron up icon
Plotting Multiple Charts, Subplots, and Figures Chevron down icon Chevron up icon
Developing Visualizations for Publishing Quality Chevron down icon Chevron up icon
Plotting with Object-Oriented API Chevron down icon Chevron up icon
Plotting with Advanced Features Chevron down icon Chevron up icon
Embedding Text and Expressions Chevron down icon Chevron up icon
Saving the Figure in Different Formats Chevron down icon Chevron up icon
Developing Interactive Plots Chevron down icon Chevron up icon
Embedding Plots in a Graphical User Interface Chevron down icon Chevron up icon
Plotting 3D Graphs Using the mplot3d Toolkit Chevron down icon Chevron up icon
Using the axisartist Toolkit Chevron down icon Chevron up icon
Using the axes_grid1 Toolkit Chevron down icon Chevron up icon
Plotting Geographical Maps Using Cartopy Toolkit Chevron down icon Chevron up icon
Exploratory Data Analysis Using the Seaborn Toolkit Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(5 Ratings)
5 star 20%
4 star 20%
3 star 20%
2 star 20%
1 star 20%
John C. May 20, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a well written and thorough survey of the Matplotlib library with a solid introduction to the Seaborn library. You don't need to know anything about Matplotlib to get started. It starts with plotting a line through two points on default axes and adds more and more features to the examples as the book progresses.That said, you DO need a basic competency in Python to understand the explanations. This is, after all, a library of extensions to the Python language.Super helpful is full code for all the examples available for download. You can read the discussion, experiment with the example code and really understand what's going on. You'll need the free open source Jupyter Python IDE to run the code, but Jupyter is probably the most frequently used platform for running Matplotlib, and it's ideal for this kind of hands on learning.
Amazon Verified review Amazon
Saurabh Oct 02, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Matplotlib is tedious but you need to know it whether you are using pandas based plotting or seaborn.I like the fact that book is very detailed. I don't know of a better book right now to learn matplotlib. However, the approach uses a lot of state based plotting, which is no longer recommended. For example it uses a lot of plt.xticks() instead of ax.xticks() approach.Another problem is it does not show how to make plots using pandas data frame plot method. Since most people making plots today are using pandas, I'm disappointed that the data frame plot method was not covered.Overall this book is not for beginner python users. It will be appreciated more by intermediate python and pandas users.
Amazon Verified review Amazon
Student of the Universe Oct 23, 2022
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I've not a seasoned Python developer, so, when I purchased this book, I was pleased to see it has all the content I was interested in learning. I downloaded the code for this book from GitHub, worked through the first two chapters, and then in chapter 3, I ran into multiple errors right off. It appears that the book is out of date and the GitHub site is not updated for the latest Python 3 that is installed with Anaconda (I'm using the Mac). So, there is a chart where the author called out what is required for Windows 10. I will have to use Parallels on the Mac to see if that works. Pitty.
Amazon Verified review Amazon
Richard McClellan May 15, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
It is a pretty good book. The code examples are clear, and well explained.HOWEVER. This is 2019. You buy a programming book (I bought the Kindle version) you expect to be able to access the code. Usually on-line or a download. Since you can't cut and past out of Kindle, typing in examples is wholly last century.Well, there is a website (packt) that supposedly lets you download. 95mb zipped file later, I find that it is some combination of pdf's and png's of output. No code. Some mysterious IPYNB extension. So--a last century level, effectively. Last century you got a CD.It would be at least 4 stars if I could get at the code without having to type it all in.Two stars because it isn't entirely worthless.
Amazon Verified review Amazon
Adrian Savage Apr 12, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This is, as it says, a cookbook. That is it give recipes for many different uses for Matplotlib. What it fails to do is to give any useful information as to the Matplotlib modules, the uses to which they can be put and the syntax of each command. In fact, should you wish to find out how a call such as Matplotlib.dates.DateFormatter works, you will not even find it in the index. In fact date and time are not in the index so in the 652 mostly useless pages of the book, you will struggle to make a graph with date/time on the x axis. As a cookbook its recipes are without taste or interest.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.