Book Image

Interactive Applications using Matplotlib

Book Image

Interactive Applications using Matplotlib

Overview of this book

Table of Contents (12 chapters)

Preface

Why Matplotlib? Why Python, for that matter? I picked up Python for scientific development because I needed a full-fledged programming language that made sense. Too often, I felt hemmed in by the traditional tools in the meteorology field. I needed a language that respected my time as a developer and didn't fight me every step of the way. "Don't you find Python constricting?" asked a colleague who was fond of bad puns. "No, quite the opposite," I replied, the joke going right over my head.

Matplotlib is the same in this respect. Switching from traditional graphing tools of the meteorology field to Matplotlib was a breath of fresh air. Not only were useful programs being written using the Matplotlib library, but it was also easy to write my own. Furthermore, I could write out modules and easily use them in both the hardcopy generating scripts for my publications and for my data exploration interactive applications. Most importantly, the Matplotlib library let me do what I needed it to do.

I have been an active developer for Matplotlib since 2010 and I am still discovering Matplotlib. It isn't that the library is insanely huge and unwieldy—it isn't. Instead, Matplotlib appeals to all levels of expertise and interests. One can simply care enough only to get a single plot displayed in three line of code and never think of the library again. Or, one could assume control over every single minute plotting detail, ensuring that everything is displayed "just right." And even when one does this and thinks they have seen every single nook and cranny of the library, they will discover some other feature that they have never seen before.

Matplotlib is 12 years old now. New plotting projects have cropped up—some supplementing Matplotlib's design, while others trying to replace Matplotlib entirely. However, there has been no slacking of interest in Matplotlib, not from the users and definitely not from the developers. The new projects are interesting, and as with all things open source, we try to learn from these projects. But I keep coming back to this project. Its design, developers, and community of users are some of the best and most devoted in the open source world.

The book you are reading right now is actually not the book I originally wanted to write. The interactive aspect of Matplotlib is not my area of expertise. After some nudging from fellow developers and users, I relented. I proceeded to rewrite the only interactive application I had ever finished and published. Working through the chapters, I tried to find better ways of doing the things I did originally, pointing out major pitfalls and easy mistakes as I encountered them. It was a significant learning experience for me, which was wholly unexpected.

I now invite you to discover Matplotlib for yourself. Whether it is the first time or not, it certainly won't be the last.

What this book covers

Chapter 1, Introducing Interactive Plotting, covers basic figure-axes-artist hierarchy and other Matplotlib essentials such as displaying the plot. It also introduces you to the interactive Matplotlib figure.

Chapter 2, Using Events and Callbacks, provides Matplotlib's events and a callback system to bring your figures to life. It also explains how you can extend it with custom events, making the application truly interactive.

Chapter 3, Animations, deals with ArtistAnimation, FuncAnimation, and timers to make animations of all types. It also deals with animations that can be saved as movies.

Chapter 4, Widgets, covers built-in widgets such as buttons, checkboxes, selectors, lassos, and sliders, which are all explained and demonstrated. Here, you'll also learn about other useful third-party widgets and tools.

Chapter 5, Embedding Matplotlib, teaches you how to add GUI elements to an existing Matplotlib application. Here you'll also see how to add your interactive Matplotlib figure to an existing GUI application. Identical examples are presented using GTK, Tkinter, wxWidgets, and Qt.

What you need for this book

At the absolute least, you will need the following Python packages installed on your system: NumPy, SciPy, Basemap, and (of course) Matplotlib. To work on the instructions presented in Chapter 5, Embedding Matplotlib, you will want to have at least one of the following GUI toolkits installed: GTK, Tkinter (should come with Python), wxWidgets, or Qt (version 4 is preferred; version 5 is supported only recently for Matplotlib version 1.4). You will also need the corresponding Python bindings for the GUI toolkits (some come with them by default).

Who this book is for

If you are a Python programmer who wants to do more than just see your data, this is the book for you. It will explain the SciPy stack (that is, NumPy and Matplotlib) and provide pointers to install them. Experience with GUI toolkits, such as wxPython, Qt, or GTK+, is also not required, so this book can be an excellent complement to other GUI programming resources. To understand the examples and explanations, you need to know basic object-oriented programming terms and concepts.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from tutorial import track_loader
tracks = track_loader('polygons.shp')
# Filter out non-tracks (unassociated polygons given trackID of -9)
tracks = {tid: t for tid, t in tracks.items() if tid != -9}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    polys = [p for p in cells.polygons] 
    for p in polys: 
        p.set_visible(True) 
        p.set_alpha(0.0) 

    def update(frame, polys): 
        for i, p in enumerate(polys): 
            alpha = 0.0 if i > frame else 1.0 / ((frame - i + 1)**2) 
            p.set_alpha(alpha) 

    ax.set_xlabel("Longitude")
    ax.set_ylabel("Latitude")
    strmanim = FuncAnimation(fig, update, frameCnt, 
                             fargs=(polys,)) 
    plt.show()

Any command-line input or output is written as follows:

$ pip install matplotlib

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Now click on the Selection radio button and you will find that you can select a polygon again."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.