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
Free Trial
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (8 Ratings)
Paperback Jun 2015 292 pages 1st Edition
eBook
Can$30.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial
Arrow left icon
Profile Icon Duncan M McGreggor Profile Icon Duncan M. McGreggor
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (8 Ratings)
Paperback Jun 2015 292 pages 1st Edition
eBook
Can$30.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial
eBook
Can$30.99 Can$44.99
Paperback
Can$55.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783987542
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 29, 2015
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781783987542
Category :
Languages :
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 Can$6 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 Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 161.97
Learning SciPy for Numerical and Scientific Computing Second Edition
Can$41.99
Mastering SciPy
Can$63.99
Mastering Matplotlib
Can$55.99
Total Can$ 161.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.