Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Matplotlib for Python Developers
Matplotlib for Python Developers

Matplotlib for Python Developers: Python developers who want to learn Matplotlib need look no further. This book covers it all with a practical approach including lots of code and images. Take this chance to learn 2D plotting through real-world examples.

eBook
€25.99 €28.99
Paperback
€37.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 for Python Developers

Chapter 2. Getting Started with Matplotlib

In the previous chapter, we have given a brief introduction to Matplotlib. We now want to start using it for real—after all, that's what you are reading this book for.

In this chapter, we will:

  • Explore the basic plotting capabilities of Matplotlib for single or multiple lines

  • Add information to the plots such as legends, axis labels, and titles

  • Save a plot to a file

  • Describe the interaction with IPython

  • Customize Matplotlib, both through configuration files and Python code

Let's start looking at some graphs.

First plots with Matplotlib

One of the strong points of Matplotlib is how quickly we can start producing plots out of the box. Here is our first example:

$ ipython
In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1, 3, 2, 4])
Out[2]: [<matplotlib.lines.Line2D object at 0x2544f10>]
In [3]: plt.show()

This code snippet gives the output shown in the following screenshot:

As you can see, we are using IPython. This will be the case throughout...

First plots with Matplotlib


One of the strong points of Matplotlib is how quickly we can start producing plots out of the box. Here is our first example:

$ ipython
In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1, 3, 2, 4])
Out[2]: [<matplotlib.lines.Line2D object at 0x2544f10>]
In [3]: plt.show()

This code snippet gives the output shown in the following screenshot:

As you can see, we are using IPython. This will be the case throughout the book, so we'll skip the command execution line (and the heading) as you can easily recognize IPython output.

Let's look at each line of the previous code in detail:

In [1]: import matplotlib.pyplot as plt

This is the preferred format to import the main Matplotlib submodule for plotting, pyplot. It's the best practice and in order to avoid pollution of the global namespace, it's strongly encouraged to never import like:

from <module> import *

The same import style is used in the official documentation, so we want to be consistent with...

Multiline plots


It's fun to plot a line, but it's even more fun when we can plot more than one line on the same figure. This is really easy with Matplotlib as we can simply plot all the lines that we want before calling show(). Have a look at the following code and screenshot:

In [1]: import matplotlib.pyplot as plt
In [2]: x = range(1, 5)
In [3]: plt.plot(x, [xi*1.5 for xi in x])
Out[3]: [<matplotlib.lines.Line2D object at 0x2076ed0>]
In [4]: plt.plot(x, [xi*3.0 for xi in x])
Out[4]: [<matplotlib.lines.Line2D object at 0x1e544d0>]
In [5]: plt.plot(x, [xi/3.0 for xi in x])
Out[5]: [<matplotlib.lines.Line2D object at 0x20864d0>]
In [6]: plt.show()

Note how Matplotlib automatically chooses different colors for each line—green for the first line, blue for the second line, and red for the third one (from top to bottom).

Can you tell why a float value was used in line [5]? Try it yourself with an integer one and you'll see. The answer is that if divided by 3 (that is, by using...

Grid, axes, and labels


Now we can learn about some features that we can add to plots, and some features to control them better.

Adding a grid

In the previous images, we saw that the background of the figure was completely blank. While it might be nice for some plots, there are situations where having a reference system would improve the comprehension of the plot—for example with multiline plots. We can add a grid to the plot by calling the grid() function; it takes one parameter, a Boolean value, to enable (if True ) or disable (if False) the grid:

In [1]: import matplotlib.pyplot as plt
In [2]: import numpy as np
In [3]: x = np.arange(1, 5)
In [4]: plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
Out[4]:
[<matplotlib.lines.Line2D object at 0x8fcc20c>,
<matplotlib.lines.Line2D object at 0x8fcc50c>,
<matplotlib.lines.Line2D object at 0x8fcc84c>]
In [5]: plt.grid(True)
In [6]: plt.show()

We can see the grid in the following screenshot, as a result of executing the preceding code:

Handling...

Titles and legends


We are about to introduce two other important plot features—titles and legends.

Adding a title

Just like in a book or a paper, the title of a graph describes what it is:

