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

Mastering Matplotlib: A practical guide that takes you beyond the basics of matplotlib and gives solutions to plot complex data

Arrow left icon
Profile Icon Duncan M McGreggor Profile Icon Duncan M. McGreggor
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (8 Ratings)
eBook Jun 2015 292 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Duncan M McGreggor Profile Icon Duncan M. McGreggor
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (8 Ratings)
eBook Jun 2015 292 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€32.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
Table of content icon View table of contents Preview book icon Preview Book

Mastering Matplotlib

Chapter 2. The matplotlib Architecture

As software systems age, they tend to undergo a natural evolution through processes such as feature addition and debugging. The resultant codebase embodies the familiar tension between maintaining the old code and at the same time offering the end users an improved product. Architectures for long-term projects are not something that were originally carved in stone and adhered to monomaniacally ever since. Rather, they are living, adaptive concepts that guide the plans and activities of a project's contributors.

The matplotlib module arose out of such an environment, and it has continuous goals of refining and improving its architecture and updating its older bits to follow the best practices of and the latest advances in not only the project itself, but also the wider Python community over the years since its inception.

In this chapter, we will perform the following tasks:

  • Review the original design goals of matplotlib and explore its evolution...

The original design goals

As mentioned in Chapter 1, Getting Up to Speed, the creators of matplotlib were originally focused on building a GTK+ application for researchers and providing a command interface for the interactive plotting of data, not unlike that provided by MATLAB.

Both of these aims helped drive the development of improved abstractions for matplotlib. It was in this dual crucible that the top-level object of the rendered plots in matplotlib gained its rightful prominence—the Figure. These ideas led to various foundational objects in matplotlib, and the relationships between them ultimately provided the basis for the architecture of this library.

The current matplotlib architecture

The current matplotlib architecture revolves around the operations that are necessary for the users to create, render, and update the Figure objects. Figures can be displayed and interacted with via common user interface events such as the keyboard and mouse inputs. This layer of interaction with common user interface is called the backend layer. A Figure needs to be composed of multiple objects that should be individually modifiable, but it should be implemented in such a way that it has a positive and predictable impact on the other aspects of the Figure. This logical layer is responsible for the abstraction of each visual component that one sees in a Figure. Due to its highly visual nature, this layer was identified as the more general concept of creating visual art and is thus referred to as the artist layer. Lastly, the Figure needs to support programmatic interaction and provide the users with the ability to manipulate Figures with a syntax that...

The backend layer

Seasoned computer scientists, engineers, and software developers all know that one of the subtler and trickier problems that arise in our industry is naming. It sounds a bit silly and it is repeatedly the subject of jokes, but the difficulty remains—how do you speak or write explicitly on a subject whose very nature requires exquisite precision and yet has great ambiguity that arises in different contexts?

We have the same problem with the term backend. Here, as in so many other instances, the context is everything. Our context is matplotlib, a set of tools, and a framework where everything is done in support of the visualizing of data and their relationships. The term backend has to be viewed from this perspective to support the generation of plots. The matplotlib backend has nothing to do with other noteworthy backends such as databases, servers, messaging systems, or dispatchers of various sorts. The backend of matplotlib is an abstraction layer over various components...

The artist layer

The artist layer constitutes the bulk of what matplotlib actually does—the generation of the plots for the purpose of display, manipulation, and publication. Most work in the artist layer is performed by a number of classes, most of which are derived from the Artist base class.

The artist layer is concerned with things such as the lines, shapes, axes, text, and so on. These are the subclasses of the Artist class that define things such as the following:

  • A canvas-artist coordinate transformation
  • Visibility
  • A clip box that defines the paintable area
  • Labels
  • A callback registry instance to handle user interaction events

The Artist subclasses can be classified into one of the following two groups:

  • Primitives
  • Containers

The following two sections provide more details about these groups.

Primitives

The matplotlib artist primitives are classes of graphical objects that are supposed to be painted on a figure's canvas. These include, but are not limited to, the following:

  • Line2D
  • Shape...

The scripting layer

While the backend layer focuses on providing a common interface to the toolkits and rendering the primitives and containers of the artist layer, the scripting layer is the user-facing interface that simplifies the task of working with other layers.

Programmers who integrate matplotlib with application servers will often find it more convenient to work directly with the backend and artist layers. However, for the scientists' daily use, data visualization, or exploratory interactions, pyplot—the scripting layer—is a better option. This is what we use in most of the IPython Notebooks in this book.

The pyplot interface is much less verbose; one can get insights into one's data in very few steps. Under the covers, pyplot uses module-level objects to track the state of the data so that the user does not have to create things like figures, axes, canvases, figure canvas managers, or preferred backends.

We will take a quick look at pyplot's internals...

The original design goals


As mentioned in Chapter 1, Getting Up to Speed, the creators of matplotlib were originally focused on building a GTK+ application for researchers and providing a command interface for the interactive plotting of data, not unlike that provided by MATLAB.

