23,99 €
This book is intended for Python programmers who want to do more than just see their data. Experience with GUI toolkits is not required, so this book can be an excellent complement to other GUI programming resources.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 221
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2015
Production reference: 1170315
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-884-6
www.packtpub.com
Author
Benjamin V. Root
Reviewers
Kamran Husain
Nathan Jarus
Jens Hedegaard Nielsen
Sergi Pons Freixes
Acquisition Editors
Richard Gall
Owen Roberts
Content Development Editor
Shubhangi Dhamgaye
Technical Editors
Tanvi Bhatt
Nanda Padmanabhan
Copy Editors
Roshni Banerjee
Gladson Monteiro
Project Coordinator
Harshal Ved
Proofreaders
Maria Gould
Lesley Harrison
Bernadette Watkins
Indexer
Monica Ajmera Mehta
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
Benjamin V. Root has been a member of the Matplotlib development team since 2010. His main areas of development have been the documentation and the mplot3d toolkit, but now he focuses on code reviews and debugging. Ben is also an active member of mailing lists, using his expertise to help newcomers understand Matplotlib. He is a meteorology graduate student, working part-time on his PhD dissertation. He works full-time for Atmospheric and Environmental Research, Inc. as a scientific programmer.
I would like to acknowledge the entire Matplotlib development team for their insightful responses to my questions while I was writing this book. In particular, I would like to thank Michael Droettboom, Eric Firing, Thomas Caswell, Phil Elson, and Ryan May. Thanks also go to the members of the matplotlib users' list without whom I would have never learned this tool in the first place and for whom I wrote this book.
This book would not have been possible without the love and support of my wife, Margaret. She put up with far more than she should have, and for that, I am in her debt.
Last, but not least, I must acknowledge John Hunter, the creator of Matplotlib and the man who included me into the development team. Working with him and the rest of the team allowed me to mature as a programmer and scientist, and directly resulted in me attaining my current employment, thus starting my career.
Nathan Jarus is a computer science PhD candidate at Missouri S&T. He regularly uses Matplotlib to visualize and experiment with results. Prior to his graduate studies, he spent several years developing data visualization tools for research professors. Beyond visualization, he studies complex system modeling and control.
Jens Hedegaard Nielsen is a research software developer at University College London, where he works on a number of different programming projects in relation to research across the university. He is an active Matplotlib developer. He has a PhD in experimental laser physics from Aarhus University, Denmark.
Sergi Pons Freixes is a telecommunications engineer and a PhD candidate with experience on optical sensors and data analysis. For almost 10 years, he has been working in international environments, performing both hands-on development and research.
During his master's degree in telecommunications engineering, he engaged in part-time research in the Department of Signal Theory and Communications at the Polytechnic University of Catalonia (UPC), with the design and development of a low-cost hyperspectral in-situ sensor. This experience stimulated him to start a PhD at the same department. He obtained a grant from the Spanish National Research Council (CSIC) and performed his predoctoral training at the Marine Technology Unit in Barcelona, graduating for a master of advanced studies and leading and supervising the master thesis of other university students, while continuing his research on low-cost solutions oriented to increase the observational capabilities for marine/oceanographic biological information systems.
In 2011, he gained a fellowship from the Spanish Ministry of Economy and Competitiveness to expand his experience in international scientific organisms, moving to the European Space Agency office in Italy and working on assessing the viability of remote sensing coral monitoring. During his stay, he gained a contractor position as performance simulation engineer for the Sentinel 3 satellite project at the European Space Agency facilities in the Netherlands, being responsible for the simulators and processors operation and maintenance.
In January 2015, he moved to San Diego, California, where he is currently finishing his PhD while he pursues new opportunities.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
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.
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.
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).
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.
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 <[email protected]>, 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.
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.
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.
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 ErrataSubmissionForm 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 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 <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
A picture is worth a thousand words
The goal of any interactive application is to provide as much information as possible while minimizing complexity. If it can't provide the information the users need, then it is useless to them. However, if the application is too complex, then the information's signal gets lost in the noise of the complexity. A graphical presentation often strikes the right balance.
The Matplotlib library can help you present your data as graphs in your application. Anybody can make a simple interactive application without knowing anything about draw buffers, event loops, or even what a GUI toolkit is. And yet, the Matplotlib library will cede as much control as desired to allow even the most savvy GUI developer to create a masterful application from scratch. Like much of the Python language, Matplotlib's philosophy is to give the developer full control, but without being stupidly unhelpful and tedious.
There are many ways to install Matplotlib on your system. While the library used to have a reputation for being difficult to install on non-Linux systems, it has come a long way since then, along with the rest of the Python ecosystem. Refer to the following command:
Most likely, the preceding command would work just fine from the command line. Python Wheels (the next-generation Python package format that has replaced "eggs") for Matplotlib are now available from PyPi for Windows and Mac OS X systems. This method would also work for Linux users; however, it might be more favorable to install it via the system's built-in package manager.
While the core Matplotlib library can be installed with few dependencies, it is a part of a much larger scientific computing ecosystem known as SciPy. Displaying your data is often the easiest part of your application. Processing it is much more difficult, and the SciPy ecosystem most likely has the packages you need to do that. For basic numerical processing and N-dimensional data arrays, there is NumPy. For more advanced but general data processing tools, there is the SciPy package (the name was so catchy, it ended up being used to refer to many different things in the community). For more domain-specific needs, there are "Sci-Kits" such as scikit-learn for artificial intelligence, scikit-image for image processing, and statsmodels for statistical modeling. Another very useful library for data processing is pandas.
This was just a short summary of the packages available in the SciPy ecosystem. Manually managing all of their installations, updates, and dependencies would be difficult for many who just simply want to use the tools. Luckily, there are several distributions of the SciPy Stack available that can keep the menagerie under control. The following are Python distributions that include the SciPy Stack along with many other popular Python packages or make the packages easily available through package management software:
For this book, we will assume at least Python 2.7 or 3.2. The requisite packages are numpy, matplotlib, basemap, and scipy. Just about any version of these packages released in the past 3 years should work for most examples in this book (exceptions are noted in this book). The version 0.14.0 of SciPy (released in May 2014) cannot be used in this book due to a (now fixed) regression in its NetCDF reader. Chapter 5, Embedding Matplotlib will have special notes with regards to GUI toolkit packages.
With Matplotlib installed, you are now ready to make your first simple plot. Matplotlib has multiple layers. Pylab is the topmost layer, often used for quick one-off plotting from within a live Python session. Start up your favorite Python interpreter and type the following:
Nothing happened! This is because Matplotlib, by default, will not display anything until you explicitly tell it to do so. The Matplotlib library is often used for automated image generation from within Python scripts, with no need for any interactivity. Also, most users would not be done with their plotting yet and would find it distracting to have a plot come up automatically. When you are ready to see your plot, use the following command:
A figure window should now appear, and the Python interpreter is not available for any additional commands. By default, showing a figure will block the execution of your scripts and interpreter. However, this does not mean that the figure is not interactive. As you mouse over the plot, you will see the plot coordinates in the lower right-hand corner. The figure window will also have a toolbar:
From left to right, the following are the tools:
The figure window would also be responsive to the keyboard. The default keymap is fairly extensive (and will be covered fully later), but some of the basic hot keys are the Home key for resetting the plot view, the left and right keys for back and forward actions, p for pan/zoom mode, o for zoom-to-rectangle mode, and Ctrl + s to trigger a file save. When you are done viewing your figure, close the window as you would close any other application window, or use Ctrl + w.
When we did the previous example, no plots appeared until show() was called. Furthermore, no new commands could be entered into the Python interpreter until all the figures were closed. As you will soon learn, once a figure is closed, the plot it contains is lost, which means that you would have to repeat all the commands again in order to show() it again, perhaps with some modification or additional plot. Matplotlib ships with its interactive plotting mode off by default.
There are a couple of ways to turn the interactive plotting mode on. The main way is by calling the ion() function (for Interactive ON). Interactive plotting mode can be turned on at any time and turned off with ioff(). Once this mode is turned on, the next plotting command will automatically trigger an implicit show() command. Furthermore, you can continue typing commands into the Python interpreter. You can modify the current figure, create new figures, and close existing ones at any time, all from the current Python session.