Matplotlib for Python Developers Build remarkable publication quality plots the easy way Sandro Tosi BIRMINGHAM - MUMBAI This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 Matplotlib for Python Developers Copyright © 2009 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, Packt Publishing, nor its dealers or 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 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: November 2009 Production Reference: 2221009 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-847197-90-0 www.packtpub.com Cover Image by Raghuram Ashok ([email protected]) This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 Credits Author Editorial Team Leader Sandro Tosi Akshara Aware Reviewers Project Team Leader Michael Droettboom Priya Mukherji Reinier Heeres Project Coordinator Acquisition Editor Zainab Bagasrawala Usha Iyer Proofreader Development Editor Lesley Harrison Rakesh Shejwal Graphics Technical Editor Nilesh Mohite Namita Sahni Production Coordinator Copy Editor Adline Swetha Jesuthas Leonard D'Silva Cover Work Adline Swetha Jesuthas Indexers Monica Ajmera Hemangini Bari This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 About the Author Sandro Tosi was born in Firenze (Italy) in the early 80s, and graduated with a B.Sc. in Computer Science from the University of Firenze. His personal passions for Linux, Python (and programming), and computer technology are luckily a part of his daily job, where he has gained a lot of experience in systems and applications management, database administration, as well as project management and development. After having worked for five years as an EAI and an Application architect in an energy multinational, he's now working as a system administrator for an important European Internet company. I'd like to thank Laura, who has assisted and supported me while writing this book. This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 About the Reviewers Michael Droettboom holds a Master's Degree in Computer Music Research from The Johns Hopkins University. His research in optical music recognition lead to the development of the Gamera document image analysis framework, which has been used to recognize features in documents as diverse as medieval manuscript, Navajo texts, historical Scottish census data, and early American sheet music. His focus on computer graphics has lead to specializations in consumer electronics, computer-assisted engineering, and most recently, the science software for the Space Telescope Science Institute. He is currently one of the most active developers on the Matplotlib project. I wish to thank my son, Kai, for asking all the hard questions. Reinier Heeres has an MSc degree in Applied Physics from the Delft University of Technology, The Netherlands. He is currently pursuing a PhD there in the Quantum Transport group of the nanoscience department. He has previously worked on Sugar, the child-friendly user interface mainly in use by One Laptop Per Child's $100 laptop. For this project, he designed the Calculator application. Recently, he revived and extended the 3D plotting functionalities for Matplotlib to make it an excellent 2D graphing library, and a simple 3D plotting tool again. This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 Table of Contents Preface 1 Chapter 1: Introduction to Matplotlib 7 Merits of Matplotlib 8 Matplotlib web sites and online documentation 10 Output formats and backends 10 Output formats 11 Backends 12 About dependencies 13 Build dependencies 15 Installing Matplotlib 15 Installing Matplotlib on Linux 15 Installing Matplotlib on Windows 16 Installing Matplotlib on Mac OS X 16 Installing Matplotlib using packaged Python distributions 17 Installing Matplotlib from source code 17 Testing our installation 18 Summary 19 Chapter 2: Getting Started with Matplotlib 21 First plots with Matplotlib 21 Multiline plots 25 A brief introduction to NumPy arrays 27 Grid, axes, and labels 28 Adding a grid 28 Handling axes 29 Adding labels 31 Titles and legends 32 Adding a title 32 Adding a legend 33 This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 Table of Contents A complete example 35 Saving plots to a file 36 Interactive navigation toolbar 38 IPython support 40 Controlling the interactive mode 42 Suppressing functions output 43 Configuring Matplotlib 43 Configuration files 44 Configuring through the Python code 45 Selecting backend from code 46 Summary 47 Chapter 3: Decorate Graphs with Plot Styles and Types 49 Markers and line styles 49 Control colors 50 Specifying styles in multiline plots 52 Control line styles 52 Control marker styles 53 Finer control with keyword arguments 56 Handling X and Y ticks 58 Plot types 59 Histogram charts 59 Error bar charts 61 Bar charts 63 Pie charts 67 Scatter plots 69 Polar charts 71 Navigation Toolbar with polar plots 73 Control radial and angular grids 73 Text inside figure, annotations, and arrows 74 Text inside figure 74 Annotations 75 Arrows 77 Summary 79 Chapter 4: Advanced Matplotlib 81 Object-oriented versus MATLAB styles 81 A brief introduction to Matplotlib objects 85 Our first (simple) example of OO Matplotlib 85 Subplots 86 Multiple figures 88 Additional Y (or X) axes 89 [ ii ] This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 Table of Contents Logarithmic axes 91 Share axes 92 Plotting dates 94 Date formatting 95 Axes formatting with axes tick locators and formatters 96 Custom formatters and locators 99 Text properties, fonts, and LaTeX 99 Fonts 101 Using LaTeX formatting 102 Mathtext 103 External TeX renderer 104 Contour plots and image plotting 106 Contour plots 106 Image plotting 109 Summary 111 Chapter 5: Embedding Matplotlib in GTK+ 113 A brief introduction to GTK+ 113 Introduction to GTK+ signal system 115 Embedding a Matplotlib figure in a GTK+ window 116 Including a navigation toolbar 119 Real-time plots update 123 Embedding Matplotlib in a Glade application 132 Designing the GUI using Glade 132 Code to use Glade GUI 135 Summary 144 Chapter 6: Embedding Matplotlib in Qt 4 145 Brief introduction to Qt 4 and PyQt4 145 Embedding a Matplotlib figure in a Qt window 147 Including a navigation toolbar 151 Real-time update of a Matplotlib graph 156 Embedding Matplotlib in a GUI made with Qt Designer 165 Designing the GUI using Qt Designer 165 Code to use the Qt Designer GUI 168 Introduction to signals and slots 171 Returning to the example 172 Summary 179 Chapter 7: Embedding Matplotlib in wxWidgets 181 Brief introduction to wxWidgets and wxPython 181 Embedding a Matplotlib figure in a wxFrame 182 Including a navigation toolbar 186 [ iii ] This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104 Table of Contents Real-time plots update 192 Embedding Matplotlib in a GUI made with wxGlade 203 Summary 213 Chapter 8: Matplotlib for the Web 215 Matplotlib and CGI 216 What is CGI 216 Configuring Apache for CGI execution 216 Simple CGI example 218 Matplotlib in a CGI script 219 Passing parameters to a CGI script 220 Matplotlib and mod_python 223 What is mod_python 223 Apache configuration for mod_python 224 Matplotlib in a mod_python example 226 Matplotlib and mod_python's Python Server Pages 228 Web Frameworks and MVC 231 Matplotlib and Django 232 What is Django 232 Matplotlib in a Django application 233 Matplotlib and Pylons 237 What is Pylons 237 Matplotlib in a Pylons application 238 Summary 242 Chapter 9: Matplotlib in the Real World 243 Plotting data from a database 244 Plotting data from the Web 247 Plotting data by parsing an Apache log file 250 Plotting data from a CSV file 256 Plotting extrapolated data using curve fitting 261 Tools using Matplotlib 267 NetworkX 267 Mpmath 269 Plotting geographical data 271 First example 272 Using satellite background 274 Plot data over a map 275 Plotting shapefiles with Basemap 277 Summary 279 Index 281 [ iv ] This material is copyright and is licensed for the sole use by Jillian Fraser on 20th November 2009 111 Sutter Street, Suite 1800, San Francisco, , 94104