In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1, 3, 2, 4])
Out[2]: [<matplotlib.lines.Line2D object at 0xf54f10>]
In [3]: plt.title('Simple plot')
Out[3]: <matplotlib.text.Text object at 0xf4b850>
In [4]: plt.show()

Matplotlib provides a simple function, plt.title(), to add a title to an image, as shown in the previous code. The following screenshot displays the output of the previous example:

Adding a legend

The last thing we need to see to complete a basic plot is a legend.

Legends are used to explain what each line means in the current figure. Let's take the multiline plot example again, and extend it with a legend:

In [1]: import matplotlib.pyplot as plt
In [2]: import numpy as np
In [3]: x = np.arange(1, 5)
In [4]: plt.plot(x, x*1.5, label='Normal')
Out[4]: [<matplotlib.lines...

A complete example


Let's now group together all that we've seen so far and create a complete example as follows:

In [1]: import matplotlib.pyplot as plt
In [2]: import numpy as np
In [3]: x = np.arange(1, 5)
In [4]: plt.plot(x, x*1.5, label='Normal')
Out[4]: [<matplotlib.lines.Line2D object at 0x2ab5f50>]
In [5]: plt.plot(x, x*3.0, label='Fast')
Out[5]: [<matplotlib.lines.Line2D object at 0x2ac5210>]
In [6]: plt.plot(x, x/3.0, label='Slow')
Out[6]: [<matplotlib.lines.Line2D object at 0x2ac5650>]
In [7]: plt.grid(True)
In [8]: plt.title('Sample Growth of a Measure')
Out[8]: <matplotlib.text.Text object at 0x2aa8890>
In [9]: plt.xlabel('Samples')
Out[9]: <matplotlib.text.Text object at 0x2aa6150>
In [10]: plt.ylabel('Values Measured')
Out[10]: <matplotlib.text.Text object at 0x2aa6d10>
In [11]: plt.legend(loc='upper left')
Out[11]: <matplotlib.legend.Legend object at 0x2ac5c50>
In [12]: plt.show()

A very nice looking plot can be obtained with just...

Saving plots to a file


Saving a plot to a file is an easy task. The following example shows how:

In [1]: import matplotlib.pyplot as plt
In [2]: plt.plot([1, 2, 3])
Out[2]: [<matplotlib.lines.Line2D object at 0x22a2f10>]
In [3]: plt.savefig('plot123.png')

Just a call to savefig() with the filename as the parameter, and we can find the saved plot in the current directory.

$ file plot123.png
plot123.png: PNG image, 800 x 600, 8-bit/color RGBA, non-interlaced

The file format is based on the filename extension (so in the previous example, we saved a PNG image).

Two values govern the resulting image size in pixels—the figure size and the DPI.

Here, we can see the default values for Matplotlib:

In [1]: import matplotlib as mpl
In [2]: mpl.rcParams['figure.figsize']
Out[2]: [8.0, 6.0]
In [3]: mpl.rcParams['savefig.dpi']
Out[3]: 100

So, an 8x6 inches figure with 100 DPI results in an 800x600 pixels image (as seen in the previous example).

When an image is displayed on the screen, the length units...

Interactive navigation toolbar


If you have tried some of the book examples proposed so far, then you may have already noticed the interactive navigation toolbar (because when using matplotlib.pyplot, the toolbar is enabled by default for every figure), but in any case, here is a screenshot of the window:

This window pops up with the following code, when executed in IPython:

In [1]: import matplotlib as mpl
In [2]: mpl.use('GTKAgg') # to use GTK UI
In [3]: import matplotlib.pyplot as plt
In [4]: plt.plot([1, 3, 2, 4])
Out[4]: [<matplotlib.lines.Line2D object at 0x909b04c>]
In [5]: plt.show()

It's worth taking the time to learn more about this window, since it provides basic elaboration and manipulation functions for interactive plotting.

First of all, note how passing the mouse over the figure area results in the mouse pointer's coordinates being shown in the bottom-right corner of the window.

At the bottom of the window, we can find the navigation toolbar. A description of each of its...

IPython support


We have already used IPython throughout the chapter, and we saw how useful it is. Therefore, we want to give it a better introduction.

Matplotlib tends to defer drawing till the end, since it's an expensive operation, and updating the plot at every property change would slow down the execution.

That's fine for batch operations, but when we're working with the Python shell, we want to see updates at every command we type. Easy to say, but difficult to implement.

Most GUI libraries need to control the main loop of execution of Python, thus preventing any further interaction (that is, you can't type while viewing the image). The only GUI that plays nice with Python's standard shell is Tkinter.

Note

Tkinter is the standard Python interface to the Tk GUI library.

So you might want to set the backend property to TkAgg and interactive to True when using the Python interpreter interactively.

IPython uses a smart method to handle this situation—it spawns a thread to execute GUI library...

Configuring Matplotlib


In order to have the best experience with any program, we have to configure it to our own preferences; the same holds true for Matplotlib.

Matplotlib provides for massive configurability of plots, and there are several places to control the customization:

  • Global machine configuration file: This is used to configure Matplotlib for all the users of the machine.

  • User configuration file: A separate file for each user, where they can choose their own settings, overwriting the global configuration file (note that it will be used by that used any time the given user execute a Matplotlib-related code).

  • Configuration file in the current directory: Used for specific customization to the current script or program. This is particularly useful in situations when different programs have different needs, and using an external configuration file is better than hardcoding those settings in the code.

  • Python code in the current script or program or interactive session: To fine...

Summary


If you've arrived here, now you know:

  • How to create single or multiline plots handling the axes limits

  • How to add information to the plot such as legends, labels, and titles

  • How to save plots to a file for reuse

  • How to use the toolbar that the interactive window provides

  • Why IPython is so useful in collaboration with Matplotlib

  • How to customize Matplotlib to your needs (both from configuration files and from Python code)

But we have only scratched the surface of what Matplotlib can do. We'll see much more in the next chapter!

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create high quality 2D plots by using Matplotlib productively
  • Incremental introduction to Matplotlib, from the ground up to advanced levels
  • Embed Matplotlib in GTK+, Qt, and wxWidgets applications as well as web sites to utilize them in Python applications
  • Deploy Matplotlib in web applications and expose it on the Web using popular web frameworks such as Pylons and Django
  • Get to grips with hands-on code and complete realistic case study examples along with highly informative plot screenshots

Description

Providing appealing plots and graphs is an essential part of various fields such as scientific research, data analysis, and so on. Matplotlib, the Python 2D plotting library, is used to produce publication-quality figures in a variety of hardcopy formats and interactive environments across platforms. This book explains creating various plots, histograms, power spectra, bar charts, error charts, scatter-plots and much more using the powerful Matplotlib library to get impressive out-of-the-box results. This book gives you a comprehensive tour of the key features of the Matplotlib Python 2D plotting library, right from the simplest concepts to the most advanced topics. You will discover how easy it is to produce professional-quality plots when you have this book to hand. The book introduces the library in steps. First come the basics: introducing what the library is, its important prerequisites (and terminology), installing and configuring Matplotlib, and going through simple plots such as lines, grids, axes, and charts. Then we start with some introductory examples, and move ahead by discussing the various programming styles that Matplotlib allows, and several key features. Further, the book presents an important section on embedding applications. You will be introduced to three of the best known GUI libraries 'GTK+, Qt, and wxWidgets' and presented with the steps to implement to include Matplotlib in an application written using each of them. You will learn through an incremental approach: from a simple example that presents the peculiarities of the GUI library, to more complex ones, using GUI designer tools. Because the Web permeates all of our activities, a part of the book is dedicated to showing how Matplotlib can be used in a web environment, and another section focuses on using Matplotlib with common Python web frameworks, namely, Pylons and Django. Last, but not least, you will go through real-world examples, where you will see some real situations in which you can use Matplotlib.

Who is this book for?

This book is essentially for Python developers who have a good knowledge of Python; no knowledge of Matplotlib is required. You will be creating 2D plots using Matplotlib in no time at all.

What you will learn

  • Exploit the interactive computing environment of IPython to its fullest in collaboration with Matplotlib
  • Learn line and point styles and master their customization, customization of axis ticks, and develop several plot types available in Matplotlib, such as histograms, bars, pie charts, polar charts, and so on
  • Explore Object Oriented Matplotlib and learn how to add subplots, multiple figures, additional and shared axes, logarithmic scaled axes, data plotting with tick formatting and locators, text properties, fonts, LaTeX typewriting, and contour plots
  • Get comfortable with Gladeóa RAD toolóto quickly design a GUI for GTK+ and embed Matplotlib into it
  • Make the most of Matplotlib within the wxWidgets framework, in particular using the wxPython bindings and design a GUI with wxGlade
  • Use the Qt Designer to draw a simple GUI and refer it to your Python code to fit your needs
  • Expose Matplotlib on the Web using CGI (through Apache mod_cgi), mod_python, Django, and Pylons in no time at all
  • Profit from the real-world examples by simply following the streamóidentify the data source, elaborate the data and generate the resulting plot

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 09, 2009
Length: 308 pages
Edition : 1st
Language : English
ISBN-13 : 9781847197917
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 09, 2009
Length: 308 pages
Edition : 1st
Language : English
ISBN-13 : 9781847197917
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 100.97
Interactive Applications using Matplotlib
€24.99
Matplotlib for Python Developers
€37.99
matplotlib Plotting Cookbook
€37.99
Total 100.97 Stars icon

Table of Contents

9 Chapters
Introduction to Matplotlib Chevron down icon Chevron up icon
Getting Started with Matplotlib Chevron down icon Chevron up icon
Decorate Graphs with Plot Styles and Types Chevron down icon Chevron up icon
Advanced Matplotlib Chevron down icon Chevron up icon
Embedding Matplotlib in GTK+ Chevron down icon Chevron up icon
Embedding Matplotlib in Qt 4 Chevron down icon Chevron up icon
Embedding Matplotlib in wxWidgets Chevron down icon Chevron up icon
Matplotlib for the Web Chevron down icon Chevron up icon
Matplotlib in the Real World 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.2
(23 Ratings)
5 star 21.7%
4 star 26.1%
3 star 17.4%
2 star 21.7%
1 star 13%
Filter icon Filter
Top Reviews

Filter reviews by




John W. Shipman Mar 20, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've been teaching Python classes here at New Mexico Tech for15 years. Until now, all I could do in the Matplotlib unit isthrow some small examples at the students and then point themat the 800 pages of reference documentation and say "Here isdocumentation for the 10,000 tiny pieces of Matplotlib. Goodluck figuring out how to assemble them."Tosi's book is exactly what Matplotlib has needed for so long: aproper tutorial. He starts with the absolute basics: plot Yagainst X; add a title; add axis labels; plot two functions ofthe same variable; and so on, a progression that eases the newuser first into the features that most people will use.The writing is clear, and the examples constructed and explainedwell, with a nice balance of theory and practice.In particular I appreciate the shift in chapter 4 to a morePythonic, object-oriented approach. The author places Pylab inits proper context (great for playing around) but I agree thatfor serious production applications and modular design the objectapproach is the way to go.The only extremely minor quibbles I have are with the editing.None of the editorial crew seem to be native English speakers.Take for example the highly useful diagram on page 59, "Plottypes". This diagram helps you figure out what kind of plotfills your needs. However, the title is "Chart Suggestions -- ATought-Starter [sic]"; that should be "Thought-Starter". On thesame diagram, there are two references to "Tree Variables" thatprobably should be "Three variables".However, don't let that put you off. This is just the right bookfor people starting out. I found very few typos, and none ofthem reduced the book's usefulness.
Amazon Verified review Amazon
Haokoze Jan 09, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
シリアル通信を利用して、PICマイコンやArduinoからデータを読み取り、記録・表示するデータロガーを作ろうと奮闘してました。この本の後半はPyQt、Tkinter、WxPythonのGUIにMatplotlibのFigureを貼り付ける方法が具体的に書いてあり、とても参考になりました。この本だけで、Matplotlibの機能をすべて使いこなせる様になるわけではないでしょうが、私の場合はとても参考になったので星5にしました。英語ですが、中学生レベルの私でも読めます。オシロみたいなリアルタイムグラフ描画もQt上でできて、ちょっと自画自賛してます。
Amazon Verified review Amazon
Bode Omoboya Jan 10, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really enjoyed this and it was very helpful!I will recommend to any upcoming Python developer, especially for students in research development!
Amazon Verified review Amazon
christopher j. parrish Sep 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very helpful for my project
Amazon Verified review Amazon
david t. Pitts Jan 29, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am into this language because of the 3D plotting abilities. I think that this will allow me to do some fantastic figures.
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.

Modal Close icon
Modal Close icon