Both of these aims helped drive the development of improved abstractions for matplotlib. It was in this dual crucible that the top-level object of the rendered plots in matplotlib gained its rightful prominence—the Figure. These ideas led to various foundational objects in matplotlib, and the relationships between them ultimately provided the basis for the architecture of this library.

The current matplotlib architecture


The current matplotlib architecture revolves around the operations that are necessary for the users to create, render, and update the Figure objects. Figures can be displayed and interacted with via common user interface events such as the keyboard and mouse inputs. This layer of interaction with common user interface is called the backend layer. A Figure needs to be composed of multiple objects that should be individually modifiable, but it should be implemented in such a way that it has a positive and predictable impact on the other aspects of the Figure. This logical layer is responsible for the abstraction of each visual component that one sees in a Figure. Due to its highly visual nature, this layer was identified as the more general concept of creating visual art and is thus referred to as the artist layer. Lastly, the Figure needs to support programmatic interaction and provide the users with the ability to manipulate Figures with a syntax that...

The backend layer


Seasoned computer scientists, engineers, and software developers all know that one of the subtler and trickier problems that arise in our industry is naming. It sounds a bit silly and it is repeatedly the subject of jokes, but the difficulty remains—how do you speak or write explicitly on a subject whose very nature requires exquisite precision and yet has great ambiguity that arises in different contexts?

We have the same problem with the term backend. Here, as in so many other instances, the context is everything. Our context is matplotlib, a set of tools, and a framework where everything is done in support of the visualizing of data and their relationships. The term backend has to be viewed from this perspective to support the generation of plots. The matplotlib backend has nothing to do with other noteworthy backends such as databases, servers, messaging systems, or dispatchers of various sorts. The backend of matplotlib is an abstraction layer over various components...

The artist layer


The artist layer constitutes the bulk of what matplotlib actually does—the generation of the plots for the purpose of display, manipulation, and publication. Most work in the artist layer is performed by a number of classes, most of which are derived from the Artist base class.

The artist layer is concerned with things such as the lines, shapes, axes, text, and so on. These are the subclasses of the Artist class that define things such as the following:

  • A canvas-artist coordinate transformation

  • Visibility

  • A clip box that defines the paintable area

  • Labels

  • A callback registry instance to handle user interaction events

The Artist subclasses can be classified into one of the following two groups:

  • Primitives

  • Containers

The following two sections provide more details about these groups.

Primitives

The matplotlib artist primitives are classes of graphical objects that are supposed to be painted on a figure's canvas. These include, but are not limited to, the following:

  • Line2D

  • Shape (patch) classes...

The scripting layer


While the backend layer focuses on providing a common interface to the toolkits and rendering the primitives and containers of the artist layer, the scripting layer is the user-facing interface that simplifies the task of working with other layers.

Programmers who integrate matplotlib with application servers will often find it more convenient to work directly with the backend and artist layers. However, for the scientists' daily use, data visualization, or exploratory interactions, pyplot—the scripting layer—is a better option. This is what we use in most of the IPython Notebooks in this book.

The pyplot interface is much less verbose; one can get insights into one's data in very few steps. Under the covers, pyplot uses module-level objects to track the state of the data so that the user does not have to create things like figures, axes, canvases, figure canvas managers, or preferred backends.

We will take a quick look at pyplot's internals later in this chapter (as well...

Left arrow icon Right arrow icon

Description

If you are a scientist, programmer, software engineer, or student who has working knowledge of matplotlib and now want to extend your usage of matplotlib to plot complex graphs and charts and handle large datasets, then this book is for you.

Who is this book for?

If you are a scientist, programmer, software engineer, or student who has working knowledge of matplotlib and now want to extend your usage of matplotlib to plot complex graphs and charts and handle large datasets, then this book is for you.

What you will learn

  • Analyze the matplotlib code base and its internals
  • Rerender visualized data on the fly based on changes in the user interface
  • Take advantage of sophisticated thirdparty libraries to plot complex data relationships
  • Create custom styles for use in specialize publications, presentations, or online media
  • Generate consolidated master plots comprising many subplots for dashboardlike results
  • Deploy matplotlib in Cloud environments
  • Utilize matplotlib in big data projects

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 29, 2015
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987559
Category :
Languages :
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 : Jun 29, 2015
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987559
Category :
Languages :
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 95.97
Learning SciPy for Numerical and Scientific Computing Second Edition
€24.99
Mastering SciPy
€37.99
Mastering Matplotlib
€32.99
Total 95.97 Stars icon

Table of Contents

