Get Interactive Applications Using Matplotlib 1st Edition Root PDF ebook with Full Chapters Now
Get Interactive Applications Using Matplotlib 1st Edition Root PDF ebook with Full Chapters Now
com
https://ebookname.com/product/interactive-applications-
using-matplotlib-1st-edition-root/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/root-to-stalk-cooking-the-art-of-using-
the-whole-vegetable-1st-edition-tara-duggan/
ebookname.com
https://ebookname.com/product/interactive-computer-graphics-a-top-
down-approach-using-opengl-5th-ed-international-ed-edition-angel/
ebookname.com
https://ebookname.com/product/essential-mathematics-for-games-and-
interactive-applications-3rd-edition-james-m-van-verth-2/
ebookname.com
https://ebookname.com/product/simplifying-perspective-a-step-by-step-
guide-for-visual-artists-1st-edition-robert-pastrana/
ebookname.com
Wiley CPAexcel Exam Review 2014 Study Guide Financial
Accounting and Reporting 11th Edition O. Ray Whittington
https://ebookname.com/product/wiley-cpaexcel-exam-review-2014-study-
guide-financial-accounting-and-reporting-11th-edition-o-ray-
whittington/
ebookname.com
https://ebookname.com/product/idiot-s-guides-yoga-sarah-herrington/
ebookname.com
https://ebookname.com/product/an-emotionally-focused-guide-to-
relationship-loss-life-after-love-1-edition-clare-rosoman/
ebookname.com
https://ebookname.com/product/bringing-light-to-twilight-perspectives-
on-a-pop-culture-phenomenon-1st-edition-giselle-liza-anatol-eds/
ebookname.com
https://ebookname.com/product/compartment-syndromes-diagnosis-
treatment-and-complications-1st-edition-jorma-styf/
ebookname.com
Complicated Cases in GI Feb 15 2009 _ 1556428111 _ Slack
Incorporated First Edition Kalloo Md
https://ebookname.com/product/complicated-cases-in-gi-
feb-15-2009-_-1556428111-_-slack-incorporated-first-edition-kalloo-md/
ebookname.com
[1]
Interactive Applications Using
Matplotlib
Benjamin V. Root
BIRMINGHAM - MUMBAI
Interactive Applications Using Matplotlib
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.
ISBN 978-1-78398-884-6
www.packtpub.com
Credits
Reviewers Proofreaders
Kamran Husain Maria Gould
Nathan Jarus Lesley Harrison
Jens Hedegaard Nielsen Bernadette Watkins
Sergi Pons Freixes
Indexer
Acquisition Editors Monica Ajmera Mehta
Richard Gall
Owen Roberts Production Coordinator
Conidon Miranda
Content Development Editor
Shubhangi Dhamgaye
Cover Work
Conidon Miranda
Technical Editors
Tanvi Bhatt
Nanda Padmanabhan
Copy Editors
Roshni Banerjee
Gladson Monteiro
About the Author
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.
About the Reviewers
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.
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.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
[i]
Table of Contents
Data editing 41
User events 48
Editor events 49
Summary 54
Chapter 3: Animations 55
A short history 55
The fastest draw in the west 56
The animation module 57
Advanced animations 60
Event source 64
Timers 66
Blitting 68
Recipes 69
Tails 69
Fades 72
Saving animations 74
Notes about codecs and file formats 75
Simultaneous animations 77
How animations are saved 78
Session recorder 79
Summary 83
Chapter 4: Widgets 85
Built-in widgets 85
Slider 86
Button 89
Check buttons 92
Radio button 95
Lasso 99
LassoSelector 103
RectangleSelector 104
SpanSelector 108
Cursor 110
format_coord() 110
Third-party tools 113
mpldatacursor 114
Glue 114
Plot.ly, ggplot, prettyplotlib, and Seaborn 114
Summary 115
[ ii ]
Table of Contents
[ iii ]
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.
[v]
Preface
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 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 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.
[ vi ]
Preface
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."
[ vii ]
Preface
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)
ax.set_xlabel("Longitude")
ax.set_ylabel("Latitude")
strmanim = FuncAnimation(fig, update, frameCnt,
fargs=(polys,))
plt.show()
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."
[ viii ]
Preface
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.
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.
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.
[ ix ]
Preface
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.
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
[email protected], and we will do our best to address the problem.
[x]
Introducing Interactive
Plotting
A picture is worth a thousand words
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.
Installing Matplotlib
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:
$ pip install matplotlib
Introducing Interactive Plotting
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.
[2]
Chapter 1
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:
>>> show()
Interactive navigation
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:
• Home, Back, and Forward: These are similar to that of a web browser.
These buttons help you navigate through the previous views of your plot.
The "Home" button will take you back to the first view when the figure was
opened. "Back" will take you to the previous view, while "Forward" will
return you to the previous views.
[3]
Introducing Interactive Plotting
• Pan (and zoom): This button has two modes: pan and zoom. Press the left
mouse button and hold it to pan the figure. If you press x or y while panning,
the motion will be constrained to just the x or y axis, respectively. Press the
right mouse button to zoom. The plot will be zoomed in or out proportionate
to the right/left and up/down movements. Use the X, Y, or Ctrl key to
constrain the zoom to the x axis or the y axis or preserve the aspect ratio,
respectively.
• Zoom-to-rectangle: Press the left mouse button and drag the cursor to a new
location and release. The axes view limits will be zoomed to the rectangle
you just drew. Zoom out using your right mouse button, placing the current
view into the region defined by the rectangle you just drew.
• Subplot configuration: This button brings up a tool to modify plot spacing.
• Save: This button brings up a dialog that allows you to save the current
figure.
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.
Interactive plotting
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.
[4]
Chapter 1
Scripted plotting
Python is known for more than just its interactive interpreters; it is also a fully fledged
programming language that allows its users to easily create programs. Having a
script to display plots from daily reports can greatly improve your productivity.
Alternatively, you perhaps need a tool that can produce some simple plots of the data
from whatever mystery data file you have come across on the network share. Here is
a simple example of how to use Matplotlib's pyplot API and the argparse Python
standard library tool to create a simple CSV plotting script called plotfile.py.
Code: chp1/plotfile.py
#!/usr/bin/env python
if __name__ == '__main__':
parser = ArgumentParser(description="Plot a CSV file")
parser.add_argument("datafile", help="The CSV File")
# Require at least one column name
parser.add_argument("columns", nargs='+',
help="Names of columns to plot")
parser.add_argument("--save", help="Save the plot as...")
parser.add_argument("--no-show", action="store_true",
help="Don't show the plot")
args = parser.parse_args()
plt.plotfile(args.datafile, args.columns)
if args.save:
plt.savefig(args.save)
if not args.no_show:
plt.show()
Note the two optional command-line arguments: --save and --no-show. With the
--save option, the user can have the plot automatically saved (the graphics format is
determined automatically from the filename extension). Also, the user can choose not
to display the plot, which when coupled with the --save option might be desirable if
the user is trying to plot several CSV files.
When calling this script to show a plot, the execution of the script will stop at the
call to plt.show(). If the interactive plotting mode was on, then the execution of
the script would continue past show(), terminating the script, thus automatically
closing out any figures before the user has had a chance to view them. This is why
the interactive plotting mode is turned off by default in Matplotlib.
[5]
Introducing Interactive Plotting
Also note that the call to plt.savefig() is before the call to plt.show(). As
mentioned before, when the figure window is closed, the plot is lost. You cannot
save a plot after it has been closed.
Getting help
We have covered how to install Matplotlib and went over how to make very simple
plots from a Python session or a Python script. Most likely, this went very smoothly
for you. The rest of this book will focus on how to use Matplotlib to make an
interactive application, rather than the many ways to display data. You may be very
curious and want to learn more about the many kinds of plots this library has to
offer, or maybe you want to learn how to make new kinds of plots.
Gallery
Many users of Matplotlib are often faced with the question, "I want to make a plot
that has this data along with that data in the same figure, but it needs to look like
this other plot I have seen." Text-based searches on graphing concepts are difficult,
especially if you are unfamiliar with the terminology. The gallery showcases the
variety of ways in which one can make plots, all using the Matplotlib library. Browse
through the gallery, click on any figure that has pieces of what you want in your
plot, and see the code that generated it. Soon enough, you will be like a chef, mixing
and matching components to produce that perfect graph.
[6]
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of The Ohio
Naturalist, Vol. 1, No. 5, March, 1901
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Language: English
PUBLISHED BY
EDITORIAL STAFF
Associate Editors:
Advisory Board:
COLUMBUS, OHIO
Perennial Tumbleweeds 67
John H. Schaffner
PUBLISHED BY
John H. Schaffner.
Annual tumbleweeds,
Tumble-grasses,
Perennial tumbleweeds.
E. E. Masterman.
In 1898, I planted 1000 burs; 917 grew two plants to the bur.
In 1899, I planted 1000 burs; 921 grew two plants to the bur.
In 1900, I planted 1000 burs; 913 grew two plants to the bur.
Total three years, 3000 burs; 2751 grew two plants to the bur.
Of the remaining 249 burs some grew one plant, some none;
some had one, some had two apparently sound seeds. I regret that no
further notice was taken of these seeds. The only object was to
determine whether the two seeds could be made to grow at the same
time. An account of the work was sent to Professor Selby, asking
whether further experiment was necessary; he replied that he
thought not.
Perhaps it should be added that I selected only apparently sound
burs; soil was taken from a field near a creek where cockleburs grow
abundantly. It was passed through a ¼ inch-mesh wire sieve, and
carefully searched over with the aid of a glass. This soil was taken to
a distant part of the farm; in it the seeds were planted and nature did
the rest.
I also made observations as follows: I searched among
specimens growing for a mile along a creek, for two plants growing
together and not nearer than five inches to any other plant. Of the
1500 specimens examined each year for three years, two plants
always grew from one bur.
Why have I obtained such opposite results as compared with
Professor Arthur’s? Can it be referred to locality, soil, or some other
more favorable conditions?
The substance of the above was presented, December 27, 1900,
to the Ohio Academy of Science and it provoked a discussion in
which Professors Kellerman, Schaffner, Mosely and others
participated. Dr. Kellerman thought that the results of Arthur’s
experiments were perhaps more nearly in accord with what usually
takes place in nature. He pointed out the mistake of quoting or
saying that Arthur has shown “that only one of the seeds can be
caused to germinate the first year.” Turning to the printed report of
the experiments in question (Proc. 16th, An. Meeting Soc. Prom. Agr.
Sci., 1895), I find that, based on many experiments made previous to
1895, he gives the result in round numbers as follows: “Out of every
hundred ordinarily well formed cockleburs, seventy will produce one
seedling each, and five two seedlings each the first year after
maturity; the remaining twenty-five will for various reasons fail to
grow. Thirty of the hundred will produce seedlings the second year
after maturity, five will produce seedlings the third year after
maturity, and two or three seedlings will be produced in subsequent
years.”
Later experiments by Dr. Arthur seemed to show a lower
percentage of cases of the sprouting of both seeds to the bur in one
season. In the summary he states: “The germination of both seeds of
a bur of Xanthium in one season is exceptional.”
In view of the above and in accordance with the suggestions of
others I purpose continuing my experiments relative to this subject.
The following interesting statement is made by Dr. Arthur, in
the report cited, touching the cause of the difference in the action of
the two seeds; he says it “appears to be constitutional; a hereditary
character residing in the protoplasm of the embryo.”
New London, Ohio.
PLANT REMAINS FROM THE BAUM
VILLAGE SITE.
W. C. Mills.
Dr. V. Sterki.
In June of last year I took some Opuntia plants home, and also
some top joints heavily set with large buds. The former were planted
in the garden, the latter set in an Oleander tub. When, after a month,
none of the flower buds had opened, it was thought that they were
too many, as the joints bearing them were without roots, and most of
them were cut off and left lying on the ground, where a part of them
later on became partly or entirely covered with soil. In September, I
was surprised to find them all green and fresh; most of them had
rooted, and a few even sprouted, sending up shoots from half an inch
to over an inch high, being perfect little joints. At the present writing
(Jan. a. c.) all are alive, and, no doubt, will grow out to plants next
summer. They will be watched closely and further report be given.
It might be added that the Opuntia calyx-tube, which is later the
fruit, has “eyes,” that is buds, of the same character as the ordinary
buds of the plant, with clusters of bristles; and out of these the young
shoots grew, when the bud took root.
Evidently these buds retain more of the nature of the mother
plant than is common in flowers. It is unknown to me whether
similar observations have been made before. But it would be of
interest to make experiments with different plants. Would the
receptacles root and sprout if detached after flowering and
fertilization have taken place? Would the buds sprout when left in
situ on the mother plant, after the flowering parts had been removed,
the receptacle only left in place? Will the buds of other genera of
Cacteae, and other similar succulent plants behave in the same way,
under favorable conditions?
So-called viviparous plants are, as is well known, rather
common, e. g. among Gramineae, Cyperaceae, Polygoneae. But there
the actual flower parts develop into leaves, from which they had
originally been derived, and while yet remaining on the parent plant.
New Philadelphia, Ohio.
NOTE ON THE INVOLUCRAL LEAVES OF
SYNDESMON.
F. H. Burglehaus.
W. A. Kellerman.
W. A. Kellerman.