Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Matplotlib 2.x By Example
Matplotlib 2.x By Example

Matplotlib 2.x By Example: Multi-dimensional charts, graphs, and plots in Python

Arrow left icon
Profile Icon Allen Yu Profile Icon Aldrin Yim Profile Icon Claire Chung
Arrow right icon
€8.99 €29.99
eBook Aug 2017 334 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Allen Yu Profile Icon Aldrin Yim Profile Icon Claire Chung
Arrow right icon
€8.99 €29.99
eBook Aug 2017 334 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Matplotlib 2.x By Example

Figure Aesthetics

Now that you have entered the world of Matplotlib, surely you will want more than plain boring figures that look all the same. This chapter talks about the aesthetics of a figure. We introduce the structure and components of a Matplotlib figure and how to style these details. In this chapter, you will learn how to make a figure stylish, professional, and genuinely yours.

Here are the topics covered in this chapter:

  • Basic structure and terminologies of a Matplotlib figure
  • Setting colors in Matplotlib
  • Adjusting text formats
  • Lines and markers
    • Customizing line styles
    • Customizing marker styles
  • Grids, ticks, and axes
    • Adding and adjusting grid lines
    • Adjusting tick spacing
    • Customizing tick formatters
    • Adding axes labeling
    • Nonlinear axes
  • Title and legends
  • Style sheet support

Basic structure of a Matplotlib figure

A basic Matplotlib figure is made up of multiple components common to different plot types. It will be useful to familiarize ourselves with the terminologies, as we will be using them frequently in plotting. To get you up to speed, we have prepared a glossary of these basic objects. For clearer illustration, here is a plot adapted from Matplotlib's official website that nicely highlights the anatomy of a typical Matplotlib figure:

Glossary of objects in a Matplotlib figure

  • Figure: A figure is the whole plotting area that contains all plot elements. Multiple subplots may be tiled in grid within one figure.
  • Subplot: A subplot is a subregion in a figure that contains all of the relevant...

Setting colors in Matplotlib

Many elements in a Matplotlib figure can have their colors specified. There are several ways to do so. You will come across the color parameter as a keyword argument for style settings very often in different functions. The alternate abbreviated keyword c can often be used. We will first briefly introduce the general rule here.

Single letters for basic built-in colors

There is a list of common colors we can quickly call with single letters:

  • b: Blue
  • g: Green
  • r: Red
  • c: Cyan
  • m: Magenta
  • y: Yellow
  • k: Black
  • w: White

Names of standard HTML colors

...

Adjusting text formats

For an informative figure, we typically have a number of text elements, including the title, labels of axes and ticks, legend, and any additional annotations. We can adjust the font size and font family in the default rc settings. These settings are set in a dictionary-like variable, matplotlib.rcParams, so you can do import matplotlib and define a parameter like this:

matplotlib.rcParams['font.size'] = 18 

Matplotlib also provides functions to alter the settings. The matplotlib.rc() changes the parameters one by one, whereas matplotlib.rcParams.update() accepts a dictionary input to change multiple settings simultaneously. Let's say we would like to change the font size to 20 and font family to serif, then use. We can do so in two ways:

matplotlib.rc('font', size=18)
matplotlib.rc('font&apos...

Customizing lines and markers

Lines and markers are key components found among various plots. Many times, we may want to customize their appearance to better distinguish different datasets or for better or more consistent styling. Whereas markers are mainly used to show data, such as line plots and scatter plots, lines are involved in various components, such as grids, axes, and box outlines. Like text properties, we can easily apply similar settings for different line or marker objects with the same method.

Lines

Most lines in Matplotlib are drawn with the lines  class, including the ones that display the data and those setting area boundaries. Their style can be adjusted by altering parameters in ...

Customizing grids, ticks, and axes

Lines of grids, ticks, and axes help us to visually locate and measure the data values. Their distribution and style determine whether they make good visual aids for the plot or clutter the figure. We will demonstrate the basic methods here.

Grids

Sometimes it may not be easy to tell the coordinates of any point in the plot. Grid lines extend from axis tick marks and help us estimate the value at a certain position.

Adding grids

Grids can be added by calling pyplot.grid(). By default, grid lines will be added at major tick marks...

Using style sheets

We have learned to set the style details step by step so far. The matplotlib.style module provides a handy way to apply a predefined global style to the whole figure. There are a number of built-in style sheets coming along the matplotlib package. You can call matplotlib.style.available to check them out:

The function returns a list of built-in style sheets, including classic, seaborn, and ggplot. Classic refers to the Matplotlib style before version 2.0. Seaborn is a popular package built on top of Matplotlib that offers some special plotting APIs and themes for generating aesthetically attractive statistical figures. In Matplotlib 2.0, we can easily work on the styling natively for simple plot types, without importing an extra module. Multiple style sheets for different purposes are available. The ...

Title and legend

Title and legend are pieces of text that facilitate quick comprehension of the data context. Although a title is not required or recommended, sometimes, such as in inline figures of many scientific publications, adding a title for your plot often helps make the message clear, especially when your figure is not accompanied by explanatory text. For plots with multiple datasets, it is a good practice to keep a data legend with a distinct color or pattern code labeled with the corresponding identities.

Adding a title to your figure

The title of a figure can be set by pyplot.title() or axes.set_title(). Text properties can be supplied as keyword arguments.

...

Test your skills

Now that we have gone through each style setting one by one, it's your showtime to combine all the techniques!

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib as mpl

mpl.style.use('seaborn-darkgrid')

# 2001-2015 per genome sequencing cost in USD
# Adapted from NIH National Human Genome Research Institute figures
# genome.gov/sequencingcosts
# Data were quoted from builtwith.com on May 8th 2017
# Seasonal data were averaged by year for simplicity

# Prepare the data
years = list(range(2001,2016))
y_pos = np.arange(len(years))
seqcost = [95263071.92,70175437.42,61448421.50,53751684.08,
40157554.23,28780376.21,\
20442576.14,19934345.74,18519312.16,17534969.56,16159699.44,
16180224.10,\
13801124.19,12585658.90,11732534.52,11455315.22,10474556.36,
9408738.91,\
9047002.97,8927342.14,7147571.39,3063819.99,1352982.23,752079...

Summary

In this chapter, you learned how to set the styles, including colors, sizes, and shapes, of various elements in a Matplotlib plot. Now you are also aware of some stylistic considerations for a refined figure.

In the next chapter, we will continue to discuss the appearance of plots, moving our focus to the layout and annotation.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create and customize live graphs, by adding style, color, font to make appealing graphs.
  • A complete guide with insightful use cases and examples to perform data visualizations with Matplotlib's extensive toolkits.
  • Create timestamp data visualizations on 2D and 3D graphs in form of plots, histogram, bar charts, scatterplots and more.

Description

Big data analytics are driving innovations in scientific research, digital marketing, policy-making and much more. Matplotlib offers simple but powerful plotting interface, versatile plot types and robust customization. Matplotlib 2.x By Example illustrates the methods and applications of various plot types through real world examples. It begins by giving readers the basic know-how on how to create and customize plots by Matplotlib. It further covers how to plot different types of economic data in the form of 2D and 3D graphs, which give insights from a deluge of data from public repositories, such as Quandl Finance. You will learn to visualize geographical data on maps and implement interactive charts. By the end of this book, you will become well versed with Matplotlib in your day-to-day work to perform advanced data visualization. This book will guide you to prepare high quality figures for manuscripts and presentations. You will learn to create intuitive info-graphics and reshaping your message crisply understandable.

Who is this book for?

This book is for anyone interested in data visualization, to get insights from big data with Python and Matplotlib 2.x. With this book you will be able to extend your knowledge and learn how to use python code in order to visualize your data with Matplotlib. Basic knowledge of Python is expected.

What you will learn

  • • Familiarize with the latest features in Matplotlib 2.x
  • • Create data visualizations on 2D and 3D charts in the form of bar charts, bubble charts, heat maps, histograms, scatter plots, stacked area charts, swarm plots and many more.
  • • Make clear and appealing figures for scientific publications.
  • • Create interactive charts and animation.
  • • Extend the functionalities of Matplotlib with third-party packages, such as Basemap, GeoPandas, Mplot3d, Pandas, Scikit-learn, and Seaborn.
  • • Design intuitive infographics for effective storytelling.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 28, 2017
Length: 334 pages
Edition : 1st
Language : English
ISBN-13 : 9781788292139
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 28, 2017
Length: 334 pages
Edition : 1st
Language : English
ISBN-13 : 9781788292139
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 99.97
SciPy Recipes
€29.99
Python Machine Learning, Second Edition
€32.99
Matplotlib 2.x By Example
€36.99
Total 99.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Hello Plotting World! Chevron down icon Chevron up icon
Figure Aesthetics Chevron down icon Chevron up icon
Figure Layout and Annotations Chevron down icon Chevron up icon
Visualizing Online Data Chevron down icon Chevron up icon
Visualizing Multivariate Data Chevron down icon Chevron up icon
Adding Interactivity and Animating Plots Chevron down icon Chevron up icon
A Practical Guide to Scientific Plotting Chevron down icon Chevron up icon
Exploratory Data Analytics and Infographics Chevron down icon Chevron up icon
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.