10 Chapters
1. Getting Up to Speed Chevron down icon Chevron up icon
2. The matplotlib Architecture Chevron down icon Chevron up icon
3. matplotlib APIs and Integrations Chevron down icon Chevron up icon
4. Event Handling and Interactive Plots Chevron down icon Chevron up icon
5. High-level Plotting and Data Analysis Chevron down icon Chevron up icon
6. Customization and Configuration Chevron down icon Chevron up icon
7. Deploying matplotlib in Cloud Environments Chevron down icon Chevron up icon
8. matplotlib and Big Data Chevron down icon Chevron up icon
9. Clustering for matplotlib Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(8 Ratings)
5 star 37.5%
4 star 12.5%
3 star 25%
2 star 12.5%
1 star 12.5%
Filter icon Filter
Top Reviews

Filter reviews by




Justin Marley Nov 24, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book with a lot of material including code, graphs and hardware/cloud discussion to take the reader to the next level.
Amazon Verified review Amazon
Loris Aug 11, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this book with the goal of improving my basic knowledge of matplotlib: while the creation of basic plots is straightforward, I found it difficult to modify the default behaviors of the library, and I faced problems in plotting large amount of data. I can safely say that this book helped me to solve both issues. As the author mentions in the book, a prior knowledge of matplotlib will definitely makes the reading more enjoiable.The book begins by giving an historical overview of matplotlib and by introducing two popular projects, seaborn and pandas. The chapters that follow describes the matplotlib internal architecture and its API. Next the author illustrates how events are handled in matplotlib and how to create interactive plots. The fifth chapter is dedicated to high-level plotting and shows how to create plots with third-party libraries, such as networkX, pandas, and seaborn, which wrap matplotlib functionality. The chapter also briefly introduces Bokeh, a library that offers a series of improvements over matplotlib and focus its attention on the web browser. In this chapter the author did a very good job in showing how a good visualization of the data is crucial in data analysis. The next chapter covers the customization (and the configuration) of matplotlib. Here the author shows how to create complex layouts where different plots are combined in the same figure. In the eight chapter the author explains how to plot huge amount of data by illustrating different strategies that range from using tools such as numpy's memmap function and pytables, to decimating data (removal of a fraction of the data). The last chapter shows how it is possible to improve the performance of matplotlib by using a clustered environment.Last but not least, the authors provided a GitHub repository with the example code and notebooks of each chapter of the book.
Amazon Verified review Amazon
Ro'eh Nävee May 12, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
'Mastering matplotlib' is a textbook for someone acquainted with using the Python library named 'matplotlib.' Also the IPython/Jupyter interpreter, since the 'nbagg' IPython Notebook backend to matplotlib will also be used. The 'nbagg' backend is for working with plots in a Web browser. Other Python libraries were SciPy, NumPy, Pandas and Seaborn.Most Jupyter notebooks in the tutorials start with:import matplotlibmatplotlib.use('nbagg')%matplotlib inlineimport matplotlib.pyplot as pltOne convenience to appreciate is how the author listed dependent libraries featured in the textbook, and even stored them in a text file included within the accompanying code, which can be downloaded for free from Packt Publishing. The generous author even states: "...you are welcome to...utilize the matplotlib library and the provided code in whatever way you see fit." Free practical, usable code. Once the free code has been downloaded, the github.com repo masteringmatplotlib/notebooks is optional. Mastering matplotlib
Amazon Verified review Amazon
G. A. Patino Aug 12, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is the definite book to learn the most advanced aspects of matplotlib. Even though the book covers installation and gives the fundamentals about basic plots, it is best suited for intermediate users in both Python and matplotlib. In fact, the authors are very class-oriented, making a fair familiarity with object-oriented programming something of a prerequisite. However, if you have those prerequisites the book is a worthy investment as you will be able to take full advantage of matplotlib.Even though the topics covered are advanced, from the matplotlib architecture to deploying it in Docker and implementing in parallel computing, they are presented in a clear and concise way. Yet the breadth of applications covered is quite comprehensive, and the authors are able to articulate all the different chapters so that the learning feels like a natural progression instead of trying to cram very disparate subjects. The code is elegant and relatively short, facilitating its reading; and the authors explanations for it are very easy to follow. In particular, the chapter of big data visualization definitely goes beyond what is presented in other books that also cover the same topic, and the implementation explanations are much better. The fact that the book is under 300 pages long is a huge plus. The only chapter I felt that wasn't as easy to follow is the one on GUI deployment.One aspect I really enjoyed about the book is the multiple explanations about the different approaches to creating figures with matplotlib. When you are learning Python and matplotlib you see some books that use pyplot, while others use pylab. Or some like the ax. synthax while others stick to the plt. one. This is the first book in which I see a presentation of all those possibilities, along with their advantages and disadvantages. By the same token, if you are confused as to when to use Seaborn vs yhat ggplot, what's the point of NetworkX, what is ModGrapher, etc. you will find all those explanations here, along with suggestions for their appropriate application.
Amazon Verified review Amazon
NRK Aug 14, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I was hoping for a systematic understanding of the package. Didn't get it.
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.