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 (raghuram.ashok@gmail.com) 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 Sandro Tosi Reviewers Michael Droettboom Reinier Heeres Acquisition Editor Usha Iyer Development Editor Rakesh Shejwal Technical Editor Namita Sahni Copy Editor Leonard D'Silva Editorial Team Leader Akshara Aware Project Team Leader Priya Mukherji Project Coordinator Zainab Bagasrawala Proofreader Lesley Harrison Graphics Nilesh Mohite Production Coordinator Adline Swetha Jesuthas Cover Work Indexers Adline Swetha Jesuthas 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 Chapter 1: Introduction to Matplotlib Merits of Matplotlib Matplotlib web sites and online documentation Output formats and backends Output formats Backends About dependencies Build dependencies Installing Matplotlib Installing Matplotlib on Linux Installing Matplotlib on Windows Installing Matplotlib on Mac OS X Installing Matplotlib using packaged Python distributions Installing Matplotlib from source code Testing our installation Summary Chapter 2: Getting Started with Matplotlib First plots with Matplotlib Multiline plots A brief introduction to NumPy arrays Grid, axes, and labels Adding a grid Handling axes Adding labels Titles and legends Adding a title Adding a legend 10 10 11 12 13 15 15 15 16 16 17 17 18 19 21 21 25 27 28 28 29 31 32 32 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 Saving plots to a file Interactive navigation toolbar IPython support Controlling the interactive mode Suppressing functions output Configuring Matplotlib Configuration files Configuring through the Python code Selecting backend from code Summary Chapter 3: Decorate Graphs with Plot Styles and Types Markers and line styles Control colors Specifying styles in multiline plots Control line styles Control marker styles Finer control with keyword arguments Handling X and Y ticks Plot types Histogram charts Error bar charts Bar charts Pie charts Scatter plots Polar charts Navigation Toolbar with polar plots Control radial and angular grids Text inside figure, annotations, and arrows Text inside figure Annotations Arrows Summary Chapter 4: Advanced Matplotlib Object-oriented versus MATLAB styles A brief introduction to Matplotlib objects Our first (simple) example of OO Matplotlib Subplots Multiple figures Additional Y (or X) axes 35 36 38 40 42 43 43 44 45 46 47 49 49 50 52 52 53 56 58 59 59 61 63 67 69 71 73 73 74 74 75 77 79 81 81 85 85 86 88 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 Share axes Plotting dates Date formatting Axes formatting with axes tick locators and formatters Custom formatters and locators Text properties, fonts, and LaTeX Fonts Using LaTeX formatting 91 92 94 95 96 99 99 101 102 Contour plots and image plotting Contour plots Image plotting Summary 106 106 109 111 Mathtext External TeX renderer Chapter 5: Embedding Matplotlib in GTK+ A brief introduction to GTK+ Introduction to GTK+ signal system Embedding a Matplotlib figure in a GTK+ window Including a navigation toolbar Real-time plots update Embedding Matplotlib in a Glade application Designing the GUI using Glade Code to use Glade GUI Summary 103 104 113 113 115 116 119 123 132 132 135 144 Chapter 6: Embedding Matplotlib in Qt 145 Chapter 7: Embedding Matplotlib in wxWidgets 181 Brief introduction to Qt and PyQt4 Embedding a Matplotlib figure in a Qt window Including a navigation toolbar Real-time update of a Matplotlib graph Embedding Matplotlib in a GUI made with Qt Designer Designing the GUI using Qt Designer Code to use the Qt Designer GUI Introduction to signals and slots Returning to the example Summary Brief introduction to wxWidgets and wxPython Embedding a Matplotlib figure in a wxFrame Including a navigation toolbar 145 147 151 156 165 165 168 171 172 179 181 182 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 Embedding Matplotlib in a GUI made with wxGlade Summary 192 203 213 Chapter 8: Matplotlib for the Web 215 Chapter 9: Matplotlib in the Real World 243 Index 281 Matplotlib and CGI What is CGI Configuring Apache for CGI execution Simple CGI example Matplotlib in a CGI script Passing parameters to a CGI script Matplotlib and mod_python What is mod_python Apache configuration for mod_python Matplotlib in a mod_python example Matplotlib and mod_python's Python Server Pages Web Frameworks and MVC Matplotlib and Django What is Django Matplotlib in a Django application Matplotlib and Pylons What is Pylons Matplotlib in a Pylons application Summary Plotting data from a database Plotting data from the Web Plotting data by parsing an Apache log file Plotting data from a CSV file Plotting extrapolated data using curve fitting Tools using Matplotlib NetworkX Mpmath Plotting geographical data First example Using satellite background Plot data over a map Plotting shapefiles with Basemap Summary 216 216 216 218 219 220 223 223 224 226 228 231 232 232 233 237 237 238 242 244 247 250 256 261 267 267 269 271 272 274 275 277 279 [ 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 ... Apache for CGI execution Simple CGI example Matplotlib in a CGI script Passing parameters to a CGI script Matplotlib and mod _python What is mod _python Apache configuration for mod _python Matplotlib. .. Matplotlib in a mod _python example Matplotlib and mod _python' s Python Server Pages Web Frameworks and MVC Matplotlib and Django What is Django Matplotlib in a Django application Matplotlib and Pylons... Who this book is 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