MatplotlibRelease 1.0.1 Darren Dale, Michael Droettboom, Eric Firing, John Hunter January 06, 2011 CONTENTS I 1 2 User’s Guide Introduction Installing 2.1 OK, so you want to do it the hard way? 2.2 Installing from source . . . . . . . . . 2.3 Build requirements . . . . . . . . . . . 2.4 Building on OSX . . . . . . . . . . . . 1 3 5 5 6 6 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Pyplot tutorial 9 3.1 Controlling line properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Working with multiple figures and axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.3 Working with text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Interactive navigation 19 4.1 Navigation Keyboard Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Customizing matplotlib 23 5.1 The matplotlibrc file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.2 Dynamic rc settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Using matplotlib in a python shell 33 6.1 Ipython to the rescue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 6.2 Other python interpreters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 6.3 Controlling interactive updating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Working with text 7.1 Text introduction . . . . . . . . . 7.2 Basic text commands . . . . . . . 7.3 Text properties and layout . . . . 7.4 Writing mathematical expressions 7.5 Text rendering With LaTeX . . . 7.6 Annotating text . . . . . . . . . . Image tutorial 37 37 37 38 41 51 56 59 4 5 6 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 i 8.1 8.2 8.3 9 Startup commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Importing image data into Numpy arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Plotting numpy arrays as images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 73 74 76 77 78 81 83 85 86 87 88 89 91 91 93 93 94 97 97 98 102 103 107 107 110 111 113 115 Artist tutorial 9.1 Customizing your objects 9.2 Object containers . . . . . 9.3 Figure container . . . . . 9.4 Axes container . . . . . . 9.5 Axis containers . . . . . . 9.6 Tick containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Customizing Location of Subplot Using GridSpec 10.1 GridSpec and SubplotSpec . . . . . . . . . . . 10.2 Adjust GridSpec layout . . . . . . . . . . . . 10.3 GridSpec using SubplotSpec . . . . . . . . . . 10.4 GridSpec with Varying Cell Sizes . . . . . . . 11 Legend guide 11.1 What to be displayed 11.2 Multicolumn Legend 11.3 Legend location . . 11.4 Multiple Legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Event handling and picking 12.1 Event connections . . 12.2 Event attributes . . . . 12.3 Mouse enter and leave 12.4 Object picking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Transformations Tutorial 13.1 Data coordinates . . . . . . . . . . . . . . . . . 13.2 Axes coordinates . . . . . . . . . . . . . . . . . 13.3 Blended transformations . . . . . . . . . . . . . 13.4 Using offset transforms to create a shadow effect 13.5 The transformation pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Path Tutorial 117 14.1 Bézier example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 14.2 Compound paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 15 Annotating Axes 15.1 Annotating with Text with Box . . . . . . . . . . 15.2 Annotating with Arrow . . . . . . . . . . . . . . . 15.3 Placing Artist at the anchored location of the Axes 15.4 Using Complex Coordinate with Annotation . . . 15.5 Using ConnectorPatch . . . . . . . . . . . . . . . 15.6 Zoom effect between Axes . . . . . . . . . . . . . 15.7 Define Custom BoxStyle . . . . . . . . . . . . . . ii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 123 124 130 133 135 135 136 16 Our Favorite Recipes 16.1 Sharing axis limits and views . . 16.2 Easily creating subplots . . . . . 16.3 Fixing common date annoyances 16.4 Fill Between and Alpha . . . . . 16.5 Transparent, fancy legends . . . . 16.6 Placing text boxes . . . . . . . . 17 Toolkits 17.1 Basemap . 17.2 GTK Tools 17.3 Excel Tools 17.4 Natgrid . . 17.5 mplot3d . . 17.6 AxesGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 141 141 142 143 147 148 151 151 151 151 151 151 152 153 153 154 154 154 154 155 155 155 156 156 156 157 157 157 158 158 158 159 159 159 161 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Screenshots 18.1 Simple Plot . . . . . . 18.2 Subplot demo . . . . . 18.3 Histograms . . . . . . 18.4 Path demo . . . . . . 18.5 mplot3d . . . . . . . . 18.6 Ellipses . . . . . . . . 18.7 Bar charts . . . . . . . 18.8 Pie charts . . . . . . . 18.9 Table demo . . . . . . 18.10 Scatter demo . . . . . 18.11 Slider demo . . . . . . 18.12 Fill demo . . . . . . . 18.13 Date demo . . . . . . 18.14 Financial charts . . . . 18.15 Basemap demo . . . . 18.16 Log plots . . . . . . . 18.17 Polar plots . . . . . . 18.18 Legends . . . . . . . . 18.19 Mathtext_examples . . 18.20 Native TeX rendering 18.21 EEG demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 What’s new in matplotlib 173 19.1 new in matplotlib-1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 19.2 new in matplotlib-0.99 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 19.3 new in 0.98.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 20 License 187 20.1 License agreement for matplotlib 1.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 21 Credits 189 iii II The Matplotlib FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 195 195 195 196 197 197 197 199 201 22 Installation FAQ 22.1 Report a compilation problem . . . . . . . . . . . . . . 22.2 matplotlib compiled fine, but nothing shows up with plot 22.3 Cleanly rebuild and reinstall everything . . . . . . . . . 22.4 Install from svn . . . . . . . . . . . . . . . . . . . . . . 22.5 Install from git . . . . . . . . . . . . . . . . . . . . . . 22.6 Backends . . . . . . . . . . . . . . . . . . . . . . . . . 22.7 OS-X questions . . . . . . . . . . . . . . . . . . . . . . 22.8 Windows questions . . . . . . . . . . . . . . . . . . . . 23 Usage 203 23.1 Matplotlib, pylab, and pyplot: how are they related? . . . . . . . . . . . . . . . . . . . . . 203 24 Howto 24.1 Plotting: howto . . . . . . . . . . . . 24.2 Contributing: howto . . . . . . . . . 24.3 Matplotlib in a web application server 24.4 Search examples . . . . . . . . . . . 24.5 Cite Matplotlib . . . . . . . . . . . . 25 Troubleshooting 25.1 Obtaining matplotlib version . . . 25.2 matplotlib install location . . . 25.3 .matplotlib directory location . 25.4 Report a problem . . . . . . . . . 25.5 Problems with recent svn versions 205 206 215 216 217 218 219 219 219 219 220 221 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . III The Matplotlib Developers’ Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 225 225 229 232 233 233 234 236 239 239 239 240 242 243 243 244 26 Coding guide 26.1 Version control . . . . . . . . 26.2 Style guide . . . . . . . . . . 26.3 Documentation and docstrings 26.4 Developing a new backend . . 26.5 Writing examples . . . . . . . 26.6 Testing . . . . . . . . . . . . 26.7 Licenses . . . . . . . . . . . 27 Documenting matplotlib 27.1 Getting started . . . . . . . . . . . . . . . 27.2 Organization of matplotlib’s documentation 27.3 Formatting . . . . . . . . . . . . . . . . . 27.4 Figures . . . . . . . . . . . . . . . . . . . 27.5 Referring to mpl documents . . . . . . . . 27.6 Internal section references . . . . . . . . . 27.7 Section names, etc . . . . . . . . . . . . . iv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27.8 Inheritance diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 27.9 Emacs helpers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 28 Doing a matplolib release 28.1 Testing . . . . . . . . . . 28.2 Branching . . . . . . . . 28.3 Packaging . . . . . . . . 28.4 Release candidate testing: 28.5 Uploading . . . . . . . . 28.6 Announcing . . . . . . . 247 247 247 247 248 248 249 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Working with transformations 251 29.1 matplotlib.transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 30 Adding new scales and projections to matplotlib 271 30.1 Creating a new scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 30.2 Creating a new projection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 30.3 API documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 31 Docs outline 281 31.1 Reviewer notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 IV The Matplotlib API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 289 289 291 291 293 293 298 298 298 299 300 301 303 303 304 304 305 306 307 307 307 308 309 309 v 32 API Changes 32.1 Changes beyond 0.99.x . 32.2 Changes in 0.99 . . . . 32.3 Changes for 0.98.x . . . 32.4 Changes for 0.98.1 . . . 32.5 Changes for 0.98.0 . . . 32.6 Changes for 0.91.2 . . . 32.7 Changes for 0.91.1 . . . 32.8 Changes for 0.91.0 . . . 32.9 Changes for 0.90.1 . . . 32.10 Changes for 0.90.0 . . . 32.11 Changes for 0.87.7 . . . 32.12 Changes for 0.86 . . . . 32.13 Changes for 0.85 . . . . 32.14 Changes for 0.84 . . . . 32.15 Changes for 0.83 . . . . 32.16 Changes for 0.82 . . . . 32.17 Changes for 0.81 . . . . 32.18 Changes for 0.80 . . . . 32.19 Changes for 0.73 . . . . 32.20 Changes for 0.72 . . . . 32.21 Changes for 0.71 . . . . 32.22 Changes for 0.70 . . . . 32.23 Changes for 0.65.1 . . . 32.24 32.25 32.26 32.27 32.28 32.29 32.30 32.31 32.32 Changes for 0.65 . Changes for 0.63 . Changes for 0.61 . Changes for 0.60 . Changes for 0.54.3 Changes for 0.54 . Changes for 0.50 . Changes for 0.42 . Changes for 0.40 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 309 310 310 310 311 314 315 316 33 matplotlib configuration 319 33.1 matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 34 matplotlib afm 323 34.1 matplotlib.afm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 35 matplotlib artists 35.1 matplotlib.artist . 35.2 matplotlib.legend . 35.3 matplotlib.lines . . 35.4 matplotlib.patches 35.5 matplotlib.text . . . 327 327 336 339 347 383 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 matplotlib axes 395 36.1 matplotlib.axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 37 matplotlib axis 535 37.1 matplotlib.axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 38 matplotlib cbook 545 38.1 matplotlib.cbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 39 matplotlib cm 557 39.1 matplotlib.cm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 40 matplotlib collections 559 40.1 matplotlib.collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559 41 matplotlib colorbar 573 41.1 matplotlib.colorbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 42 matplotlib colors 577 42.1 matplotlib.colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577 43 matplotlib dates 585 43.1 matplotlib.dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585 44 matplotlib figure 593 44.1 matplotlib.figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593 vi 45 matplotlib font_manager 611 45.1 matplotlib.font_manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611 45.2 matplotlib.fontconfig_pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616 46 matplotlib gridspec 619 46.1 matplotlib.gridspec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 47 matplotlib mathtext 621 47.1 matplotlib.mathtext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 48 matplotlib mlab 637 48.1 matplotlib.mlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637 49 matplotlib path 661 49.1 matplotlib.path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 50 matplotlib pyplot 667 50.1 matplotlib.pyplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 51 matplotlib nxutils 815 51.1 matplotlib.nxutils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815 52 matplotlib spine 817 52.1 matplotlib.spine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817 53 matplotlib ticker 821 53.1 matplotlib.ticker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821 54 matplotlib units 829 54.1 matplotlib.units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829 55 matplotlib backends 55.1 matplotlib.backend_bases . . . . . . . 55.2 matplotlib.backends.backend_gtkagg 55.3 matplotlib.backends.backend_qt4agg 55.4 matplotlib.backends.backend_wxagg . 55.5 matplotlib.backends.backend_pdf . . 55.6 matplotlib.dviread . . . . . . . . . . . 55.7 matplotlib.type1font . . . . . . . . . . 831 831 847 847 848 849 851 854 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . V Glossary 855 859 861 Python Module Index Index vii viii Part I User’s Guide 1 CHAPTER ONE INTRODUCTION matplotlib is a library for making 2D plots of arrays in Python. Although it has its origins in emulating the MATLAB® 1 graphics commands, it is independent of MATLAB, and can be used in a Pythonic, object oriented way. Although matplotlib is written primarily in pure Python, it makes heavy use of NumPy and other extension code to provide good performance even for large arrays. matplotlib is designed with the philosophy that you should be able to create simple plots with just a few commands, or just one! If you want to see a histogram of your data, you shouldn’t need to instantiate objects, call methods, set properties, and so on; it should just work. For years, I used to use MATLAB exclusively for data analysis and visualization. MATLAB excels at making nice looking plots easy. When I began working with EEG data, I found that I needed to write applications to interact with my data, and developed and EEG analysis application in MATLAB. As the application grew in complexity, interacting with databases, http servers, manipulating complex data structures, I began to strain against the limitations of MATLAB as a programming language, and decided to start over in Python. Python more than makes up for all of MATLAB’s deficiencies as a programming language, but I was having difficulty finding a 2D plotting package (for 3D VTK more than exceeds all of my needs). When I went searching for a Python plotting package, I had several requirements: • Plots should look great - publication quality. One important requirement for me is that the text looks good (antialiased, etc.) • Postscript output for inclusion with TeX documents • Embeddable in a graphical user interface for application development • Code should be easy enough that I can understand it and extend it • Making plots should be easy Finding no package that suited me just right, I did what any self-respecting Python programmer would do: rolled up my sleeves and dived in. Not having any real experience with computer graphics, I decided to emulate MATLAB’s plotting capabilities because that is something MATLAB does very well. This had the added advantage that many people have a lot of MATLAB experience, and thus they can quickly get up to steam plotting in python. From a developer’s perspective, having a fixed user interface (the pylab interface) has been very useful, because the guts of the code base can be redesigned without affecting user code. 1 MATLAB is a registered trademark of The MathWorks, Inc. 3 Matplotlib, Release 1.0.1 The matplotlib code is conceptually divided into three parts: the pylab interface is the set of functions provided by matplotlib.pylab which allow the user to create plots with code quite similar to MATLAB figure generating code (Pyplot tutorial). The matplotlib frontend or matplotlib API is the set of classes that do the heavy lifting, creating and managing figures, text, lines, plots and so on (Artist tutorial). This is an abstract interface that knows nothing about output. The backends are device dependent drawing devices, aka renderers, that transform the frontend representation to hardcopy or a display device (What is a backend?). Example backends: PS creates PostScript® hardcopy, SVG creates Scalable Vector Graphics hardcopy, Agg creates PNG output using the high quality Anti-Grain Geometry library that ships with matplotlib, GTK embeds matplotlib in a Gtk+ application, GTKAgg uses the Anti-Grain renderer to create a figure and embed it a Gtk+ application, and so on for PDF, WxWidgets, Tkinter etc. matplotlib is used by many people in many different contexts. Some people want to automatically generate PostScript files to send to a printer or publishers. Others deploy matplotlib on a web application server to generate PNG output for inclusion in dynamically-generated web pages. Some use matplotlib interactively from the Python shell in Tkinter on Windows™. My primary use is to embed matplotlib in a Gtk+ EEG application that runs on Windows, Linux and Macintosh OS X. 4 Chapter 1. Introduction CHAPTER TWO INSTALLING There are lots of different ways to install matplotlib, and the best way depends on what operating system you are using, what you already have installed, and how you want to use it. To avoid wading through all the details (and potential complications) on this page, the easiest thing for you to do is use one of the prepackaged python distributions that already provide matplotlib built in. The Enthought Python Distribution (EPD) for Windows, OS X or Redhat is an excellent choice that “just works” out of the box. Another excellent alternative for Windows users is Python (x, y) which tends to be updated a bit more frequently. Both of these packages include matplotlib and pylab, and lots of other useful tools. matplotlib is also packaged for pretty much every major linux distribution, so if you are on linux your package manager will probably provide matplotlib prebuilt. One single click installer and you are done. 2.1 OK, so you want to do it the hard way? For some people, the prepackaged pythons discussed above are not an option. That’s OK, it’s usually pretty easy to get a custom install working. You will first need to find out if you have python installed on your machine, and if not, install it. The official python builds are available for download here, but OS X users please read Which python for OS X?. Once you have python up and running, you will need to install numpy. numpy provides high performance array data structures and mathematical functions, and is a requirement for matplotlib. You can test your progress: >>> import numpy >>> print numpy.__version__ matplotlib requires numpy version 1.1 or later. Although it is not a requirement to use matplotlib, we strongly encourage you to install ipython, which is an interactive shell for python that is matplotlib aware. Next we need to get matplotlib installed. We provide prebuilt binaries for OS X and Windows on the matplotlib download page. Click on the latest release of the “matplotlib” package, choose your python version (2.5 or 2.6) and your platform (macosx or win32) and you should be good to go. If you have any problems, please check the Installation FAQ, google around a little bit, and post a question the mailing list. If you are on debian/unbuntu linux, it suffices to do: 5 Matplotlib, Release 1.0.1 > sudo apt-get install python-matplotlib Instructions for installing our OSX binaries are found in the FAQ Installing OSX binaries. Once you have ipython, numpy and matplotlib installed, in ipython’s “pylab” mode you have a MATLABlike environment that automatically handles most of the configuration details for you, so you can get up and running quickly: johnh@flag:~> ipython -pylab Python 2.4.5 (#4, Apr 12 2008, 09:09:16) IPython 0.9.0 -- An enhanced Interactive Python. Welcome to pylab, a matplotlib-based Python environment. For more information, type ’help(pylab)’. In [1]: x = randn(10000) In [2]: hist(x, 100) Instructions for installing our OSX binaries are found in the FAQ ref:install_osx_binaries. Note that when testing matplotlib installations from the interactive python console, there are some issues relating to user interface toolkits and interactive settings that are discussed in Using matplotlib in a python shell. 2.2 Installing from source If you are interested perhaps in contributing to matplotlib development, running the latest greatest code, or just like to build everything yourself, it is not difficult to build matplotlib from source. Grab the latest tar.gz release file from sourceforge, or if you want to develop matplotlib or just need the latest bugfixed version, grab the latest svn version Install from svn. Once you have satisfied the requirements detailed below (mainly python, numpy, libpng and freetype), you build matplotlib in the usual way: cd matplotlib python setup.py build python setup.py install We provide a setup.cfg file that lives along setup.py which you can use to customize the build process, for example, which default backend to use, whether some of the optional libraries that matplotlib ships with are installed, and so on. This file will be particularly useful to those packaging matplotlib. 2.3 Build requirements These are external packages which you will need to install before installing matplotlib. Windows users only need the first two (python and numpy) since the others are built into the matplotlib windows installers available for download at the sourceforge site. If you are building on OSX, see Building on OSX. If you are 6 Chapter 2. Installing Matplotlib, Release 1.0.1 installing dependencies with a package manager, you may need to install the development packages (look for a “-dev” postfix) in addition to the libraries themselves. python 2.4 (or later but not python3) matplotlib requires python 2.4 or later (download) numpy 1.1 (or later) array support for python (download) libpng 1.1 (or later) library for loading and saving PNG files (download). libpng requires zlib. If you are a windows user, you can ignore this since we build support into the matplotlib single click installer freetype 1.4 (or later) library for reading true type font files. If you are a windows user, you can ignore this since we build support into the matplotlib single click installer. Optional These are optional packages which you may want to install to use matplotlib with a user interface toolkit. See What is a backend? for more details on the optional matplotlib backends and the capabilities they provide tk 8.3 or later The TCL/Tk widgets library used by the TkAgg backend pyqt 3.1 or later The Qt3 widgets library python wrappers for the QtAgg backend pyqt 4.0 or later The Qt4 widgets library python wrappers for the Qt4Agg backend pygtk 2.4 or later The python wrappers for the GTK widgets library for use with the GTK or GTKAgg backend wxpython 2.6 or later The python wrappers for the wx widgets library for use with the WXAgg backend wxpython 2.8 or later The python wrappers for the wx widgets library for use with the WX backend pyfltk 1.0 or later The python wrappers of the FLTK widgets library for use with FLTKAgg Required libraries that ship with matplotlib agg 2.4 The antigrain C++ rendering engine. matplotlib links against the agg template source statically, so it will not affect anything on your system outside of matplotlib. pytz 2007g or later timezone handling for python datetime objects. By default, matplotlib will install pytz if it isn’t already installed on your system. To override the default, use :file:‘setup.cfg to force or prevent installation of pytz. dateutil 1.1 or later provides extensions to python datetime handling. By default, matplotlib will install dateutil if it isn’t already installed on your system. To override the default, use setup.cfg to force or prevent installation of dateutil. 2.4 Building on OSX The build situation on OSX is complicated by the various places one can get the png and freetype requirements from (darwinports, fink, /usr/X11R6) and the different architectures (x86, ppc, universal) and the different OSX version (10.4 and 10.5). We recommend that you build the way we do for the OSX release: by grabbing the tarbar or svn repository, cd-ing into the release/osx dir, and following the instruction in the 2.4. Building on OSX 7 Matplotlib, Release 1.0.1 README. This directory has a Makefile which will automatically grab the zlib, png and freetype dependencies from the web, build them with the right flags to make universal libraries, and then build the matplotlib source and binary installers. 8 Chapter 2. Installing create a figure.show() 4. in that it keeps track of the current figure and plotting area.5 2.4]) plt.0 0. etc.pyplot is a collection of command style functions that make matplotlib work like MATLAB.5 3.0 1.0 0.0 2. Each pyplot function makes some change to a figure: eg.plot([1.5 1.ylabel(’some numbers’) plt.5 2.2.0 9 .5 some numbers 3.pyplot as plt plt..CHAPTER THREE PYPLOT TUTORIAL matplotlib.0 1.0 3. create a plotting area in a figure.5 1. and the plotting functions are directed to the current axes import matplotlib...pyplot is stateful.0 2.3. matplotlib. decorate the plot with labels. plot some lines in a plotting area. If you provide a single list or array to the plot() command. and you concatenate a color string with a line style string. In fact. there is an optional third argument which is the format string that indicates the color and line type of the plot. 10 Chapter 3. matplotlib assumes it is a sequence of y values.9. Hence the x data are [0. ymin. The axis() command in the example above takes a list of [xmin. If matplotlib were limited to working with lists. Since python ranges start with 0. Pyplot tutorial . For example.2.3. 20]) 20 15 10 5 00 1 2 3 4 5 6 See the plot() documentation for a complete list of line styles and format strings.4. The letters and symbols of the format string are from MATLAB. 0. The example below illustrates a plotting several lines with different format styles in one command using arrays.0. it would be fairly useless for numeric processing. plot() is a versatile command.16]) For every x. Generally.plot([1. y pair of arguments.16]. which is a solid blue line.Matplotlib. 6.9.1. and automatically generates the x values for you.3. [1. you would issue import matplotlib.4].2. xmax.axis([0.pyplot as plt plt. all sequences are converted to numpy arrays internally. The default format string is ‘b-‘. ’ro’) plt. and will take an arbitrary number of arguments.4. you can issue the command: plt. you will use numpy arrays.2]. For example. to plot the above with red circles. [1. the default x vector has the same length as y but starts with 0.4].1 You may be wondering why the x-axis ranges from 0-2 and the y-axis from 1-3.plot([1. ymax] and specifies the viewport of the axes. Release 1. to plot x versus y. etc. ’o’) to get the first element of the list: 3. plot returns a list of lines. = plot(x.plot(t.1 Controlling line properties Lines have many attributes that you can set: linewidth. ’r--’.. 5. Release 1.x2).arange(0. Controlling line properties 11 .pyplot as plt # evenly sampled time at 200ms intervals t = np. line2 = plot(x1. I use tuple unpacking in the line. linewidth=2.0. eg line1.1 import numpy as np import matplotlib.Line2D. ’g^’) 120 100 80 60 40 20 00 1 2 3 4 5 3. matplotlib. t**3. t**2.2) # red dashes. ’bs’. 0. There are several ways to set line properties • Use keyword args: plt.. dash style.x2. t. t. Below I have only one line so it is a list of length 1.1.plot(x. t.lines. y.y1. antialiased. y.0) see • Use the setter methods of the Line2D instance. blue squares and green triangles plt.Matplotlib. array xdata. a Patch any matplotlib color the hit testing function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points (np.array ydata) a matplotlib.0. x2. y. 2.0) # or MATLAB style string value pairs plt. You can either use python keyword arguments or MATLAB-style string/value pairs: lines = plt.. = plt.setp(lines. np.’ | ‘. ’-’) line. stride) used in interactive line selection the line pick selection radius [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Matplotlib.Transform instance [True | False] np. ’r’.transforms.plot(x.plot(x1. color=’r’.array np.figure.’ | ‘:’ | ‘steps’ | . ’color’.Bbox instance [True | False] a Path instance and a Transform instance. The example below uses a MATLAB-style command to set multiple properties on a list of lines. ’linewidth’. y1.set_antialiased(False) # turn off antialising • Use the setp() command. Release 1.. y2) # use keyword args plt. linewidth=2.] float value in points [True | False] [ ‘+’ | ‘.1 line.’ | ‘1’ | ‘2’ | ‘3’ | ‘4’ any matplotlib color float value in points any matplotlib color float None | integer | (startind.setp(lines. setp works transparently with a list of objects or a single object.transform.0) Here are the available Line2D properties. Pyplot tutorial . Property alpha animated antialiased or aa clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data figure label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markersize or ms markevery picker pickradius solid_capstyle solid_joinstyle transform visible xdata ydata zorder Value Type float [True | False] [True | False] a matplotlib.Figure instance any string [ ‘-‘ | ‘–‘ | ‘-.array any number 12 Chapter 3. ’k’) plt.0. t2. have the concept of the current figure and the current axes. All plotting commands apply to the current axes.1.0. Of course.2.axes.plot(t2. numcols.1). The commas in the subplot command are optional if numrows*numcols<10. 0. Working with multiple figures and axes 13 . 0. So subplot(211) is identical to subplot(2.pyplot as plt plt. not on a rectangular grid.3]) In [70]: plt. because it is all taken care of behind the scenes. Release 1. you don’t have to worry about this.snip 3. bottom.Axes instance).pi*t) t1 = np.1 To get a list of settable line properties.0.3]) 3. just as a subplot(111) will be created by default if you don’t manually specify an axes.. 5.2.arange(0.plot(t1.figure(1) # the first figure plt.exp(-t) * np. Below is a script to create two subplots.02) plt. ’bo’. import numpy as np import matplotlib.subplot(211) plt.figure. and gcf() returns the current figure (matplotlib.Matplotlib.setp(lines) alpha: float animated: [True | False] antialiased or aa: [True | False] .. width. call the setp() function with a line or lines as argument In [69]: lines = plt. ’r--’) The figure() command here is optional because figure(1) will be created by default.2 Working with multiple figures and axes MATLAB. each figure can contain as many axes and subplots as your heart desires: import matplotlib.1) t2 = np.subplot(212) plt. If you want to place an axes manually. ie.0.figure(1) plt. height]) where all values are in fractional (0 to 1) coordinates. f(t2).pyplot as plt def f(t): return np.arange(0. use the axes() command.cos(2*np. Normally. See pylab_examples-axes_demo for an example of placing axes manually and pylab_examples-line_styles for an example with lots-o-subplots.Figure instance). The subplot() command specifies numrows.plot([1. np. f(t1). You can create an arbitrary number of subplots and axes.subplot(211) # the first subplot in the first figure plt. 5. which allows you to specify the location as axes([left.cos(2*np.plot([1. and pyplot.pi*t2).0. You can create multiple figures by using multiple figure() calls with an increasing figure number. fignum where fignum ranges from 1 to numrows*numcols. The function gca() returns the current axes (a matplotlib.2. 5. you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close().0 0.6]) plt.plot([4.8 0. because pyplot maintains internal references until close() is called.2 0.5 0.5.0 0.6 0.subplot(212) plt.80 1.0 0.0 0.0. If you find this statefulness.1 1.2 0. Pyplot tutorial . and/or using the window manager to kill the window in which the figure appears on the screen. subplot(212) still current # make subplot(211) in figure1 current # subplot 211 title You can clear the current figure with clf() and the current axes with cla(). Release 1.figure(1) plt.6]) 1 2 3 4 5 1 2 3 4 5 # the second subplot in the first figure plt.4 0. don’t despair.subplot(211) plt.00 plt.figure(2) plt.2. this is just a thin stateful wrapper around an object oriented API. is not enough.title(’Easy as 1. 14 Chapter 3.4 0. Deleting all references to the figure.3’) # a second figure # creates a subplot(111) by default # figure 1 current.plot([4. which you can use instead (see Artist tutorial) If you are making a long sequence of figures.6 0.Matplotlib. annoying.5 1. grid(True) 0.3 Working with text The text() command can be used to add text in an arbitrary location. you can customize the properties by passing keyword arguments into the text functions or using setp(): 3. bins. r’$\mu=100. 50.xlabel(’Smarts’) plt.Text instance. 160.03]) plt. 0.hist(x.015 0. facecolor=’g’. normed=1.3.025. . 15 x = mu + sigma * np.0. alpha=0. Release 1.title(’Histogram of IQ’) plt.020 Probability 0.005 0. Working with text 15 .000 40 60 Histogram of IQ µ =100. sigma = 100.1 3. patches = plt.030 0.\ \sigma=15$’) plt.ylabel(’Probability’) plt.pyplot as plt mu.025 0.text.randn(10000) # the histogram of the data n.text(60. and the xlabel().axis([40. σ =15 80 100 120 Smarts 140 160 All of the text() commands return an matplotlib. Just as with with lines above.75) plt. ylabel() and title() are used to add text in the indicated locations (see Text introduction for a more detailed example) import numpy as np import matplotlib.random.Matplotlib.010 0. 0. matplotlib has a built-in TeX expression parser and layout engine. you can write a TeX expression surrounded by dollar signs: plt. 1). 0. arrowprops=dict(facecolor=’black’. color=’red’) These properties are covered in more detail in Text properties and layout. s.plot(t. xy=(2. There are a variety of other coordinate systems one can choose – see Annotating text and Annotating Axes for details.0. More examples can be found in pylab_examples-annotation_demo. lw=2) plt. xytext=(3.5). For example to write the expression σi = 15 in the title.0. 1. 16 Chapter 3. Both of these arguments are (x. both the xy (arrow tip) and xytext locations (text location) are in data coordinates. Thus you can use mathematical text across platforms without requiring a TeX installation.1 t = plt.2 Annotating text The uses of the basic text() command above place text at an arbitrary position on the Axes. there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. you can also use LaTeX to format your text and incorporate the output directly into your display figures or saved postscript – see Text rendering With LaTeX.arange(0. and ships its own math fonts – for details see Writing mathematical expressions. Release 1. A common use case of text is to annotate some feature of the plot. fontsize=14.subplot(111) t = np. shrink=0.0. and the annotate() method provides helper functionality to make annotations easy.annotate(’local max’.xlabel(’my data’.title(r’$\sigma_i=15$’) The r preceeding the title string is important – it signifies that the string is a raw string and not to treate backslashes and python escapes. 5. = plt.3.ylim(-2.cos(2*np.Matplotlib.01) s = np.2) plt. import numpy as np import matplotlib. In an annotation.show() In this basic example.pi*t) line. 3.pyplot as plt ax = plt.05). 3.y) tuples. ) plt. Pyplot tutorial .1 Using mathematical expressions in text matplotlib accepts TeX equation expressions in any text expression.3. For those who have LaTeX and dvipng installed. Release 1. Working with text 17 .0 1.0.Matplotlib.5 1.1 2.5 2.0 0.5 1.0 1.00 1 2 3 4 5 local max 3.3.5 0.0 0. 1 18 Chapter 3. Pyplot tutorial .Matplotlib. Release 1.0. the data under the point where you pressed will be moved to the point where you released. default view of your data. think web browser where data views are web pages. Ditto for the y axis and up/down motions. Press the left mouse button and hold it to pan the figure. 19 . Home always takes you to the first. The point under your mouse when you begin the zoom remains stationary. If you press ‘x’ or ‘y’ while panning the motion will be constrained to the x or y axis. You can use the modifier keys ‘x’. dragging it to a new position. Click the toolbar button to activate panning and zooming. the y axis. The Pan/Zoom button This button has two modes: pan and zoom. The x axis will be zoomed in proportionate to the rightward movement and zoomed out proportionate to the leftward movement. ‘y’ or ‘CONTROL’ to constrain the zoom to the x axis. The radius axis labels can be dragged using the left mouse button. Press the right mouse button to zoom. This is analogous to trying to click Back on your web browser before visiting a new page –nothing happens. Here is a description of each of the buttons at the bottom of the toolbar The Forward and Back buttons These are akin to the web browser forward and back buttons. which can be used to navigate through the data set. the pan and zoom functionality behaves differently. or aspect ratio preserve. They are used to navigate back and forth between previously defined views. Forward and Back. Use the pan and zoom to rectangle to define new views.CHAPTER FOUR INTERACTIVE NAVIGATION All figure windows come with a navigation toolbar. dragging it to a new position. For Home. With polar plots. respectively. respectively. They have no meaning unless you have already navigated somewhere else using the pan and zoom buttons. When you release it. The radius scale can be zoomed in and out using the right mouse button. then put your mouse somewhere over an axes. allowing you to zoom to an arbitrary point in the figure. 0. There is also an experimental ‘zoom out to rectangle’ in this mode with the right button. space between the rows and space between the columns. If you are writing your own user interface code. which will place your entire axes in the region defined by the zoom out rectangle. 4.1 The Zoom-to-rectangle button Click this toolbar button to activate this mode.*). Drag the mouse while holding the button to a new location and release. The Save button Click this button to launch a file save dialog. ps. bottom.pyplot the toolbar will be created automatically for every figure. you can add the toolbar as a widget. The Subplot-configuration button Use this tool to configure the parameters of the subplot: the left. svg and pdf. You can save files with the following extensions: png. which can be overwritten by use of your matplotlibrc (#keymap. Command Home/Reset Back Forward Pan/Zoom Zoom-to-rect Save Toggle fullscreen Constrain pan/zoom to x axis Constrain pan/zoom to y axis Preserve aspect ratio Toggle grid Toggle x axis scale (log/linear) Toggle y axis scale (log/linear) Keyboard Shortcut(s) h or r or home c or left arrow or backspace v or right arrow p o s f hold x hold y hold CONTROL g L or k l If you are using matplotlib.1 Navigation Keyboard Shortcuts The following table holds all the default keys. Release 1. top. eps.Matplotlib. The axes view limits will be zoomed to the rectangle you have defined. right. Interactive navigation . Put your mouse somewhere over and axes and press the left mouse button. The exact syntax depends on 20 Chapter 4. 3]) canvas = FigureCanvas(fig) # a gtk.VBox() win. lambda x: gtk. Here is some example code for GTK: from matplotlib.main_quit()) win.Matplotlib.connect("destroy".4).0.Window() win.plot([1. but we have examples for every supported UI in the matplotlib/examples/user_interfaces directory.300) win.backends. Navigation Keyboard Shortcuts 21 .show_all() gtk. dpi=100) ax = fig. win) vbox.pack_start(toolbar. False) win.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar win = gtk.1 your UI.backends. Release 1. False.set_title("Embedding in GTK") vbox = gtk.main() 4.1.add_subplot(111) ax.figure import Figure from matplotlib.add(vbox) fig = Figure(figsize=(5.set_default_size(400.2.DrawingArea vbox.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas from matplotlib.pack_start(canvas) toolbar = NavigationToolbar(canvas. Interactive navigation .1 22 Chapter 4. Release 1.0.Matplotlib. 2 Dynamic rc settings You can also dynamically change the default rc settings in a python script or interactively from the python shell.matplotlib/matplotlibrc. axis and grid properties.matplotlib/matplotlibrc’ See below for a sample matplotlibrc file. this file will be overwritten. Every time you install matplotlib. for the user’s default customizations. rcParams can be modified directly. so if you want your customizations to be saved.color’] = ’r’ 23 . 2.linewidth’] = 2 mpl. matplotlib looks for matplotlibrc in three locations. See . one can do the following: >>> import matplotlib >>> matplotlib.matplotlib directory. in the following order: 1.matplotlib_fname() ’/home/foo/. axes. for example: import matplotlib as mpl mpl. please move this file to you . color and style. usually used for specific customizations that you do not want to apply elsewhere. You can control the defaults of almost every property in matplotlib: figure size and dpi. text and font properties and so on.1 The matplotlibrc file matplotlib uses matplotlibrc configuration files to customize all kinds of properties. matplotlibrc in the current working directory. 5. INSTALL/matplotlib/mpl-data/matplotlibrc.rcParams. and maybe C:\Python25\Lib\site-packages on Windows. All of the rc settings are stored in a dictionary-like variable called matplotlib. To display where the currently active matplotlibrc file was loaded from.CHAPTER FIVE CUSTOMIZING MATPLOTLIB 5.rcParams[’lines.5/site-packages on Linux. which we call rc settings or rc parameters. line width.rcParams[’lines.matplotlib directory location. . where INSTALL is something like /usr/lib/python2. 3. which is global to the matplotlib package. you can find a copy of it on your system in site-packages/matplotlib/mpl-data/matplotlibrc.75 . linewidth=2.a hex string. Other lines must have the format key : val # optional comment Colors: for the color values below.a scalar grayscale intensity such as 0. 0.rc(’lines’. such as r. Customizing matplotlib .an rgb tuple.rcdefaults() command will restore the standard matplotlib default settings. see matplotlib. color=’r’) There matplotlib. we will automatically try and find a compatible one for # you if backend_fallback is True #backend_fallback: True #interactive : False #toolbar : toolbar2 # None | classic | toolbar2 24 Chapter 5.matplotlib/matplotlibrc (unix/linux like systems) and C:\Documents and Settings\yourname\.matplotlib (win32 systems).Matplotlib. or b . please note that it will be overridden in your next install. eg red.0.1 Matplotlib also provides a couple of convenience functions for modifying rc settings. one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg # MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template # You can also deploy your own backend outside of matplotlib by # referring to the module name (which must be in the PYTHONPATH) as # ’module://my_backend’ backend : GTKAgg # if you are runing pyplot inside a GUI and your backend choice # conflicts. as are trailing comments. The matplotlib. you can either use .1 A sample matplotlibrc file ### MATPLOTLIBRC FORMAT # # # # # # # # # # # # # # # # # # # # This is a sample matplotlib configuration file .2. 0. If you edit it there. using keyword arguments: import matplotlib as mpl mpl. Release 1. or lines starting with a comment symbol. are ignored.a legal html color name. 5. blue. k. Blank lines. place it in HOME/. such as (1.5.rcsetup for details. If you want to keep a permanent local copy that will not be over-written.0) .a matplotlib color string. darkslategray #### CONFIGURATION BEGINS HERE # the default backend. There is some degree of validation when setting the values of rcParams. This file is best viewed in a editor which supports python mode syntax highlighting.0.rc() command can be used to modify multiple settings in a single group at once. such as ff00ff or #ff00ff . 5. #lines.sourceforge.solid_capstyle : projecting # butt|round|projecting #lines.solid_joinstyle : miter # miter|round|bevel #lines. like polygons or # circles.style property has three values: normal (or roman). Release 1.2.marker : None # the default marker #lines. # # The font. small-caps is equivalent # to using a font size of ’smaller’.linewidth : 1.g. Each of # these font families has a default list of font names in decreasing # order of priority associated with them. bitmaps.html for more # information on font properties. and ’monospace’ (e. Zapf-Chancery).net/api/font_manager_api.family property has five values: ’serif’ (e.linestyle : # solid line #lines. Western).0 # edge width in points #patch.Text.g. # ’sans-serif’ (e. # # The font.sourceforge.antialiased : True # render lines in antialised (no jaggies) ### PATCHES # Patches are graphical objects that fill 2D space. Times).1 #timezone : UTC # a pytz timezone string. # ’fantasy’ (e.Matplotlib.linewidth : 1.g.markeredgewidth : 0. etc reside #datapath : /home/jdhunter/mpldata ### LINES # See http://matplotlib.patches # information on patch properties #patch. # # The font. which are scalable fonts.5 # the line width around the marker symbol #lines.html#module-matplotlib.g.0. italic # or oblique. The oblique style will be used for italic.lines for more # information on line properties.0 # line width in points #lines. ’cursive’ (e.dash_capstyle : butt # butt|round|projecting #lines.net/api/artist_api.antialiased : True # render patches in antialised (no jaggies) ### FONT # # font properties used by text. This is where the matplotlib fonts. if it is not # present.dash_joinstyle : miter # miter|round|bevel #lines. or about 83% of the current font # size.html#module-matplotlib.facecolor : blue #patch.g. The 6 font properties used for font # matching are given below with their default values. For # TrueType fonts. Dynamic rc settings 25 .color : blue #lines.sourceforge.edgecolor : black #patch. See # http://matplotlib.variant property has two values: normal or small-caps.markersize : 6 # markersize.net/api/artist_api. eg US/Central or Europe/Paris # Where your matplotlib data lives if you installed to a non-default # location. Courier). See # http://matplotlib. Helvetica). in points #lines. Sand. Chicago.net/api/artist_api.style : normal #font. Special text sizes can be defined # relative to font. sans-serif. please inquire at the # matplotlib mailing list #text. medium.color : black ### LaTeX customizations. and narrower. # computer modern sans serif. Textile. etc. normal.Matplotlib. Century Schoolbook L.0..html#module-matplotlib.0 #font.org/Wiki/Cookbook/Matplotlib/UsingTex #text. #text.size property is the default font size for text. PLEASE DO NOT ASK FOR HELP # IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO. New Century Schoolbook. cursive #font.latex.Text. x-small. condensed. Western. Normal is the same as # 400. This # property is not currently implemented. Customizing matplotlib .serif : Bitstream Vera Serif.scipy. To configure # special text sizes tick labels. using the following values: xx-small. See http://www. larger. # zapf chancery. 200. # # The font. Utopia. charter. Lucida Grande. Courier. semi-condensed. Fixed ### TEXT # text properties used by text. monospace.usetex : False # use latex for all text handling. 300.1 # # The font. Verdana. computer modern typewriter # If another font is desired which can loaded using the # LaTeX \usepackage command. labels. # # The font.monospace : Bitstream Vera Sans Mono. 26 Chapter 5.cursive : Apple Chancery.sourceforge. # extra-condensed. Release 1. # small.fantasy : Comic Sans MS. bolder and lighter are relative values with # respect to the current weight. Ava #font. Nimbus Mono L.size controls default text sizes.stretch : normal # note that font.weight property has effectively 13 values: normal.family : sans-serif #font. # #font. bookman.text for more # information on text properties #text. The following fonts # are supported through the usual rc parameter settings: # new century schoolbook.preamble : # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES # AND IS THEREFORE UNSUPPORTED. See # http://matplotlib. courier. helvetica. Geneva.stretch property has 11 values: ultra-condensed.unicode : False # use "ucs" and "inputenc" LaTeX packages for handling # unicode strings. Helvetica.. Courier New. computer modern roman. xx-large. Charcoal. and bold is 700. given in pts. 900. Arial. extra-expanded.latex. ITC B #font.variant : normal #font. see the rc # settings for axes and ticks.. bold. # 12pt is the standard value.sans-serif : Bitstream Vera Sans.size. times. fantasy #font. semi-expanded. title. Impact.size : 12. or smaller #font. palatino. large. lighter. # bolder. # expanded. axes. . serif. Zapf Chancery. Lucid. x-large. 100. # avant garde. ultra-expanded. wider. Andale Mono.weight : medium #font. tt : monospace #mathtext.sf : sans #mathtext. An example: text.fontset is ’custom’. so beware of package collisions: color.net/api/axes_api. # default fontsizes for ticklabels. type1cm. Release 1. otherwise not.preamble : \usepackage{bm}. use symbols from the Computer Modern # fonts when a symbol can not be found in one of # the custom math fonts. # The following settings allow you to select the fonts in math mode. including the special name "regular" for the same font used in regular text.axes #axes.cache before testing and False to force correction off. #mathtext.facecolor : white # axes background color #axes.labelcolor : black 5.cal : cursive #mathtext.1 # # # # # # # # #text. geometry. None will try and guess based on your dvipng version This only #text.0. graphicx. #mathtext.0 # edge linewidth #axes. See # http://matplotlib.dvipnghack : None preamble is a comma separated list of LaTeX statements that are included in the LaTeX document preamble.hinting : True # If True.fontset : cm # Should be ’cm’ (Computer Modern). textcomp. # These settings are only used if mathtext.html#module-matplotlib. # affects the Agg backend.default : it # # # # The default font to use for math. # They map from a TeX font name to a fontconfig font pattern.hold : True # whether to clear the axes by default on #axes.it : serif:italic #mathtext.edgecolor : black # axes edge color #axes.fallback_to_cm : True # When True.Matplotlib. Dynamic rc settings 27 . Adobe Postscript (PSSNFS) font packages may also be loaded. ’stix’. Use True to correct and flush ~/. # Note that this "custom" mode is unsupported and may go away in the # future.\usepackage{euler} The following packages are always loaded with usetex. Can be any of the LaTeX font names. default tick sizes. ### AXES # default face and edge color.bf : serif:bold #mathtext.titlesize : large # fontsize of the axes title #axes.2.rm : serif #mathtext. text will be hinted.grid : False # display grid or not #axes. depending on your font settings # # # # # # some versions of dvipng don’t handle alpha channel properly.labelsize : medium # fontsize of the x any y labels #axes. and so on. # ’stixsans’ or ’custom’ #mathtext.matplotlib/tex.latex.linewidth : 1.sourceforge. r.org/wiki/Plus_sign#Plus_sig #axes.direction : in # direction: in or out #ytick.5 # grid color # dotted # in points : False # if True.isaxes : True #legend.size #ytick. or # web-style hex #polaraxes.minor.direction : : : : : : : 4 2 4 4 k medium in # # # # # # # major tick size in points minor tick size in points distance to major tick label in points distance to the minor tick label in points color of the tick labels fontsize of the tick labels direction: in or out ### GRIDS #grid.numpoints : 2 #legend.formatter. k # color cycle for plot lines # as list of string colorspecs: # single letter.0 # the following dimensions are #legend.major.handletextsep : 0.wikipedia.markerscale : 1.color : k # color of the tick labels #xtick.pad #ytick.5 #legend. etc) #axes. original in axes coords # the vertical space between the legend entries # the length of the legend lines # the space between the legend line and legend text # the border between the axes and legend edge #legend.fancybox : : : black : 0.pad : 0.major. use a rounded box for the # legend. long name.0 #legend. m.axespad : 0. c.borderpad : 0.major.size #ytick.major.Tick #xtick.color #grid. Release 1. 7 # use scientific notation if log10 # of the axis range is smaller than the # first or larger than the second #axes.color #ytick.unicode_minus : True # use unicode for the minus symbol # rather than hypen.size : 4 # major tick size in points #xtick.linewidth ### Legend #legend. the fractional whitespace inside the legend border # border whitspace in fontsize units # the relative size of legend markers vs.grid #axes3d.limits : -7. Customizing matplotlib .Matplotlib.html#matplotlib.pad : 4 # distance to the minor tick label in points #xtick.0.size : 2 # minor tick size in points #xtick.010 #legend.color_cycle : b.pad #ytick.minor.handlelen : 0. else a rectangle # the number of points in the legend line # deprecated.labelsep : 0.fontsize : large #legend.axis.minor. y. text. g.axisbelow # whether axis gridlines and ticks are below # the axes elements (lines.pad : 4 # distance to major tick label in points #xtick.02 #legend.grid : True : True # display grid on polar axes # display grid on 3d axes : False ### TICKS # see http://matplotlib.02 28 Chapter 5.sourceforge.05 #legend. See http://en.labelsize : medium # fontsize of the tick labels #xtick.1 #axes.net/api/axis_api.linestyle #grid.minor.labelsize #ytick. facecolor : 0. values in the range # 10000 to 100000 can improve speed slightly # and prevent an Agg rendering failure # when plotting very large data sets.top : 0. the size of the colormap lookup table lower | upper dashed # dashed | solid ### Agg rendering ### Warning: experimental.subplot.sourceforge.html#matplotlib. you may want a higher resolution. ### SAVING FIGURES #path.right : 0.net/api/figure_api. rectilinear axis-aligned paths will be snapped to # the nearest pixel when certain criteria are met.hspace : 0..subplot.2 #figure.2 ### IMAGES #image.subplot.left : 0.subplot. 2008/10/10 #agg.75 # figure facecolor. # It may cause minor artifacts.shadow : False ### FIGURE # See http://matplotlib.resample : False ### CONTOUR PLOTS #contour.2.75 is scalar gray #figure.dpi : 80 # figure dots per inch #figure.subplot. Release 1.9 #figure.lut : 256 #image.Matplotlib.Figure #figure.125 #figure.. simplify paths by removing "invisible" # points to reduce file size and increase rendering # speed #path. # especially if they are very gappy.1 #legend. though.1 #figure.9 #figure.figsize : 8. # paths will never be snapped.1 # The threshold of similarity below which # vertices will be removed in the simplification # process #path.interpolation : bilinear #image.origin : upper #image. 0. When False. or to make the figure # background white 5.aspect : equal #image.subplot. # the default savefig params can be different from the display params # Eg.negative_linestyle : All dimensions are fraction of the # # # # # # the the the the the the left side of the subplots of the figure right side of the subplots of the figure bottom of the subplots of the figure top of the subplots of the figure amount of width reserved for blank space between subplots amount of height reserved for white space between subplots # # # # # equal | auto | a number see help(imshow) for options gray | jet etc.cmap : jet #image.edgecolor : white # figure edgecolor # The figure subplot parameters.wspace : 0. Dynamic rc settings 29 .0.figure.simplify_threshold : 0.bottom : 0. # figure width or height #figure.simplify : True # When True.path. 6 # figure size in inches #figure.chunksize : 0 # 0 to disable.snap : True # When True. # A value of 20000 is probably a good # starting point. image_noscale : False #svg.fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType) # svg backend params #svg. # These objects can a filename. ps.level : silent # one of silent. #verbose. When submitting # problems to the mailing-list.report.1 #savefig.fileo : sys. Release 1. or ’auto’ : png # png.fonttype : 6000 : 3 # auto.edgecolor #savefig. Any level is # inclusive of all the levels below it. # xpdf intended for production of publication quality files. debug-annoying #verbose. helpful.stdout # a log filename.0.hardcopy = False # write raster image data directly into the svg file # suppress scaling of raster data embedded in SVG # embed character outlines in the SVG file # set this when you want to generate hardcopy docstring # Set the verbose flags.res #ps. B0-B10 # use of afm fonts. If your setting is "debug". # you’ll get all the debug and helpful messages. debug-annoying.useafm : False #ps. letter. eg --verbose-helpful. # # You can access the verbose instance in your code # from matplotlib import verbose.dpi #savefig.stderr 30 Chapter 5.compression : 6 # integer from 0 to 9 # 0 disables compression (good for debugging) #pdf.papersize : letter #ps. xpdf and ps2eps # dpi # Output Type 3 (Type3) or Type 42 (TrueType) # pdf backend params #pdf. The verbosity # levels are: silent. ghostscript or xpdf # Experimental: may produce smaller files. legal. ledger. # but requires ghostscript.Matplotlib. Customizing matplotlib .distiller. or a filehandle like sys.extension #cairo. # # You can override the rc default verbosity from the command line by # giving the flags --verbose-LEVEL where LEVEL is one of the legal # levels. pdf. please set verbose to "helpful" or "debug" # and paste the output into your report. # # The "fileo" gives the destination for any calls to verbose. debug.embed_char_paths : True # docstring params #docstring.window_focus : False # ps backend params #ps. sys. This controls how much information # matplotlib gives you at runtime and where it goes. helpful.facecolor #savefig. svg # tk backend params #tk. results in small files # can be: None.image_inline : True #svg. A0-A10.format : : : : 100 white white auto # # # # figure dots per inch figure facecolor when saving figure edgecolor when saving what extension to use for savefig(’foo’).stdout or sys.usedistiller : False # Maintain shell focus for TkAgg #ps. debug.stdout. sourceforge. (i.grid : g #keymap. k #keymap.2. v #keymap. Release 1.forward : right.directory : ’’ 5.1 # Event keys to interact with figures/plots via keyboard.. backspace #keymap. c.back : left. fullscreen : ’’) #keymap.zoom : o #keymap.xscale : L.download to False and examples.Matplotlib. but sometimes you want to avoid that.net/svnroot/matplotlib/trunk/sample_data # False to bypass downloading mechanism # directory to look in if download is false #examples.yscale : l #keymap.pan : p #keymap.fullscreen : f #keymap.directory to the directory where you have a checkout of https://matplotlib. Dynamic rc settings 31 . Various examples download some data from the Matplotlib svn repository to avoid distributing extra files. In that case set examples. # Customize these settings according to your needs. # Leave the field(s) empty if you don’t need a key-map.e. home #keymap.download : True #examples.home : h.all_axes : a # # # # # # # # # # # # # # # # # toggling home or reset mnemonic forward / backward keys to enable left handed quick navigation pan mnemonic zoom mnemonic saving current figure switching on/off a grid in current axes toggle scaling of y-axes (’log’/’linear’) toggle scaling of x-axes (’log’/’linear’) enable all axes Control downloading of example data.0. r.save : s #keymap.svn. Customizing matplotlib . Release 1.0.Matplotlib.1 32 Chapter 5. in practice it can be tricky. so when you start ipython in the pylab mode. While this is simple in concept. or the marker style of a line. after changing the xlabel().An enhanced Interactive Python. ipython also turns on interactive mode for you. and is matplotlib aware. eg. matplotlib defers drawing until the end of the script because drawing can be an expensive operation. 100) it sets everything up for you so interactive plotting works as you would expect it to. ipython will turn off interactive mode during a run command. Note in the example above that we did not import any matplotlib names because in pylab mode. For more information.CHAPTER SIX USING MATPLOTLIB IN A PYTHON SHELL By default. In [1]: x = randn(10000) In [2]: hist(x. and you may not want to update the plot every time a single property is changed. and also provides a matplotlib aware run command to run matplotlib scripts efficiently. which causes every pyplot command to trigger a figure update.1 Ipython to the rescue Fortunately. only once after all the properties have changed. call plot() and your data appears in the figure window. ipython will import them automatically. johnh@flag:~> ipython -pylab Python 2. and there are some tricks to make the applications work right in a python shell. Call figure() and a figure window pops up. type ’help(pylab)’. Apr 12 2008.5 (#4. ipython. Welcome to pylab. But when working from the python shell.0 -. you usually do want to update the plot with every command. and then restore the interactive state at the end of the run so you can continue tweaking the figure manually. because matplotlib is a graphical user interface application under the hood. 33 . has figured out all of these tricks.9. 6.4. 09:09:16) IPython 0. an enhanced interactive python shell. a matplotlib-based Python environment. Using matplotlib in a python shell . that uses the Tkinter user interface toolkit. you can use matplotlib from an arbitrary python shell. then every pyplot command triggers a draw. With the TkAgg backend. with pylab support. eg the plainole standard python interactive interpreter.1 There has been a lot of recent work to embed ipython. The pyplot interface provides 4 commands that are useful for interactive control. color=’green’) draw() # force a draw savefig(’alldone’. then the figure state is updated on every plot command. so check on the ipython mailing list for the latest status. and this is the tricky part that ipython solves for all the major toolkits that matplotlib supports. Note.2 Other python interpreters If you can’t use ipython.Matplotlib. and still want to use matplotlib/pylab from an interactive python shell. The solution is to run the GUI in a separate thread. 6. in batch mode. Then: >>> from pylab import * >>> plot([1. interactive mode can be slow since it redraws the figure with each command. but will only be drawn on explicit calls to draw(). So you may want to think carefully before making this the default behavior.3]) >>> xlabel(’hi mom’) should work out of the box.0. 6. There are reports that upcoming versions of pygtk will place nicely with the standard python shell.2. the situation is complicated by the GUI mainloop which takes over the entire process. you are going to need to understand what a matplotlib backend is What is a backend?. into various GUI applications.3 Controlling interactive updating The interactive property of the pyplot interface controls whether a figure canvas is drawn on every pyplot command. If interactive is False. When interactive is True. or the interpreter in your favorite IDE. you may want to turn matplotlib’s interactive setting off temporarily to avoid the performance hit: >>> >>> >>> >>> >>> >>> #create big-expensive-figure ioff() # turn updates off title(’now how much would you pay?’) xticklabels(fontsize=20. Just set your backend : TkAgg and interactive : True in your matplotlibrc file (see Customizing matplotlib) and fire up python. so stay tuned. For other user interface toolkits and their corresponding matplotlib backends. ie when making figures from scripts. isinteractive() returns the interactive setting True|False ion() turns interactive mode on ioff() turns interactive mode off draw() forces a figure redraw When working with a big figure in which drawing is expensive. dpi=300) 34 Chapter 6. Release 1. 1 >>> close() >>> ion() # turn updating back on >>> plot(rand(20). mec=’r’. Controlling interactive updating 35 .3.0. mfc=’g’. ls=’--’. ms=40. Release 1.Matplotlib. mew=4. lw=3) 6. Matplotlib. Release 1.0. Using matplotlib in a python shell .1 36 Chapter 6. add an axis label to the x-axis. truetype support for raster and vector outputs.text() in the API.suptitle() in the API.axes. which can bew configured with a variety of font and other properties.Axes.Axes. • xlabel() . matplotlib.text.Text() instance. 7. matplotlib. All of these functions create and return a matplotlib. antialiased fonts.axes.set_xlabel() in the API. eg for postscript or PDF. newline separated text with arbitrary rotations. with optional arrow. • annotate() .add text at an arbitrary location to the Figure. thanks to Paul Barrett.Axes.Axes.1 Text introduction matplotlib has excellent text support. matplotlib.Figure. font weight. And significantly for those interested in mathematical or scientific figures. matplotlib includes its own matplotlib.set_title() in the API. matplotlib implements a large number of TeX math symbols and commands. 37 . Because we embed the fonts directly in the output documents.Figure. to the Axes .add an axis label to the y-axis.add a title to the Figure.2 Basic text commands The following commands are used to create text in the pyplot interface • text() . W3C compliant font finding algorithm.add a title to the Axes. The example below shows all of these commands in action.axes.add an annotation. matplotlib.figure.font_manager. You have total control over every text property (font size.add text at an arbitrary location to the Axes.axes. • ylabel() . • suptitle() . matplotlib.text() in the API. that look good even at small raster sizes. freetype2 support produces very nice. • figtext() . including mathematical expressions. • title() .axes.Axes. etc) with sensible defaults set in the rc file. which implements a cross platform. text location and color.annotate() in the API.CHAPTER SEVEN WORKING WITH TEXT 7.set_ylabel() in the API. and unicode support. what you see on the screen is what you get in the hardcopy.figure. matplotlib. matplotlib. to support mathematical expressions anywhere in your figure. 85) ax.add_subplot(111) fig. fontsize=14.show() 7.pyplot as plt fig = plt. ’boxed italics text in data coords’. shrink=0. Release 1. ’pad’:10}) ax. ’o’) ax.01. Working with text . fontweight=’bold’) ax = fig.transAxes. ’alpha’:0. 0. unicode(’unicode: Institut f\374r Festk\366rperphysik’. style=’italic’. verticalalignment=’bottom’. 0.05)) ax. xy=(2.text(3.set_ylabel(’ylabel’) ax.suptitle(’bold figure suptitle’. r’an equation: $E=mc^2$’. color=’green’. ’colored text in axes coords’.subplots_adjust(top=0. xlabel() and text()). fontsize=15) ax. horizontalalignment=’right’. [1]. 10]) plt. 1).1 # -*.coding: utf-8 -*import matplotlib. 4).Matplotlib.text(0. 38 Chapter 7.set_title(’axes title’) ax. fontsize=15) ax. 10. arrowprops=dict(facecolor=’black’. ’latin-1’)) ax. 8.text.annotate(’annotate’. xytext=(3.text(3. 6.text(2.plot([2].Text instances have a variety of properties which can be configured via keyword arguments to the text commands (eg title(). transform=ax.3 Text properties and layout The matplotlib.figure() fig.set_xlabel(’xlabel’) ax.axis([0.95.5. bbox={’facecolor’:’red’.0. 2. transform. Text properties and layout | False] weight or fontweight [ ‘normal’ | ‘bold’ | ‘heavy’ | ‘light’ | ‘ultrabold’ | ‘ultralight’] x float y float 39 .Matplotlib.font_manager.3..FontProperties instance horizontalalignment or ha [ ‘center’ | ‘right’ | ‘left’ ] label any string linespacing float multialignment [’left’ | ‘right’ | ‘center’ ] name or fontname string eg. [’Sans’ | ‘Courier’ | ‘Helvetica’ .transform transformation instance variant [ ‘normal’ | ‘small-caps’ ] verticalalignment or va [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] visible [True 7. a Patch color any matplotlib color family [ ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] fontproperties a matplotlib..Bbox instance clip_on [True | False] clip_path a Path instance and a Transform instance.] picker [None|float|boolean|callable] position (x.0. Release 1. ‘x-large’ ] style or fontstyle [ ‘normal’ | ‘italic’ | ‘oblique’] text string or anything printable with ‘%s’ conversion transform a matplotlib.1 10 8 ylabel 6 4 2 00 2 bold figure suptitle axes title boxed italics text in data coords an equation: E = mc2 annotate unicode: Institut für Festkörperphysik colored text in axes coords 4 xlabel 6 8 10 Property Value Type alpha float backgroundcolor any matplotlib color bbox rectangle prop dict plus key ‘pad’ which is a pad in points clip_box a matplotlib.y) rotation [ angle in degrees ‘vertical’ | ‘horizontal’ size or fontsize [ size in points | relative size eg ‘smaller’. bottom. . transform=ax. The use of transform=ax.transAxes) 40 Chapter 7. clip_on=False ) ax.text(left. center or right justified. Here is an example which uses the text() command to show the various alignment possibilities. ’center top’.5 right = left + width top = bottom + height fig = plt. center or right side of the text bounding box.text(right. horizontalalignment=’center’. transform=ax. . ’left bottom’.transAxes) ax.transAxes) ax. horizontalalignment=’right’. verticalalignment=’bottom’. verticalalignment.text(right. transform=ax. verticalalignment=’top’.transAxes. transform=ax. width = . import matplotlib. Working with text .1 the upper right. fill=False.pyplot as plt import matplotlib. verticalalignment=’top’. bottom. with 0. horizontalalignment=’right’. horizontalalignment=’left’.text(right. bottom. height = .transAxes throughout the code indicates that the coordinates are given relative to the axes bounding box. and multialignment.1 You can layout text with the alignment arguments horizontalalignment.transAxes) ax. Release 1. transform=ax.1.add_patch(p) ax.text(left. verticalalignment controls whether the y positional argument for the text indicates the bottom. ’right top’. center or top side of the text bounding box.0.Rectangle( (left. bottom).patches as patches # build a rectangle in axes coords left. top.figure() ax = fig.Matplotlib.add_axes([0.25.0 is bottom left and 1. ’right bottom’.1 is upper right p = patches. width. ’left top’. top. multialignment.transAxes) ax.0 being the lower left of the axes and 1. horizontalalignment=’left’. horizontalalignment controls whether the x positional argument for the text indicates the left.1]) # axes coordinates are 0.5 bottom. transform=ax.0. verticalalignment=’bottom’.25. height. verticalalignment=’top’. for newline separated strings only. controls whether the different lines are left. if you use the STIX fonts you should also set ps. ’centered’.transAxes) ax. verticalalignment=’center’. transform=ax.0.5*(left+right). top.fonttype and pdf. since matplotlib ships its own TeX expression parser.set_axis_off() plt. color=’red’. STIX fonts (with are designed to blend well with Times) or a Unicode font that you provide. rotation=’vertical’.text(right. ’rotated\nwith newlines’. horizontalalignment=’center’. 0.transAxes) ax. transform=ax.show() 7. 0.Matplotlib.transAxes) ax.5*(bottom+top). horizontalalignment=’center’. ’middle’. Otherwise some characters will not be visible. horizontalalignment=’center’. not 42. layout engine and fonts.5*(bottom+top). The layout engine is a fairly direct adaptation of the layout algorithms in Donald Knuth’s TeX.text(left.fontset (see Customizing matplotlib) Note: On “narrow” builds of Python. ’right center’.5*(bottom+top).text(left. horizontalalignment=’right’. as in TeX. rotation=’vertical’.transAxes) ax. You should use raw strings (preceed the quotes with an ’r’). transform=ax. verticalalignment=’center’. verticalalignment=’center’. 0.4 Writing mathematical expressions You can use a subset TeX markup in any matplotlib text string by placing it inside a pair of dollar signs ($). Release 1. so the quality is quite good (matplotlib also provides a usetex option for those who do want to call out to TeX to generate their text (see Text rendering With LaTeX). verticalalignment=’center’.1 ax. transform=ax. 0. Note that you do not need to have TeX installed. and surround the math text with dollar signs ($). fontsize=20. The mathtext font can be selected with the customization variable mathtext. Writing mathematical expressions 41 . 7.text(0. verticalalignment=’center’. transform=ax. rotation=’vertical’.5*(bottom+top).4.transAxes) ax. Any text element can use math text. Regular text and mathtext can be interleaved within the same string. horizontalalignment=’left’. Mathtext can use the Computer Modern fonts (from (La)TeX).fonttype to 3 (the default). rotation=45.text(left. ’left center’. See the usetex tutorial for more information. Working with text centered . Release 1. This is a small change from regular TeX.Matplotlib. it will be displayed verbatim as a dollar sign.usetex flag.0. Therefore.00”. Whereas this: # math text plt.title(r’$\alpha > \beta$’) produces “α > β”. 42 Chapter 7. the text outside does not.g.title(’alpha > beta’) produces “alpha > beta”. Note: Mathtext should be placed between a pair of dollar signs ($). In particular. To make it easy to display monetary values. characters such as: # $ % & ~ _ ^ \ { } \( \) \[ \] have special meaning outside of math mode in TeX.1 wit ro right center h ne tate left center wli d ne s right bottom right top middle left bottom left top center top Here is a simple example: # plain text plt. “$100. where the dollar sign in non-math text would have to be escaped (‘$’). e. if a single dollar sign is present in the entire string. these characters will behave differently depending on the rcParam text. Note: While the syntax inside the pair of dollar signs ($) aims to be TeX-like. to write the sum of xi from 0 to ∞.0.\frac{1}{x}}{4}$’ (7. For example.4) 4 Note that special care needs to be taken to place parentheses and brackets around fractions.6) 43 . use the ’_’ and ’^’ symbols: r’$\alpha_i > \beta_i$’ αi > βi (7. binomials and stacked numbers can be created with the \frac{}{}.4.1 Subscripts and superscripts To make subscripts and superscripts.2) 7.\frac{1}{x}}{4})$’ 5− 1 x ) (7. \binom{}{} and \stackrel{}{} commands.1 7.2 Fractions.Matplotlib. Doing things the obvious way produces brackets that are too small: r’$(\frac{5 .1) Some symbols automatically put their sub/superscripts under and over the operator.4. Writing mathematical expressions (7. you could do: r’$\sum_{i=0}^\infty x_i$’ ∞ xi i=0 (7. binomials and stacked numbers Fractions. respectively: r’$\frac{3}{4} \binom{3}{4} \stackrel{3}{4}$’ produces 3 3 3 4 4 4 Fractions can be arbitrarily nested: r’$\frac{5 .3) produces 5− 1 x (7. Release 1.4.5) 4 The solution is to precede the bracket with \left and \right to inform the parser that those brackets encompass the entire object: ( r’$\left(\frac{5 .\frac{1}{x}}{4}\right)$’ 1 x 5 − 4 7. many commonly used function names that are typeset in a Roman font have shortcuts. by setting it to regular.11) Result Roman Italic Typewriter CALLIGRAPHY Chapter 7. for example. Note in the example above the caligraphy A is squished into the sin.3 Radicals Radicals can be produced with the \sqrt[]{} command. “sin” is in Roman font.9) More conveniently.1 7.4 Fonts The default font is italics for mathematical symbols.0. So the expression above could be written as follows: r’$s(t) = \mathcal{A}\sin(2 \omega t)$’ s(t) = A sin(2ωt) (7. to use the same font as regular non-math text for math text. and the amplitude “A” is in calligraphy font. and can not contain layout commands such as fractions or sub/superscripts: r’$\sqrt[3]{x}$’ √ 3 x (7.10) Here “s” and “t” are variable in italics font (default).4. eg. enclose the text in a font command: r’$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$’ s(t) = Asin(2ωt) (7.7) Any base can (optionally) be provided inside square brackets. Note that the base must be a simple expression. This is useful.4.8) 7. Note: This default can be changed using the mathtext. to write “sin” in a Roman font. For example: r’$\sqrt{2}$’ √ 2 (7. Release 1.Matplotlib. You can use a spacing command to add a little whitespace between them: s(t) = \mathcal{A}\/\sin(2 \omega t) s(t) = A sin(2ωt) The choices available with all fonts are: Command \mathrm{Roman} \mathit{Italic} \mathtt{Typewriter} \mathcal{CALLIGRAPHY} 44 (7.default rcParam. To change fonts. Working with text . . you can then set the following parameters. 7.. you can use \mathdefault{. There are a number of limitations to this approach.} to use the font used for regular text outside of mathtext. you also have the choice of: Command \mathbb{blackboard} \mathrm{\mathbb{blackboard}} \mathfrak{Fraktur} \mathsf{sansserif} \mathrm{\mathsf{sansserif}} Result Fraktur sansserif sansserif There are also three global “font sets” to choose from.fontset to custom. and should be considered an experimental feature for patient users only. This method is fairly tricky to use.. but it can be useful to make math expressions blend well with other text in the plot.fontset parameter in matplotlibrc.1 When using the STIX fonts. By setting the rcParam mathtext. which control which font file to use for a particular set of math characters.} or its alias \mathregular{.4. Custom fonts mathtext also provides a way to use custom fonts for math. Release 1. which are selected using the mathtext.Matplotlib. most notably that far fewer symbols will be available. cm: Computer Modern (TeX) stix: STIX (designed to blend well with Times) stixsans: STIX sans-serif Additionally. Writing mathematical expressions 45 .0.. Note that in the following \imath is used to avoid the extra dot over the i: r"$\hat i\ \ \hat \imath$" ˆ ı i ˆ (7.5 Accents An accent command may precede any symbol to add an accent above it.0.it mathtext.Matplotlib.a \grave a or \‘a \hat a or \^a \tilde a or \~a \vec a Result a ´ a ¯ a ˘ a ¨ a ˙ a ` a ˆ a ˜ a In addition.12) 7. If you want to use a math symbol that is not contained in your custom fonts.tt mathtext. Working with text . 7.1 Parameter mathtext. such as Greek.cal mathtext.bf mathtext. 46 Chapter 7.4. and many fonts may not have glyphs in the correct place for mathtext. there are two special accents that automatically adjust to the width of the symbols below: Command \widehat{xyz} \widetilde{xyz} Result xyz xyz Care should be taken when putting accents on lower-case i’s and j’s.fallback_to_cm to True which will cause the mathtext system to use characters from the default Computer Modern fonts whenever a particular character can not be found in the custom font. as in \infty. you can set the rcParam mathtext. Command \acute a or \’a \bar a \breve a \ddot a or \"a \dot a or \. Release 1.6 Symbols You can also use a large number of the TeX symbols.rm mathtext. Note that the math glyphs specified in Unicode have evolved over time. \sum. The fonts used should have a Unicode mapping in order to find any non-Latin characters.4. \int. \leftarrow.sf Corresponds to \mathit{} or default italic \mathrm{} Roman (upright) \mathtt{} Typewriter (monospace) \mathbf{} bold italic \mathcal{} calligraphic \mathsf{} sans-serif Each parameter should be set to a fontconfig font descriptor (as defined in the yet-to-be-written font chapter). There are long and short forms for some of them. Matplotlib.0.4.1 Lower-case Greek α \alpha \epsilon λ \lambda π \pi θ \theta \varpi ζ \zeta Upper-case Greek ∆ \Delta Ψ \Psi \nabla Hebrew ℵ \aleph Delimiters // ↓ \downarrow \rangle | \vert Big symbols \bigcap \biguplus \oint Standard function names Pr \Pr arg \arg coth \coth dim \dim inf \inf lim inf \liminf max \max sinh \sinh arccos \arccos cos \cos csc \csc exp \exp ker \ker lim sup \limsup min \min sup \sup arcsin \arcsin cosh \cosh deg \deg gcd \gcd lg \lg ln \ln sec \sec tan \tan arctan \arctan cot \cot det \det hom \hom lim \lim log \log sin \sin tanh \tanh \bigcup \bigvee \prod \bigodot \bigwedge \sum \bigoplus \coprod \bigotimes \int [[ \langle \rceil { \{ ⇓ \Downarrow \lceil \rfloor \| ⇑ \Uparrow \lfloor \ulcorner } \} \Vert \llcorner ↑ \uparrow ]] \ \backslash \lrcorner \urcorner || \beth \daleth \gimel Γ \Gamma Σ \Sigma Λ \Lambda Θ \Theta Ω \Omega Υ \Upsilon Φ \Phi Ξ \Xi Π \Pi \mho β \beta η \eta µ \mu ψ \psi υ \upsilon \varrho χ \chi γ \gamma ν \nu ρ \rho ε \varepsilon ς \varsigma δ \delta ι \iota ω \omega σ \sigma κ \varkappa ϑ \vartheta \digamma κ \kappa φ \phi τ \tau ϕ \varphi ξ \xi Binary operation and relation symbols 7. Writing mathematical expressions 47 . Release 1. Matplotlib.1 \Bumpeq \Doteq \Supset ≈ \approx \asymp \backsimeq \between \bigtriangleup ⊥ \bot \boxminus • \bullet · \cdot \coloneq \curlyeqprec \curlywedge ‡ \ddag \divideontimes \dotplus \eqcolon \eqslantless \frown \geqslant \gnapprox \gtrapprox \gtreqqless ∈ \in ≤ \leq \lessapprox \lesseqqgtr \ll \lneqq | \mid \nVDash \ncong \neq \ngtr \nless \nparallel \nsubset \nsupset \Cap \Join \Vdash \approxeq \backepsilon \barwedge \bigcirc \blacktriangleleft \bowtie \boxplus \bumpeq ◦ \circ \cong \curlyeqsucc † \dag \diamond \doteq \doublebarwedge \eqsim ≡ \equiv \Cup \Subset \Vvdash ∗ \ast \backsim \because \bigtriangledown \blacktriangleright \boxdot \boxtimes ∩ \cap \circeq ∪ \cup \curlyvee \dashv ÷ \div \doteqdot \eqcirc \eqslantgtr \fallingdotseq ≥ \geq \gg \gneqq \gtrdot \gtrless \intercal \leqq \lessdot \lessgtr \lll \lnsim |= \models \nVdash \ne \nequiv \ni \nmid \nprec \nsubseteq \nsupseteq \geqq \ggg \gnsim \gtreqless \gtrsim \leftthreetimes \leqslant \lesseqgtr \lesssim \lnapprox \ltimes \mp \napprox \neq \ngeq \nleq \notin \nsim \nsucc \ntriangleleft 48 Chapter 7. Working with text . Release 1.0. Writing mathematical expressions .1 \ntrianglelefteq \nvDash \ominus ⊗ \otimes \pitchfork \precapprox \precnapprox ∝ \propto \rtimes / \slash \sqcup \sqsubseteq \sqsupseteq ⊆ \subseteq \subsetneqq \succcurlyeq \succnsim ⊇ \supseteq \supsetneqq \top \triangleq \uplus \vartriangleleft ∨ \vee \wr Arrow symbols \ntriangleright \nvdash ⊕ \oplus \parallel ± \pm \preccurlyeq \precnsim \rightthreetimes ∼ \sim \smile \sqsubset \sqsupset \star \subseteqq \succ \succeq \succsim \supseteqq ∴ \therefore \triangleleft \triangleright \vDash \vartriangleright \veebar \ntrianglerighteq \odot \oslash ⊥ \perp \prec \preceq \precsim \risingdotseq \simeq \sqcap \sqsubset \sqsupset ⊂ \subset \subsetneq \succapprox \succnapprox ⊃ \supset \supsetneq × \times \trianglelefteq \trianglerighteq ∝ \varpropto \vdash ∧ \wedge ⇓ \Downarrow ⇔ \Leftrightarrow ⇐= \Longleftarrow =⇒ \Longrightarrow \Nearrow ⇒ \Rightarrow \Rsh \Swarrow \Updownarrow \circlearrowright \curvearrowright \dashrightarrow \downdownarrows \downharpoonright → \hookrightarrow ← \leftarrow \leftharpoondown \leftleftarrows \leftrightarrows \leftrightsquigarrow ⇐ \Leftarrow \Lleftarrow ⇐⇒ \Longleftrightarrow \Lsh \Nwarrow \Rrightarrow \Searrow ⇑ \Uparrow \circlearrowleft \curvearrowleft \dashleftarrow ↓ \downarrow \downharpoonleft ← \hookleftarrow \leadsto \leftarrowtail \leftharpoonup ↔ \leftrightarrow \leftrightharpoons \leftsquigarrow 49 7.Matplotlib.0. Release 1.4. . Unicode characters can also be used: ur’$\u23ce$’ 50 Chapter 7. Release 1. \vdots . . . Working with text .Matplotlib.0. . \ddots ∅ \emptyset \flat ♥ \heartsuit \iint ∞ \infty \measuredangle \nexists \prime \sphericalangle ∅ \varnothing ℘ \wp Å \AA \Im § \S \bigstar \blacktriangledown \circledR \complement ♦ \diamondsuit ð \eth ∀ \forall \hslash \iint \jmath \natural \oiiint \sharp \ss \vartriangle \yen \Finv ¶ \P ∠ \angle \blacksquare · · · \cdots \circledS © \copyright \ell ∃ \exists \hbar \iiint ı \imath . \ldots ¬ \neg ∂ \partial ♠ \spadesuit \triangledown . If a particular symbol does not have a name (as is true of many of the more obscure symbols in the STIX fonts).1 ←− \longleftarrow −→ \longmapsto \looparrowleft → \mapsto \nLeftarrow \nRightarrow \nleftarrow \nrightarrow → \rightarrow \rightharpoondown \rightleftarrows \rightleftharpoons \rightrightarrows \rightsquigarrow \swarrow \twoheadleftarrow ↑ \uparrow \updownarrow \upharpoonright ←→ \longleftrightarrow −→ \longrightarrow \looparrowright \multimap \nLeftrightarrow \nearrow \nleftrightarrow \nwarrow \rightarrowtail \rightharpoonup \rightleftarrows \rightleftharpoons \rightrightarrows \searrow → \to \twoheadrightarrow \updownarrow \upharpoonleft \upuparrows Miscellaneous symbols $ \$ \Game \Re \backprime \blacktriangle \checkmark ♣ \clubsuit . . 01) s = np. 0.s) plt. fontsize=20) plt.pi*t) plt.4.0.0 0.6. -0. r’$\mathcal{A}\mathrm{sin}(2 \omega t)$’.5 1. fontsize=20) plt.title(r’$\alpha_i > \beta_i$’.6. Text rendering With LaTeX 51 . 0.0 7.5 volts (mV) 0.ylabel(’volts (mV)’) 1. Release 1.0 time (s) xi 1. fontsize=20) plt.xlabel(’time (s)’) plt.plot(t. This option is available with the following backends: • Agg 7.7 Example Here is an example illustrating many of these features in context.text(1.0 0.pyplot as plt t = np.5 Text rendering With LaTeX Matplotlib has the option to use LaTeX to manage all text layout. r’$\sum_{i=0}^\infty x_i$’.0.0 αi >βi Asin(2ωt) ∞ i =0 0.text(0.arange(0.0 0.5 1.6.0.5.1 7.sin(2*np.Matplotlib.5 2. 2. import numpy as np import matplotlib. cos. show 52 Chapter 7. Computer Modern Roman Helvetica. The first time you run a script you will see a lot of output from tex and associated tools.usetex : True in your rc settings.cursive font.texmanager. pi from matplotlib. The next time.60 or later is recommended). the run may be silent.html properly installed on your system. which can be changed using rc settings. The results can be striking.1 • PS • PDF The LaTeX option is activated by setting text. dvipng (which may be included with your LaTeX installation). savefig. the Computer Modern fonts are used by default. and requires that you have tex and the other dependencies described at http://matplotlib. title. usetex=True) Here is the standard example.’serif’:[’Palatino’])) rc(’text’. Palatino.usetex : : : : : serif Times. math packages.) can be used.usetex is set. xlabel. plot. while the other Adobe serif fonts make use of the Computer Modern math fonts. Avant Garde.monospace text. Times and Palatino each have their own accompanying math fonts. This works currently on the agg and ps backends.sans-serif font.**{’family’:’serif’.sf. To use LaTeX and select Helvetica as the default font.tex. since different LaTeX packages (font packages. axes. tex_demo. \ grid.family font.serif font.pyplot import figure.net/matplotlib. Here is an example matplotlibrc file: font. The executables for these external dependencies must all be located on your PATH.’sans-serif’:[’Helvetica’]}) ## for Palatino and other serif fonts use: #rc(’font’. New Century Schoolbook. All of the other fonts are Adobe fonts. and Ghostscript (GPL Ghostscript 8. If the fonts are not specified. ylabel. etc.py: #!/usr/bin/env python """ You can use TeX to render all of your matplotlib text if the rc parameter text.0. especially when you take care to use the same fonts in your figures as in the main document.**{’family’:’sans-serif’. without editing matplotlibrc use: from matplotlib import rc rc(’font’. Text handling with matplotlib’s LaTeX support is slower than matplotlib’s very capable mathtext. as a lot of the information is cached in ~/. Computer Modern Sans serif Zapf Chancery Courier. See the PSNFSS documentation for more details. but is more flexible. Bookman. Working with text . Computer Modern Typewriter : true The first valid font in each family is the one that will be loaded.Matplotlib. Release 1. There are a couple of options to mention.cache """ from matplotlib import rc from numpy import arange. Matplotlib’s LaTeX support requires a working LaTeX installation. 0 Note that display math mode ($$ e=mc^2 $$) is not supported.8 1.7]) t = arange(0. Text rendering With LaTeX 53 .4 time (s) 0. Note: Certain characters require special escaping in TeX.0 1. figsize=(6.0 0.4)) ax = axes([0.01.0 ∞ n=1 −eiπ ! 2n voltage (mV) 2.8. 0.5.0+0. 0.fontsize=16) title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!".1 rc(’text’. as in tex_demo. such as: # $ % & ~ _ ^ \ { } \( \) \[ \] Therefore. will produce the same results.5 1.1. fontsize=16. 0.Matplotlib.6 0. family=’serif’) figure(1. 1. 0. color=’r’) grid(True) savefig(’tex_demo’) show() TEX is Number 3.py.0.1. these characters will behave differently depending on the rcParam text.usetex flag. s) xlabel(r’\textbf{time (s)}’) ylabel(r’\textit{voltage (mV)}’.5 2.0. Release 1.0 0.01) s = cos(2*2*pi*t)+2 plot(t. but adding the command \displaystyle. 7.2 0. usetex=True) rc(’font’. figsize=(6.0+0.usetex’]=True rcParams[’text.Matplotlib. xlabel. fontsize=16) title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!".7]) t = arange(0.01. 0. title.1 usetex with unicode It is also possible to use unicode strings with the LaTeX text manager. Release 1. dvipng and ghostscript executables.pyplot import figure.usedistiller rc setting to xpdf. so it scales properly. 0. pi from matplotlib.latex.5. plot.5. This alternative produces postscript without rasterizing text.0. This step produces results which may be unacceptable to some users. 54 Chapter 7. 7. which requires Poppler or Xpdf.1. and searched text in pdf documents.3 Possible hangups • On Windows. axes. One workaround is to to set ps. 1. here is an example taken from tex_unicode_demo.4)) ax = axes([0. cos. the default behavior of matplotlib is to distill the output.coding: utf-8 -*""" This demo is tex_demo. which are not scalable like standard postscript. \ grid. See that file for more information. the PATH environment variable may need to be modified to include the directories containing the latex.res to a higher value (perhaps 6000) in your rc settings. fontsize=16. which will produce larger files but may look better and scale reasonably.1 7. because the text is coarsely rasterized and converted to bitmaps. and the text is not searchable.1.py modified to have unicode. Working with text . 0. See environment-variables and setting-windowsenvironment-variables for details.2 Postscript options In order to produce encapsulated postscript files that can be embedded in a new LaTeX document. ylabel. which removes some postscript operators used by LaTeX that are illegal in an eps file. color=’r’) grid(True) show() 7.5. can be edited in Adobe Illustrator.01) s = cos(2*2*pi*t)+2 plot(t. can be activated by changing the ps.0.py: #!/usr/bin/env python # -*. 0. savefig. A better workaround.8. show figure(1. s) xlabel(r’\textbf{time (s)}’) ylabel(ur’\textit{Velocity (\u00B0/sec)}’.unicode’]=True from numpy import arange. """ from matplotlib import rcParams rcParams[’text.distiller. If you don’t know where to find • Make sure LaTeX. • Some progress has been made so matplotlib uses the dvi files directly for text layout.Matplotlib. Text rendering With LaTeX 55 .6 0.0.8 1.5 1.2 0. This allows latex to be used for text layout with the pdf and svg backends. go to MiKTeX/Options and update your format files • The fonts look terrible on screen.4 Troubleshooting • Try deleting your . 7.5. if you get odd *Agg and PNG results.0 ∞ n=1 −eiπ ! 2n Velocity (°/sec) 2. please try upgrading to the latest release before reporting problems to the list.matplotlib.0 0. dvipng and ghostscript are each working and on your PATH. as well as the *Agg and PS backends.1 TEX is Number 3. .0 1.0 • Using MiKTeX with Computer Modern fonts. the base texlive install does not ship with the type1cm package.5. In the future. You may need to install some of the extra packages to get all the goodies that come bundled with other latex distributions.dvipnghack : True in your matplotlibrc file. 7. • On Ubuntu and Gentoo. see .5 2.0 0. You are probably running Mac OS. Set text.cache directory.matplotlib/tex. Release 1. that your LaTeX syntax is valid and that you are using raw strings if necessary to avoid unintended escape sequences. • Make sure what you are trying to do is possible in a LaTeX document. If possible. a latex installation may be the only external dependency.4 time (s) 0. and there is some funny business with older versions of dvipng on the mac. • Most problems reported on the mailing list have been cleared up by upgrading Ghostscript.matplotlib directory location. 2) plt.0 is lower left of figure and 1. Working with text .1 is upper right use the axes data coordinate system For example to place the text coordinates in fractional axes coordinates. There are a variety of other coordinate systems one can choose – you can specify the coordinate system of xy and xytext with one of the following strings for xycoords and textcoords (default is ‘data’) argument ‘figure points’ ‘figure pixels’ ‘figure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ coordinate system points from the lower left corner of the figure pixels from the lower left corner of the figure 0.Matplotlib. ) ax.6 Annotating text For a more detailed introduction to annotations.1 is lower left of axes and 1. 0. see Annotating Axes. In an annotation. textcoords=’axes fraction’. and lots of ways to cause problems. xytext=(3. arrowprops=dict(facecolor=’black’. xy=(2. 1. Both of these arguments are (x.annotate(’local max’.pyplot as plt fig = plt. 1).y) tuples. lw=2) ax.add_subplot(111) t = np. This option provides lots of flexibility. both the xy (arrow tip) and xytext locations (text location) are in data coordinates. 5.plot(t.annotate(’local max’. and the annotate() method provides helper functionality to make annotations easy. shrink=0.95).01) s = np. Release 1. Please disable this option before reporting problems to the mailing list.1 is upper.preamble rc setting is not officially supported. one could do: ax.1 • The text. xytext=(0.cos(2*np. The uses of the basic text() command above place text at an arbitrary position on the Axes. shrink=0.set_ylim(-2. import numpy as np import matplotlib. right points from lower left corner of axes pixels from lower left corner of axes 0. = ax.latex. please see Report a problem 7. xycoords=’data’.8.05). xy=(3. • If you still need help.0.pi*t) line.figure() ax = fig.05). 56 Chapter 7.0. s.arange(0.5). 1).0. A common use case of text is to annotate some feature of the plot.show() In this example. 0. arrowprops=dict(facecolor=’black’. there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. The text in this example is placed in the fractional figure coordinate system. you can specify arrow properties which draws an arrow from the text to the annotated point by giving a dictionary of arrow properties in the optional keyword argument arrowprops.Text keyword args like horizontalalignment.0 0.0 1. analogous to negative indexing of sequences.annotate‘ to the ‘‘Text instance import numpy as np import matplotlib. the origin is from the (right.5 0.0 0.patches.Axes.5 1.5 2. arrowprops key width frac headwidth shrink **kwargs description the width of the arrow in points the fraction of the arrow length occupied by the head the width of the base of the arrow head in points move the tip and base some percent away from the annotated point and text any key for matplotlib. the xy point is in native coordinates (xycoords defaults to ‘data’). If the value is negative. however.00 1 2 3 4 5 local max horizontalalignment=’right’. For a polar axes. e.1 2.0.g. top) of the figure or axes.Polygon. left) of the figure or axes. ) For physical coordinate systems (points or pixels) the origin is the (bottom. this is in (theta.text. radius) space. facecolor In the example below.pyplot as plt 7. Release 1.Matplotlib.5 1. verticalalignment and fontsize are passed from the ‘~matplotlib. verticalalignment=’top’.0 1. Annotating text 57 .6. Optionally. matplotlib. 05. color=’#ee8d18’. Release 1.0. [thisr].figure() ax = fig.6 45° 0. horizontalalignment=’left’.arange(0. # theta. Working with text . fraction textcoords=’figure fraction’. r.plot(theta.2 0. shrink=0. ) plt.05).0.4 225° a polar annotation 270° 315° For more on all the wild and wonderful things you can do with annotations. # fraction. radius xytext=(0.show() 90° 135° 0. including fancy arrows. thisr). 0. polar=True) r = np.1 fig = plt. = ax.8 1.plot([thistheta]. arrowprops=dict(facecolor=’black’. ’o’) ax. 58 Chapter 7.0 0° 180° 0.add_subplot(111. thistheta = r[ind]. lw=3) ind = 800 thisr.001) theta = 2*2*np.1. theta[ind] ax. see Annotating Axes and pylab_examples-annotation_demo.annotate(’a polar annotation’.05).pi*r line. xy=(thistheta. verticalalignment=’bottom’.Matplotlib. if you use the -pylab method. See also Pyplot tutorial. The easy way for an interactive environment: $ipython -pylab The imshow function is now directly accessible (it’s in your namespace). matplotlib only supports PNG images..” and “plt. . The image used in this example is a PNG file. but keep that PIL requirement in mind for your own data. In [1]: import matplotlib.2 Importing image data into Numpy arrays Plotting image data is supported by the Python Image Library (PIL).1 Startup commands At the very least. 8. for clarity..CHAPTER EIGHT IMAGE TUTORIAL 8. In these examples. The more expressive.pyplot as plt In [2]: import matplotlib.” prefixes. There are a couple of ways to do it. Here’s the image we’re going to play with: 59 .image as mpimg In [3]: import numpy as np Examples below will use the latter method. easier to understand later method (use this in your scripts to make it easier for others (including your future self) to read) is to use the matplotlib API (see Artist tutorial) where you use explicit namespaces and control object creation. you’ll need to have access to the imshow() function. you can skip the “mpimg. etc. The commands shown below fall back on PIL if the native read fails. Natively. 0.42745098]. 0. [ 0.42745098. [ 0.40784314. In [4]: img=mpimg. [ 0. 0. 0.41176471.. [ 0.42745098]]. 0.. 0.41176471. .41176471]. .. 0. the other kinds of image that you’ll most likely encounter are RGBA images. [ 0. [ 0.41176471]..42745098.Matplotlib. 0.42745098]. And here we go. 0.0. You can right click on it and choose “Save image as” to download it to your computer for the rest of this tutorial.42745098. [ 0. 0.42745098.40784314]. 0.40784314. 0. G. [ 0. Depending on where you get your data. [[ 0. 0. B).41176471.42745098. [ 0.. 0. [ 0.. Release 1..42745098]]. or singlechannel grayscale (luminosity) images.42745098].42745098. 0. 0.40784314.imread(’stinkbug. 0.40784314].41176471.41176471.42745098. which allow for transparency.42745098.42745098].1 It’s a 24-bit RGB PNG image (8 bits for each of R.40784314. 0. 0.42745098. 0.42745098.40784314]. 0. 0.. Image tutorial .40784314.41176471].42745098. 0.40784314.png’) Out[4]: array([[[ 0. 0.41176471. 60 Chapter 8.42745098. 3 Plotting numpy arrays as images So.1 [[ 0. 0.44313726]]]. not a 3-D array). 0. 0.43137255. 0.41960785..4509804 .44313726]. [ 0. [ 0. Why can they only render 8 bits/channel? Because that’s about all the human eye can see. the only datatype that PIL can work with is uint8. 0. [ 0. 0. Matplotlib has rescaled the 8 bit data from each channel to floating point data between 0.43137255. 0.44705883. 0.3.41960785]. [ 0.44705883. 0.4509804 .. More here (from a photography standpoint): Luminous Landscape bit depth tutorial. . 0. 0. As a side note..44705883.44705883].41568628.44313726]. Here. 0. 0.43137255. [ 0. R. [ 0.41568628. An RGBA (where A is alpha.4509804 . [ 0. or transparency). 0.44705883]. 0.41568628]. you have your data in a numpy array (either by importing it. 0.43921569.44705883. matplotlib supports only float32. [ 0. 0. Here we’ll grab the plot object. [ 0. [ 0.43137255.. 0. Release 1.4509804 ]. [ 0. 0. 0. 0. has 4 values per inner list.. If your array data does not meet one of these descriptions. 0.. and B are all similar. [ 0.43921569]. 0. 0.44313726. 0. 0. For RGB and RGBA images. Why 8 bits? Most displays can only render 8 bits per channel worth of color gradation. [ 0. 0. 8.43921569]. dtype=float32) Note the dtype there .44313726. Plotting numpy arrays as images 61 . [ 0.41568628].41568628. Since it’s a black and white image. 0.0 and 1.4509804 ].41568628. 0. Matplotlib plotting can handle float32 and uint8..4509804 .41960785.43137255.45490196. 0. 0.43137255]. 0. For grayscale. [ 0. [ 0.4509804 . 0.44313726.43137255.44313726. In Matplotlib. matplotlib supports float32 and uint8 data types.43137255.44705883]].4509804 .4509804 .43921569.43529412]. 0.43921569... This object 8.0. [[ 0. Each inner list represents a pixel.4509804 ]].43921569.43529412.44705883.4509804 ]. 0.44313726. 0. 0. 0.44313726]. G. 0. [ 0.44705883. 0.. 0. 0. there are 3 values.43137255]]...44313726. .44705883]. [ 0. [ 0.43137255].. you need to rescale it.4509804 .44313726.43137255. and a simple luminance image just has one value (and is thus only a 2-D array. [ 0. Let’s render it.4509804 ].4509804 .. [[ 0.43137255].44313726. this is performed using the imshow() function. but image reading/writing for any format other than PNG is limited to uint8 data. . 0.0.45490196]. [[ 0. with an RGB image.44705883. . 0. 0.float32. . 0.45490196. or by generating it).4509804 .Matplotlib. 0.43529412..44705883. 0. In [5]: imgplot = plt.1 gives you an easy way to manipulate the plot from the prompt.:.3. luminosity images.1 Applying pseudocolor schemes to image plots Pseudocolor can be a useful tool for enhancing contrast and visualizing your data more easily. grayscale.just remember that the datatype must be float32 (and range from 0. Image tutorial .Matplotlib. Pseudocolor is only relevant to single-channel.0) or uint8.0] This is array slicing.0. and B are all similar (see for yourself above or in your data).imshow(img) 0 50 100 150 200 250 300 350 0 100 200 300 400 You can also plot any numpy array . we can just pick on channel of our data: In [6]: lum_img = img[:. Release 1. You can read more in the Numpy tutorial. Since R.their contrast is typically quite poor. We currently have an RGB image.imshow(lum_img) 62 Chapter 8. 8. In [7]: imgplot = mpimg.0 to 1. This is especially useful when making presentations of your data using projectors . G. The default is called jet.2 Color scale reference It’s helpful to have an idea of what value a color represents. Release 1. and add in the colorbar again.0.3.set_cmap(’hot’) In [9]: imgplot. See the list and images of the colormaps. 8. LUT). There are plenty of others to choose from. Let’s set some others using the set_cmap() method on our image plot object: In [8]: imgplot. with a luminosity image.1 0 50 100 150 200 250 300 350 0 100 200 300 400 Now. 8. the default colormap (aka lookup table.set_cmap(’spectral’) There are many other colormap schemes available. is applied. It’s as easy as one line: In [10]: plt.colorbar() This adds a colorbar to your existing figure. This won’t automatically change if you change you switch to a different colormap .you have to re-create your plot. Plotting numpy arrays as images 63 .3.Matplotlib. We can do that by adding color bars. 256. The number of pixels change.flatten().0. To create a histogram of our image data. In[11]: imgplot. range=(0. Interpolation is how you fill that space. In[10]: plt.hist(lum_img. fc=’k’. The effect is more pronounced when the difference between the original image and the expanded image 64 Chapter 8. A good tool to find interesting regions is the histogram. or don’t matter. Release 1. ec=’k’) Most often.1 0 50 100 150 200 250 300 350 0 100 200 300 400 8. so that we effectively “zoom in on” part of the histogram. we use the hist() function. there’s missing space. according to different mathematical schemes. the “interesting” part of the image is around the peak. Since pixels are discrete.0.1.3.0).0. but you want the same information. We do this by calling the set_clim() method of the image plot object.set_clim=(0.Matplotlib. In our histogram. and you can get extra contrast by clipping the regions above and/or below the peak. This is why your images sometimes come out looking pixelated when you blow them up. Let’s adjust the upper limit. One common place that this happens is when you resize an image.0.4 Array Interpolation schemes Interpolation calculates what the color or value of a pixel “should” be.3.3 Examining a specific data range Sometimes you want to enhance the contrast in your image. or expand the contrast in a particular region while sacrificing the detail in colors that don’t vary much.7) 8. Image tutorial . it looks like there’s not much useful information in the high end (not many white things in the image). In In In In In [8]: import Image [9]: img = Image. and the computer has to draw in pixels to fill that space. Now when we plot it. that data gets blown up to the size on your screen. Let’s try some others: In [10]: imgplot. Plotting numpy arrays as images 65 .resize((img. bilinear. Let’s take our image and shrink it.size[1]/10)) # Use PIL to resize [11]: rsizeArr = np. The old pixels aren’t there anymore.3.Matplotlib.open(’stinkbug. 8.size[0]/10. We’re effectively discarding pixels. Release 1.asarray(rsize) # Get array back [12]: imgplot = mpimg.img. since we did not give imshow() any interpolation argument.1 0 50 100 150 200 250 300 350 0 100 200 300 400 is greater.set_interpolation(’nearest’) In [10]: imgplot. only keeping a select few.png’) # Open image as PIL image object [10]: rsize = img.people tend to prefer blurry over pixelated.0.set_interpolation(’bicubic’) Bicubic interpolation is often used when blowing up photos .imshow(rsizeArr) Here we have the default interpolation. 4 0.1 0 50 100 150 200 250 300 350 0 0.Matplotlib.3 0.6 0.5 0.0 66 Chapter 8.7 0.2 100 200 300 400 0.0. Image tutorial .8 0.1 0. Release 1. Matplotlib.6 0.0 8.4 0.0 0. Release 1. Plotting numpy arrays as images 67 .8 1.0.2 0.1 10000 8000 6000 4000 2000 0 0.3. 7 After 0 50 100 150 200 250 300 350 0 100 200 300 400 0.1 0.0. Release 1.3 0.3 0.7 68 Chapter 8.Matplotlib.5 0.1 0.5 0. Image tutorial .1 Before 0 50 100 150 200 250 300 350 0 100 200 300 400 0. 0. Plotting numpy arrays as images 69 .Matplotlib. Release 1.3.1 0 5 10 15 20 25 30 35 0 10 20 30 40 8. 0. Image tutorial .1 0 5 10 15 20 25 30 35 0 10 20 30 40 70 Chapter 8.Matplotlib. Release 1. 0. Plotting numpy arrays as images 71 .1 0 5 10 15 20 25 30 35 0 10 20 30 40 8.3. Release 1.Matplotlib. Image tutorial . Release 1.Matplotlib.0.1 72 Chapter 8. we create a Figure instance using matplotlib.15. Text.Renderer is the object which knows how to draw on the FigureCanvas.backend_bases. Line2D). The FigureCanvas and Renderer handle all the details of talking to user interface toolkits like wxPython or drawing languages like PostScript®. text. width.Artist is the object that knows how to use a renderer to paint onto the canvas. and the one you will be working with most of the time. the matplotlib. and the containers are places to put them (Axis. hist(). In the example below. and draw them when requested. this is not necessary – you can work directly with PostScript.figure() ax2 = fig2. There are two types of Artists: primitives and containers. etc.add_subplot(2. respectively). The standard use is to create a Figure instance.figure() ax = fig. The primitives represent the standard graphical objects we want to paint onto our canvas: Line2D. imshow()) to create the most common graphics primitives (Line2D. instantiate your Figures directly and connect them yourselves – but since we are focusing here on the Artist API we’ll let pyplot handle some of those details for us: import matplotlib. Text. These helper methods will take your data (eg. As we will discuss below.FigureCanvas is the area onto which the figure is drawn. simply use the add_axes() method which takes a list of [left.add_axes([0.backend_bases.. which is a convenience method for instantiating Figure instances and connecting them with your user interface or drawing toolkit FigureCanvas. first plot The Axes is probably the most important class in the matplotlib API. text(). one column. use the Figure to create one or more Axes or Subplot instances.artist. and the Artist handles all the high level constructs like representing and laying out the figure. The matplotlib.7. Rectangle. The typical user will spend 95% of his time working with the Artists. If you want to create an Axes at an arbitrary location. add them to the relevant containers. and use the Axes instance helper methods to create the primitives. which is just a special case of an Axes that lives on a regular rows by columns grid of Subplot instances.1. Image. numpy arrays and strings) and create primitive Artist instances as needed (eg.1) # two rows.CHAPTER NINE ARTIST TUTORIAL There are three layers to the matplotlib API. and the matplotlib.pyplot. AxesImage. PDF Gtk+. Most of you are probably familiar with the Subplot. and lines. This is because the Axes is the plotting area into which most of the objects go. 0. 0.pyplot as plt fig = plt. Axes and Figure).1. 0.3]) Continuing with our example: 73 . bottom.figure(). Rectangle. and the Axes has many special helper methods (plot(). or wxPython FigureCanvas instances. height] values in 0-1 relative figure coordinates: fig2 = plt. either of these will work: del ax. tick labels and axis labels: xtext = ax. Every matplotlib Artist has the following properties 74 Chapter 9.lines[0] Out[101]: <matplotlib. 0.0.set_xlabel. You can remove lines later simply by calling the list methods. each Axes bounding box (the standard white box with black edges in the typical matplotlib plot. = ax. it creates a Line2D instance and adds it to the Axes.01) s = np. and each has an extensive list of properties to configure its appearance.plot. = ax. The figure itself contains a Rectangle exactly the size of the figure. s.1 import numpy as np t = np. Each Axes instance contains an XAxis and a YAxis instance. and other properties of the Axes.sin(2*np.0.Line2D instance at 0x19a95710> In [102]: line Out[102]: <matplotlib.lines. color=’blue’. call: In [101]: ax.0. Artist tutorial .Matplotlib.set_ylabel(’my xdata’) When you call ax.lines list. circles and polygons).pi*t) line. you can see that the Axes. which handle the layout and drawing of the ticks.patch and Axes. not both! The Axes also has helper methods to configure and decorate the x-axis and y-axis tick. tick labels and axis labels. ax is the Axes instance created by the fig. rectangles. and is a 2D “patch” of color on the figure.add_subplot call above (remember Subplot is just a subclass of Axes) and when you call ax.lines. These instances are stored as member variables Figure. lw=2) In this example.plot (and the hold state is “on” which is the default) then additional lines will be added to the list. 1.arange(0. Release 1.lines[0] ax.. Try creating the figure below. transparency.remove(line) # one or the other.plot(t. it passes the information on the Text instance of the XAxis. has a Rectangle instance that determines the color.set_xlabel(’my xdata’) # returns a Text instance ytext = ax.patch (“Patch” is a name inherited from MATLAB..lines.Line2D instance at 0x19a95710> If you make subsequent calls to ax. Likewise. eg.plot.1 Customizing your objects Every element in the figure is represented by a matplotlib Artist. In the interactive ipython session below. 9. which you can use to set the background color and transparency of the figures.lines list is length one and contains the same line that was returned by the line. 0 0. Customizing your objects 75 . you can also use the set method with keyword arguments.5 0.5 1.2 0.0 3 2 1 0 1 time (s) 2 3 4 Property alpha animated axes clip_box clip_on clip_path contains figure label picker transform visible zorder Description The transparency .5*a) If you want to set a number of properties at once.Matplotlib.4 0. for auto-labeling) A python object that controls object picking The transformation A boolean whether the artist should be drawn A number which determines the drawing order Each of the properties is accessed with an old-fashioned setter or getter (yes we know this irritates Pythonistas and we plan to support direct access via properties or traits but it hasn’t been done yet). For example. possibly None The bounding box that clips the Artist Whether clipping is enabled The path the artist is clipped to A picking function to test whether the artist contains the pick point The figure instance the artist lives in.0 0.1. Release 1. to multiply the current alpha by a half: a = o.0 70 60 50 40 30 20 10 04 a sine wave volts 0.0 0.set_alpha(0.8 1.6 0.0. possibly None A text label (eg.get_alpha() o. For example: 9.a scalar from 0-1 A boolean that is used to facilitate animated drawing The axes that the Artist lives in.1 1. Release 1. This works for classes derived from Artist as well. (1. In this section we’ll review where the various container objects store the Artists that you want to get at. 0). 76 Chapter 9.2 Object containers Now that we know how to inspect and set the properties of a given object we want to configure. As mentioned in the introduction. 1).Matplotlib.0 animated = False antialiased or aa = True axes = None clip_box = None clip_on = False clip_path = None contains = None edgecolor or ec = w facecolor or fc = 0.0. (1. 1). Here are the Figure rectangle properties mentioned above: In [149]: matplotlib.0 picker = None transform = <Affine object at 0x134cca84> verts = ((0. The primitives are usually the things you want to configure (the font of a Text instance. there are two kinds of objects: primitives and containers. a handy way to inspect the Artist properties is to use the matplotlib. 9. we need to now how to get at that object.set(alpha=0. (0.125) fill = 1 hatch = None height = 1 label = linewidth or lw = 1. zorder=2) If you are working interactively at the python shell. 0)) visible = True width = 1 window_extent = <Bbox object at 0x134acbcc> x = 0 y = 0 zorder = 1 The docstrings for all of the classes also contain the Artist properties. but it also has properties like the xscale to control whether the xaxis is ‘linear’ or ‘log’.artist.1 o. so you can consult the interactive “help” or the matplotlib artists for a listing of properties for a given object. eg.artist. the width of a Line2D) although the containers also have some properties as well – for example the Axes Artist is a container that contains many of the primitives in your plot. Artist tutorial .75 figure = Figure(8.5. Figure and Rectangle.getp() function (simply getp() in pylab).patch) alpha = 1.125x6. which lists the properties and their values.getp(fig. axes: ax. 1].Matplotlib.gca and Figure. 0]. lines.Subplot instance at 0xd54b26c> In [160]: print fig. [1. and the delaxes() method to delete.axes. Figure container 77 . figure=fig) In [193]: l2 = matplotlib. You are free however. you should not insert or remove axes directly from the axes list.1.sca) to support the pylab/pyplot state machine.figure() In [157]: ax1 = fig. 1) is the top-right of the figure which you can obtain by setting the Artist transform to fig. 0) is the bottom-left of the figure and (1. 0. but rather use the add_subplot() and add_axes() methods to insert.Subplot instance at 0xd54b26c>. transform=fig. Release 1.3 Figure container The top level container Artist is the matplotlib. These are also returned by the methods that create them: In [156]: fig = plt.axes.draw() Here is a summary of the Artists the figure contains 9. <matplotlib.Axes instance at 0xd3f0b2c>] Because the figure maintains the concept of the “current axes” (see Figure.grid(True) The figure also has its own text. [0.lines. patches and images. As you add subplots (add_subplot()) and axes (add_axes()) to the figure these will be appended to the Figure. More useful is “figure coordinates” where (0. 1].patch.extend([l1.add_subplot(211) In [158]: ax2 = fig. figure=fig) In [194]: fig.3.transFigure: In [191]: fig = plt.1.lines.3]) In [159]: ax1 Out[159]: <matplotlib.Figure. which you can use to add primitives directly. and it contains everything in the figure. 0.canvas. Here is an example which turns all the axes grids on: for ax in fig.axes.transFigure. The background of the figure is a Rectangle which is stored in Figure.figure. 0.transFigure. to iterate over the list of axes or index into it to get access to Axes instances you want to customize.Line2D([0.1 9.axes [<matplotlib. transform=fig.0.add_axes([0.7.figure() In [192]: l1 = matplotlib.axes. 1].Line2D([0. The default coordinate system for the Figure will simply be in pixels (which is not usually what you want) but you can control this by setting the transform property of the Artist you are adding to the figure. l2]) In [195]: fig.lines. legends) A list of Figure Line2D instances (rarely used.1 Figure attribute axes patch images legends lines patches texts Description A list of Axes instances (includes Subplot) The Rectangle background A list of FigureImages patches . see Axes. background and border of the plotting region: ax = fig.0.useful for raw pixel display A list of Figure Legend instances (different from Axes. Artist tutorial . the canonical plot() and pass in arrays or lists of values. Release 1. as well as helper methods to access and customize the Artists it contains.add_subplot(111) rect = ax.axes.patches) A list Figure Text instances 9.patch # a Rectangle instance rect.set_facecolor(’green’) When you call a plotting method.4 Axes container The matplotlib. see Axes. the method 78 Chapter 9. it contains a Patch patch which is a Rectangle for Cartesian coordinates and a Circle for polar coordinates. this patch determines the shape.lines) A list of Figure patches (rarely used.Matplotlib. eg. Like the Figure.Axes is the center of the matplotlib universe – it contains the vast majority of all the Artists used in a figure with many helper methods to create and add these Artists to itself. 50.figure() In [262]: ax = fig. add the line to the Axes.lines [<matplotlib.Rectangle( (1.Matplotlib.8) 9. 100) In [214]: line. color=’blue’.hist(np.add_subplot(111) # create a rectangle instance In [263]: rect = matplotlib.rand(2. ’-’.lines or Axes.patches list: In [233]: n.1).get_axes() None # and the transformation instance is set to the "identity transform" In [265]: print rect.lines container.patches. methods that create patches.0.lines. bins.Line2D() instance. so that the view limits can be adjusted to contain the plotted data. as well as the default Axes transformation (unless a transformation is set).get_transform() <Affine object at 0x13695544> # now we add the Rectangle to the Axes In [266]: ax. facecolor=’yellow’) In [234]: rectangles Out[234]: <a list of 50 Patch objects> In [235]: print len(ax. width=5.lines list: In [229]: print ax. = ax. y = np.1.add_patch(rect) # and notice that the ax. create objects yourself and add them directly to the Axes using helper methods like add_line() and add_patch(). will add the patches to the Axes.patches lists unless you know exactly what you are doing.random.775x0. y. y pairs to plot.lines.patches) You should not add objects directly to the Axes. rectangles = ax. update the line with all the Line2D properties passed as keyword arguments. Release 1. It sets the figure and axes property of the Artist. The line has been added to the Axes. because the Axes needs to do a few things when it creates and adds an object.4.random. height=12) # by default the axes instance is None In [264]: print rect. It also inspects the data contained in the Artist to update the data structures controlling auto-scaling. and we are unpacking the first element of the length one list into the line variable.get_axes() Axes(0.add_patch method has set the axes # instance In [267]: print rect.0.Line2D instance at 0xd378b0c>] Similarly.1 will create a matplotlib. like bar() creates a list of rectangles. You can.plot(x. and returns it to you: In [213]: x. nonetheless.randn(1000). linewidth=2) plot returns a list of lines because you can pass in multiple x.0. Here is an annotated interactive session illustrating what is going on: In [261]: fig = plt. Axes container 79 .125. legend .image data ax.text annotations ax.get_xlim() (1.bar .bar charts ax.get_transform() <Affine object at 0x15009ca4> # the default axes transformation is ax.transData <Affine object at 0x15009ca4> # notice that the xlimits of the Axes have not been changed In [270]: print ax.0.transData In [269]: print ax.patches ax.lines and ax. The table below summarizes a small sampling of them. 5. the Axes contains two important Artist containers: the XAxis and YAxis.0.texts In addition to all of these Artists.0) # we have to manually force a figure draw In [274]: ax.set_color(’orange’) 80 Chapter 9.0.patches ax.imshow .draw() There are many.0.autoscale_view() # and now the xlim are updated to encompass the rectangle In [273]: print ax.patches ax.scatter .0) # but the data limits have been updated to encompass the rectangle In [271]: print ax.Matplotlib. Release 1.plot .patches ax.images ax.0) # we can manually invoke the auto-scaling machinery In [272]: ax.get_xticklabels(): label.legends ax.error bar plots ax. you can set the font size of the XAxis ticklabels using the Axes helper method: for label in ax.texts ax. The XAxis and YAxis containers will be detailed below.figure.dataLim.0.get_xlim() (0.canvas. and where they store them Helper method ax. 6. 1.bounds (1.errorbar .xy plots ax.scatter charts ax. For example.histograms ax. These are stored as instance variables xaxis and yaxis.fill . but note that the Axes contains many helper methods which forward calls on to the Axis instances so you often do not need to work with them directly unless you want to.collections ax.0.1 # and the transformation has been set too In [268]: print rect.annotate .axes legends ax. the kinds of Artist they create. which handle the drawing of the ticks and labels.text Artist Annotate Rectangle Line2D and Rectangle Polygon Rectangle AxesImage Legend Line2D PolygonCollection Text Container ax.lines ax.text . 1.hist .shared area ax. Artist tutorial . 12. many Axes helper methods for creating primitive Artists and adding them to their respective containers. 6. which contain the actual line and text primitives that render the ticks and ticklabels. the Axis methods contain accessor methods to return the tick lines. 4..0.get_ticklines() Out[291]: <a list of 20 Line2D ticklines objects> # but you can also ask for the minor ticks 9...Matplotlib..get_ticklabels() Out[287]: <a list of 10 Text major ticklabel objects> # note there are twice as many ticklines as labels because by # default there are tick lines at the top and bottom but only tick # labels below the xaxis. 3. you should access the lists of major and minor ticks through their accessor methods get_major_ticks() and get_minor_ticks(). 8. 5. tick locations etc.: In [285]: axis = ax. Axis containers 81 .. 7.axis. 9. Although the ticks contain all the primitives and will be covered below. You can configure the left and right ticks separately for the y-axis.get_ticklocs() Out[286]: array([ 0.]) In [287]: axis..axis.YAxis instance 9.xaxis In [286]: axis. 1.5. The Axis also stores the data and view intervals used in auto-scaling. when panning and zooming). as well as the Locator and Formatter instances which control where the ticks are placed and how they are represented as strings. Because the ticks are dynamically created as needed (eg.get_ticklines() Out[288]: <a list of 20 Line2D ticklines objects> # by default you get the major ticks back In [291]: axis..5 Axis containers The matplotlib.. Release 1. The ticks are XTick and YTick instances. 2. and the upper and lower ticks separately for the x-axis.XAxis instance matplotlib. Each Axis object contains a label attribute (this is what pylab modifies in calls to xlabel() and ylabel()) as well as a list of major and minor ticks.axis. the tick labels and the axis label.. tick labels. the grid lines. panning and zooming.1 Below is a summary of the Artists that the Axes contains Axes attribute artists patch collections images legends lines patches texts xaxis yaxis Description A list of Artist instances Rectangle instance for Axes background A list of Collection instances A list of AxesImage A list of Legend instances A list of Line2D instances A list of Patch instances A list of Text instances matplotlib.Axis instances handle the drawing of the tick lines. this can be customized In [288]: axis. set_color(’red’) label.set_color(’green’) line.4]) rect = ax1.1.patch rect.3. 0.get_ticklabels(): # label is a Text instance label.ticker.set_markersize(25) line. not recommended for its beauty.keyword minor=True|False A list of Tick locations .get_ticklines(minor=True) Out[292]: <a list of 0 Line2D ticklines objects> Here is a summary of some of the useful accessor methods of the Axis (these have corresponding setters where useful. Release 1.Formatter instance for minor ticks A list of Tick instances for major ticks A list of Tick instances for minor ticks Turn the grid on or off for the major or minor ticks Here is an example.set_markeredgewidth(3) 82 Chapter 9.add_axes([0.set_facecolor(’lightgoldenrodyellow’) ax1 = fig.Figure instance fig = plt. 0.Locator instance for major ticks The matplotlib.0.Formatter instance for major ticks The matplotlib.pyplot as plt # plt.keyword minor=True|False A list of Line2D instances . Artist tutorial .xaxis.ticker.set_facecolor(’lightslategray’) for label in ax1. such as set_major_formatter) Accessor method get_scale get_view_interval get_data_interval get_gridlines get_label get_ticklabels get_ticklines get_ticklocs get_major_locator get_major_formatter get_minor_locator get_minor_formatter get_major_ticks get_minor_ticks grid Description The scale of the axis.figure() rect = fig.figure creates a matplotlib.figure.set_fontsize(16) for line in ax1.set_rotation(45) label.yaxis. which customizes the axes and tick properties import numpy as np import matplotlib.1 In [292]: axis. eg ‘log’ or ‘linear’ The interval instance of the axis view limits The interval instance of the axis data limits A list of grid lines for the Axis The axis label .patch # a rectangle instance rect.a Text instance A list of Text instances .ticker. 0.ticker.get_ticklines(): # line is a Line2D instance line.Locator instance for minor ticks The matplotlib.keyword minor=True|False The matplotlib.Matplotlib.4. 0 83 . Tick containers 0.2 0. there are boolean variables that determine whether the upper labels and ticks are on for the x-axis and whether the right labels and ticks are on for the y-axis.8 0.6 0. as well as the label instances for the upper and lower ticks.Matplotlib.0 9.6.axis. The Tick contains the tick and grid line instances.6 0.8 1.2 0.0 0. Tick attribute tick1line tick2line gridline label1 label2 gridOn tick1On tick2On label1On label2On Description Line2D instance Line2D instance Line2D instance Text instance Text instance boolean which determines whether to draw the tickline boolean which determines whether to draw the 1st tickline boolean which determines whether to draw the 2nd tickline boolean which determines whether to draw tick label boolean which determines whether to draw tick label Here is an example which sets the formatter for the right side ticks with dollar signs and colors them green on the right side of the yaxis 9. Release 1. In addition.1 1. Each of these is accessible directly as an attribute of the Tick.4 0.0.Tick is the final container object in our descent from the Figure to the Axes to the Axis to the Tick.4 0.6 Tick containers The matplotlib.0 0. yaxis. Artist tutorial .2f ’) ax.FormatStrFormatter(’$%1.yaxis.label1On = False tick.plot(100*np.random.add_subplot(111) ax.rand(20)) formatter = ticker.set_major_formatter(formatter) for tick in ax. _gridspec-guide: 5 10 15 $0. Release 1.label2.1 import numpy as np import matplotlib.get_major_ticks(): tick.00 $20.ticker as ticker fig = plt.set_color(’green’) $100..0.label2On = True tick.00 $60.00 20 84 Chapter 9.00 0 .00 $80.figure() ax = fig.pyplot as plt import matplotlib.Matplotlib.00 $40. the subplot layout parameters (e. 1)) creates 85 . plt. Optionally.3). plt.subplot2grid((2.subplot(2. 0)) is identical to ax = plt.) can be tuned. the following commands ax1 ax2 ax3 ax4 ax5 = = = = = plt.subplot2grid((3.CHAPTER TEN CUSTOMIZING LOCATION OF SUBPLOT USING GRIDSPEC GridSpec specifies the geometry of the grid that a subplot will be placed.subplot2grid((3.1) Note that. (1.subplot2grid((3. the index starts from 0 in gridspec. 0)) (2.0). SubplotSpec specifies the location of the subplot in the given GridSpec. colspan=2) (1. rowspan=2) For example. For a simple single-cell subplot: ax = plt.(0.2. rowspan=2) (2. plt.. you provide geometry of the grid and the location of the subplot in the grid. The number of rows and number of columns of the grid need to be set.3). Basic Example of using subplot2grid To use subplot2grid.3). colspan=2) ax3 = plt. plt.subplot2grid((3. unlike matplotlib’s subplot.2). colspan=3) (1. left. subplot2grid a helper function that is similar to “pyplot.subplot2grid((3.3). 2).3). (0.3).g.subplot” but uses 0-based indexing and let subplot to occupy multiple cells.3).0). 2). right.subplot2grid((3. To create a subplot that spans multiple cells. ax2 = plt.subplot2grid((3. 0). etc. (1. For example. SubplotSpec that spans multiple cells.0. Release 1. ax2 = plt. ax = plt. :]) ax2 = plt. 2) ax = plt.(0.:-1]) 86 Chapter 10. For. use slice.subplot2grid((2.gridspec as gridspec gs = gridspec.subplot(gs[1.GridSpec(3.subplot(gs[1.1 subplot2grid ax1 ax2 ax3 ax4 ax5 10. 0)) is equal to import matplotlib.Matplotlib.subplot(gs[0.subplot(gs[0. -1]) The above example becomes gs = gridspec.1 GridSpec and SubplotSpec You can create GridSpec explicitly and use them to create a Subplot.2). Customizing Location of Subplot Using GridSpec . 3) ax1 = plt.:-1]) ax3 = plt.GridSpec(2. 0]) A gridspec instance provides array-like (2d or 1d) indexing that returns the SubplotSpec instance.subplot(gs[1:. GridSpec(3. 3) gs1. :-1]) ax3 = plt.05.05) This is similar to subplots_adjust. gs1 = gridspec.05) ax1 = plt.0]) ax5 = plt.-2]) GridSpec ax1 ax2 ax3 ax4 ax5 10. wspace=0.subplot(gs[1:. -1]) gs2 = gridspec.update(left=0. 3) gs1. but it only affects the subplots that are created from the given GridSpec. The code below gs1 = gridspec. Adjust GridSpec layout 87 .subplot(gs1[-1. :]) ax2 = plt.05. -1]) ax4 = plt.GridSpec(3.0. Release 1.2 Adjust GridSpec layout When a GridSpec is explicitly used. you can adjust the layout parameters of subplots that are created from the gridspec.48.2.1 ax3 = plt.subplot(gs[-1. 3) 10. right=0.48. wspace=0.subplot(gs[-1.GridSpec(3. right=0.subplot(gs1[:-1.subplot(gs1[-1.Matplotlib.update(left=0. 3. subplot_spec=gs0[1]) 88 Chapter 10. 3.subplot(gs2[-1. Release 1. -1]) creates GirdSpec w/ different subplotpars ax1 ax4 ax5 ax2 ax3 ax6 10. hspace=0.update(left=0.1 gs2.subplot(gs2[:.GridSpecFromSubplotSpec(3.3 GridSpec using SubplotSpec You can create GridSpec from the SubplotSpec.Matplotlib. subplot_spec=gs0[0]) gs01 = gridspec.GridSpecFromSubplotSpec(3.GridSpec(1.98. Customizing Location of Subplot Using GridSpec . in which case its layout parameters are set to that of the location of the given SubplotSpec. :-1]) ax5 = plt. right=0. gs0 = gridspec.05) ax4 = plt. -1]) ax6 = plt.55.subplot(gs2[:-1. 2) gs00 = gridspec.0. only their relative ratios matter. height_ratios=[4. gs = gridspec. Release 1. Note that absolute values are meaningless. GridSpec creates cells of equal sizes.0. 2.4 GridSpec with Varying Cell Sizes By default. You can adjust relative heights and widths of rows and columns.1 GirdSpec Inside GridSpec ax1 ax4 ax5 ax2 ax3 ax6 10.subplot(gs[3]) 10.subplot(gs[2]) plt. GridSpec with Varying Cell Sizes 89 .1] ) ax1 ax2 ax3 ax4 = = = = plt. width_ratios=[1.4.GridSpec(2.2].subplot(gs[1]) plt.Matplotlib.subplot(gs[0]) plt. 0. Release 1.1 ax1 ax2 ax3 ax4 90 Chapter 10.Matplotlib. Customizing Location of Subplot Using GridSpec . – Line2D – Patch – LineCollection – RegularPolyCollection Unfortunately. labels) The get_legend_handles_labels() method returns a tuple of two lists. and the second argument should a list of string labels.e.Legend! 11.CHAPTER ELEVEN LEGEND GUIDE Do not proceed unless you already have read legend() and matplotlib. labels = ax. • Note that not all kind of artists are supported by the legend.Legend. The label attributes (returned by get_label() method) of collected artists are used as text labels.collection which are instance of LineCollection or RegularPolyCollection.1 What to be displayed The legend command has a following call signature: legend(*args. If len(args) is 0.patches and some artists in ax. See below). it automatically generate the legend from label properties of the child artists by calling get_legend_handles_labels() method. the first argument should be a list of artist to be labeled. that artist will be ignored.get_legend_handles_labels() ax. it does not return all of its child artists.legend() is equivalent to: handles. there is no easy workaround when you need legend for an artist not in the above list (You may use one of the supported artist as a proxy. It returns all artists in ax. i. list of artists and list of labels (python string). If label attribute is empty string or starts with “_”. **kwargs) If len(args) is 2.legend(handles. or customize it beyond what is supported by matplotlib. However. 91 ..lines and ax.legend. For example.legend. The following is the list of artists that are currently supported. ax. . labels = ax. = ax.plot([1.e. = plot([1.legend(handles[::-1].itemgetter(1)) handles2.3]. 0). fc="r") legend([p]. label="line 3") handles. e. label="line 1") p2. labels[::-1]) # or sort them by labels import operator hl = sorted(zip(handles. and explicitly use these for the first two argument of the legend call.g. Or some return multiple artists. ["line 2".2.2. p1].2. 1. labels2 = zip(*hl) ax.1].1 • Remember that some pyplot commands return artist not supported by legend. "line 1"]) Or you may use get_legend_handles_labels() to retrieve list of artist and labels and manipulate them before feeding them to legend call.3. the artists may belong to other axes or even none. = ax. 11.1]) p3.. key=operator.1) p1.: p = Rectangle((0. • The legend does not care about the axes that given artists belongs. plot() returns list of Line2D instances.1]. and errorbar() returns a length 3 tuple of Line2D instances. = plot([2. i.2 Using Proxy Artist When you want to display legend for an artist not supported by matplotlib. There are a two options. = ax. you can keep lists of artists and labels. 1.1.2. you may create a proxy artist without adding it to the axes (so the proxy artist will not be drawn in the main axes) and feed it to the legend function.: ax = subplot(1.0.: p1.legend(handles2. ["Red Rectangle"]) 92 Chapter 11. Release 1. Legend guide .1 Adjusting the Order of Legend items When you want to customize the list of artists to be displayed in the legend.1]) legend([p2.get_legend_handles_labels() # reverse the order ax. labels2) 11.3. or their order of appearance. For example.3]) p2. labels).1.plot([2.1. you may use another artist as a proxy. First. label="line 2") p3. For example. = plot([3. fill_between() returns PolyCollection that is not supported.plot([3.Matplotlib. 2. Multicolumn Legend 93 . 1). Release 1. 1). label="test2") legend(bbox_to_anchor=(1. the legend will anchor to the bbox of the axes (for legend) or the bbox of the figure (figlegend).2.2 Multicolumn Legend By specifying the keyword argument ncol. mode=”expand” horizontally expand the legend to fill the axes area.3]. if you want your axes legend located at the figure corner (instead of the axes corner): l = legend(bbox_to_anchor=(0.2. . 11. mode="expand".1].Matplotlib.. label="test2") legend(bbox_to_anchor=(0. For example.3]. 1. label="test1") plot([3. you can place above or outer right-hand side of the axes. y with width=height=0). either by string or a integer number. loc=3.py for example. Unless bbox_transform argument is given. from matplotlib. 0. You can specify your own bbox using bbox_to_anchor argument. or a tuple of 2 floats (x.pyplot import * subplot(211) plot([1. borderaxespad=0.) show() 11. Also. 1. width. loc=2.0. y.1 11.2.05.1].02. 1.) subplot(223) plot([1. bbox_to_anchor can be an instance of BboxBase.2.transFigure) Also.3 Legend location The location of the legend can be specified by the keyword argument loc. label="test1") plot([3. transform=gcf(). the coordinates (even for the bbox instance) are considered as normalized axes coordinates.102). borderaxespad=0. you can have a multi-column legend. See legend_demo3.. height of the bbox). String upper right upper left lower left lower right right center left center right lower center upper center center Number 1 2 3 4 5 6 7 8 9 10 By default. ncol=2. a tuple of 4 floats (x. = plot([1.0 11.3]) p2. Legend guide . ["Test1"]. Thus.2. loc=1) l2 = legend([p2]. ["Label 1"]. from matplotlib.0 1. loc=1) legend([p2].pyplot import * p1.1 3. = plot([3.5 test1 test2 0.0 test1 test2 1.0 1. Release 1.5 2.5 2. ["Label 2"]. When the legend command is called. label="test1") p2.5 2.0 1. loc=4) However.0.2.0 1.5 1. = plot([3.0 3.5 1. a new legend instance is created and old ones are removed from the axes. loc=4) # this removes l1 from the axes.5 1.1]) legend([p1].0 2.3]. gca().Matplotlib.: p1.4 Multiple Legend Sometime. you need to manually add the removed legend.2. label="test2") l1 = legend([p1]. ["Test2"].2.5 2.0 0. = plot([1.0 0.add_artist(l1) # add l1 as a separate artist to the axes show() 94 Chapter 11. you want to split the legend into multiple ones.1]. the above code only shows the second legend.0 2.0 0. 0 Label 1 Label 2 0. Release 1.0.5 1.0 0.0 1.0 1.1 3.0 2. Multiple Legend 95 .5 2.5 1.5 2.Matplotlib.4.0 11. Release 1. Legend guide .1 96 Chapter 11.0.Matplotlib. y=%d. fltk and macosx) and in order to support features like interactive panning and zooming of figures. Otherwise the instance will be garbagecollected and the callback will vanish.xdata. which is part of the FigureCanvasBase. which was the first user interface matplotlib supported.mpl_connect(’button_press_event’. Although the event handling API is GUI neutral. qt.Axes the event occurred in. event. it is helpful to the developers to have an API for interacting with the figure via key presses and mouse movements that is “GUI neutral” so we don’t have to repeat a lot of code across the different user interfaces.1 Event connections To receive events. the class instances that are sent back to you when the event occurs. event.canvas.button.rand(10)) def onclick(event): print ’button=%d.figure() ax = fig.plot(np. 12.random. When you want to disconnect the callback. it is based on the GTK model. Here are the events that you can connect to. The events that are triggered are also a bit richer vis-a-vis matplotlib than standard GUI events. xdata=%f . Here is a simple example that prints the location of the mouse click and which button was pressed: fig = plt.axes. tkinter.CHAPTER TWELVE EVENT HANDLING AND PICKING matplotlib works with 6 user interface toolkits (wxpython.x. ydata=%f ’%( event. you need to retain a reference to that instance. including information like which matplotlib. and the event descriptions 97 . and report event locations in both pixel and data coordinates.mpl_disconnect(cid) Note: The canvas retains only weak references to the callbacks.add_subplot(111) ax. event. Therefore if a callback is a method of a class instance.ydata) cid = fig. you need to write a callback function and then connect your function to the event manager. onclick) The FigureCanvas method mpl_connect() returns a connection id which is simply an integer.canvas. gtk. x=%d. The events also understand the matplotlib coordinate system.y. event. just call: fig. event): 98 Chapter 12.canvas.mouse enters a new figure LocationEvent .mouse button is pressed MouseEvent .key is released MouseEvent .mouse enters a new axes LocationEvent . Event handling and picking . which has the following attributes x x position .mouse scroll wheel is rolled LocationEvent .cid = line.mpl_connect(’button_press_event’. The KeyEvent and MouseEvent classes that handle these events are both derived from the LocationEvent. where a simple line segment is created every time a mouse is pressed: from matplotlib import pyplot as plt class LineBuilder: def __init__(self.key is pressed KeyEvent .Event.figure canvas is resized MouseEvent .line = line self. self) def __call__(self.get_xdata()) self.pixels from bottom of canvas inaxes the Axes instance if mouse is over axes xdata x coord of mouse in data coords ydata y coord of mouse in data coords Let’s look a simple example of a canvas.get_ydata()) self.mouse leaves an axes 12.canvas draw KeyEvent . which store the attributes: name the event name canvas the FigureCanvas instance generating the event guiEvent the GUI event that triggered the matplotlib event The most common events that are the bread and butter of event handling are key press/release events and mouse press/release and movement events.0.xs = list(line. line): self. Release 1.ys = list(line.2 Event attributes All matplotlib events inherit from the base class matplotlib.figure.an object in the canvas is selected ResizeEvent .mouse motion PickEvent .1 Event name ‘button_press_event’ ‘button_release_event’ ‘draw_event’ ‘key_press_event’ ‘key_release_event’ ‘motion_notify_event’ ‘pick_event’ ‘resize_event’ ‘scroll_event’ ‘figure_enter_event’ ‘figure_leave_event’ ‘axes_enter_event’ ‘axes_leave_event’ Class and description MouseEvent .backend_bases.mouse leaves a figure LocationEvent .mouse button is released DrawEvent .pixels from left of canvas y y position .Matplotlib. line.on_motion) 12.figure. The redraw the figure.on_release) self.mpl_connect( ’button_press_event’.append(event.rect.figure.canvas.x and event.plot([0]. any character. self. self. Here is the solution: import numpy as np import matplotlib. rect): self.xdata. and add those deltas to the origin of the rectangle you stored.figure. ‘up’.mpl_connect( ’motion_notify_event’.rect.cidpress = self. compute the deltax and deltay of the mouse movement.ydata) self. motion and release mouse events. Hint: you will need to store the original xy location of the rectangle which is stored as rect.1 print ’click’.line. [0]) # empty line linebuilder = LineBuilder(line) plt.draw() fig = plt. so we have access to the data and pixel coordinates in event.show() The MouseEvent that we just used is a LocationEvent.ys) self.inaxes!=self.xy and connect to the press. = ax. ‘shift’.canvas.xdata) self.Matplotlib. ‘down’ (up and down are used for scroll events) key the key pressed: None.cidmotion = self. or ‘control’ 12.set_title(’click to build line segments’) line. 1.axes: return self.y location when dragged.figure() ax = fig. it has button button pressed None.line.ys.contains()) and if it does.0. ‘win’. store the rectangle xy and the location of the mouse click in data coords.append(event.cidrelease = self.2.set_data(self.canvas.patches.mpl_connect( ’button_release_event’. 3.1 Draggable rectangle exercise Write draggable rectangle class that is initialized with a Rectangle instance but will move its x. just reset all the button press data you stored as None. self. In the motion event callback.pyplot as plt class DraggableRectangle: def __init__(self.rect = rect self.figure.add_subplot(111) ax.2. Release 1. When the mouse is pressed. self. In addition to the LocationEvent attributes. Event attributes 99 .on_press) self. 2. On the button release event.xs.xs. event if event.press = None def connect(self): ’connect to all the events we need’ self.Rectangle.rect. check to see if the click occurs over your rectangle (see matplotlib.canvas. mpl_disconnect(self. x0+dx) self.xy self.draw() def disconnect(self): ’disconnect all the stored connection ids’ self.scipy.1 def on_press(self.mpl_disconnect(self.cidrelease) self. dx=%f. see # http://www.draw() def on_release(self. event. Extra credit solution: # draggable rectangle with the animation blit techniques.canvas.mpl_disconnect(self. y0.0. y0 = self.figure.canvas.rect. 20*np. xpress=%f.axes: return contains.xdata.connect() drs. event.org/Cookbook/Matplotlib/Animations import numpy as np 100 Chapter 12.cidpress) self.xdata.rect.ypress #print ’x0=%f.rect.rect. ypress = self.figure() ax = fig.rect. xpress.set_y(y0+dy) self.contains(event) if not contains: return print ’event contains’. xpress.ydata .press is None: return if event.inaxes != self.rect.figure.rect. Release 1.xdata .set_x(x0+dx) self.press = x0. Event handling and picking . y0.press dx = event. event): ’on motion we will move the rect if the mouse is over us’ if self.rect.xy x0.canvas.append(dr) plt.ydata def on_motion(self.xpress dy = event.xdata=%f.add_subplot(111) rects = ax. dx.show() Extra credit: use the animation blit techniques discussed in the animations recipe to make the animated drawing faster and smoother. self.bar(range(10).press = None self.rect.figure.rect.figure. event.figure.canvas. event): ’on release we reset the press data’ self.axes: return x0.Matplotlib. x0+dx=%f’%(x0.rand(10)) drs = [] for rect in rects: dr = DraggableRectangle(rect) dr. event.inaxes != self.rect.rect.canvas.cidmotion) fig = plt. attrd = self. event): ’on button press we will see if the mouse is over us and store some data’ if event.random. self. Release 1.draw() self.inaxes != self.canvas.rect. event): ’on motion we will move the rect if the mouse is over us’ if DraggableRectangle.xdata .xpress dy = event.bbox) # now redraw just the rectangle axes.set_x(x0+dx) self.axes. self.lock is not self: return if event.figure.0.figure.set_y(y0+dy) 12.on_release) self. y0.background = canvas.rect.xy x0. event): ’on button press we will see if the mouse is over us and store some data’ if event.pyplot as plt class DraggableRectangle: lock = None # only one can be animated at a time def __init__(self.cidpress = self.axes: return if DraggableRectangle. y0.press dx = event.mpl_connect( ’button_release_event’.set_animated(True) canvas.ypress self. event.rect.rect.2. y0 = self.canvas.press = None self.ydata DraggableRectangle.rect. rect): self.inaxes != self.canvas axes = self.bbox) def on_motion(self.1 import matplotlib.rect = rect self.rect.axes self.figure.rect. Event attributes 101 .copy_from_bbox(self.draw_artist(self. ypress = self.rect.xy self. xpress.rect.rect.mpl_connect( ’button_press_event’.blit(axes.canvas.rect.xdata.lock = self # draw everything but the selected rectangle and store the pixel buffer canvas = self.figure. event.axes: return x0. attrd = self.press = x0.Matplotlib. self.rect) # and blit just the redrawn area canvas.rect.on_press) self. self.ydata .contains(event) if not contains: return print ’event contains’.lock is not None: return contains.cidrelease = self.cidmotion = self.on_motion) def on_press(self.background = None def connect(self): ’connect to all the events we need’ self.rect.mpl_connect( ’motion_notify_event’.rect. random.figure.restore_region(self.add_subplot(111) rects = ax.figure.canvas.canvas.figure.rand(10)) drs = [] for rect in rects: dr = DraggableRectangle(rect) dr. Release 1.rect.connect() drs. 20*np. event): ’on release we reset the press data’ if DraggableRectangle.show() 12.bar(range(10).3 Mouse enter and leave If you want to be notified when the mouse enters or leaves a figure or axes.rect.background) # redraw just the current rectangle axes. Event handling and picking .figure.rect.rect.lock is not self: return self.draw_artist(self.Matplotlib.press = None DraggableRectangle.append(dr) plt.mpl_disconnect(self.blit(axes.canvas.mpl_disconnect(self. you can connect to the figure/axes enter/leave events.lock = None # turn off the rect animation property and reset the background self.bbox) def on_release(self.1 canvas = self.axes # restore the background region canvas.background = None # redraw the full figure self.mpl_disconnect(self.cidpress) self.set_animated(False) self.canvas.draw() def disconnect(self): ’disconnect all the stored connection ids’ self. Here is a simple example that changes the colors of the axes and figure background that the mouse is over: """ Illustrate the figure and axes enter and leave events by changing the 102 Chapter 12.cidmotion) fig = plt.cidrelease) self.canvas axes = self.rect.0.rect.figure() ax = fig.rect.rect) # blit just the redrawn area canvas.figure. enter_figure) fig1.mpl_connect(’axes_leave_event’.0.set_facecolor(’white’) event.canvas.mpl_connect(’axes_enter_event’.. enter_axes) fig2.canvas. Release 1. Object picking 103 .inaxes event. enter_axes) fig1. Patch. Text. etc.patch. leave_axes) fig2 = plt. Polygon. event. AxesImage.inaxes event.set_facecolor(’red’) event.mpl_connect(’figure_enter_event’.canvas.add_subplot(212) fig2.mpl_connect(’figure_leave_event’.figure event. leave_figure) fig2.figure.draw() def enter_figure(event): print ’enter_figure’.figure.canvas.pyplot as plt def enter_axes(event): print ’enter_axes’.Matplotlib.show() 12.mpl_connect(’axes_leave_event’.suptitle(’mouse hover over figure or axes to trigger events’) ax1 = fig1. leave_axes) plt.canvas.add_subplot(211) ax2 = fig2.) 12.canvas.1 frame colors on enter and leave """ import matplotlib.suptitle(’mouse hover over figure or axes to trigger events’) ax1 = fig2.canvas.canvas.canvas.canvas. enter_figure) fig2.canvas.patch. leave_figure) fig1.4.canvas. event.draw() def leave_figure(event): print ’leave_figure’.figure event.canvas..figure() fig1.add_subplot(212) fig1. event.set_facecolor(’grey’) event. event.inaxes.canvas.canvas.patch.mpl_connect(’figure_leave_event’.add_subplot(211) ax2 = fig1.patch.draw() fig1 = plt.mpl_connect(’axes_enter_event’.set_facecolor(’yellow’) event.inaxes.canvas.draw() def leave_axes(event): print ’leave_axes’.mpl_connect(’figure_enter_event’.figure() fig2.4 Object picking You can enable picking by setting the picker property of an Artist (eg a matplotlib Line2D. See pick() for details on the PickEvent properties of the line. Line2D attaches the ind property. The mouse event in turn has attributes like x and y (the coords in display space. certain artists like Line2D and PatchCollection may attach additional meta data like the indices into the data that meet the picker criteria (eg all the points in the line that are within the specified epsilon tolerance) 12. mouseevent) to determine the hit test. For example..pyplot as plt 104 Chapter 12. it is a user supplied function which determines whether the artist is hit by the mouse event. Here is the code: import numpy as np import matplotlib. so it represents a tolerance in points (72 points per inch). ydata (the coords in data space).artist # now do something with this. If the mouse event is over the artist.4. Release 1..0. function if picker is callable. eg the indices of the data within epsilon of the pick event. bottom) and xdata. Different matplotlib Artists can attach different data to the PickEvent. Our onpick callback function simply prints the data that are under the pick location.mouseevent artist = event. we set the line picker property to a scalar. which Axes the mouse is over. and has the indices of the data vertices that are within the pick distance tolerance. artist the Artist that generated the pick event. Event handling and picking .1 There are a variety of meanings of the picker property: None picking is disabled for this artist (default) boolean if True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist float if picker is a number it is interpreted as an epsilon tolerance in points and the the artist will fire off an event if its data is within epsilon of the mouse event. props = picker(artist. Additionally.Matplotlib. The PickEvent which is passed to your callback is always fired with two attributes: mouseevent the mouse event that generate the pick event. which keys were pressed. For some artists like lines and patch collections. you need to connect to the figure canvas pick_event to get pick callbacks on mouse press events. eg pixels from left. the artist may provide additional data to the pick event that is generated. The signature is hit. you can get information about which buttons were pressed. return hit=True and props is a dictionary of properties you want added to the PickEvent attributes After you have enabled an artist for picking by setting the picker property.MouseEvent for details. Additionally. The onpick callback function will be called when the pick event it within the tolerance distance from the line. which are the indices into the line data under the pick point.backend_bases. etc. Eg: def pick_handler(event): mouseevent = event.1 Simple picking example In the example below. See matplotlib. random.1 fig = plt.canvas. ydata[ind]) fig. onpick) plt.set_title(’click on point to plot time series’) line. axis=1) fig = plt.ind) 12.pyplot as plt X = np. and plot the original time series of the data that generated the clicked on points.4.rand(100.Matplotlib. picker=5) # 5 points tolerance def onpick(event): if event.figure() ax = fig. If more than one point is within the tolerance of the clicked on point. you can use multiple subplots to plot the multiple time series.show() 12. picker=5) # 5 points tolerance def onpick(event): thisline = event.set_title(’click on points’) line.4. plot the raw data from the dataset that generated the mean and stddev """ import numpy as np import matplotlib.mpl_connect(’pick_event’.random.std(X. 1000) xs = np. Connect the line created by the plot command to the pick event. = ax. axis=1) ys = np.rand(100).0.mean(X. ’o’. ys. Release 1. When you click on one of the mu. ’o’. zip(xdata[ind]. Object picking 105 . = ax.plot(xs.get_xdata() ydata = thisline. sigma points. Exercise solution: """ compute the mean and stddev of 100 data sets and plot mean vs stddev.add_subplot(111) ax.2 Picking exercise Create a data set of 100 arrays of 1000 Gaussian random numbers and compute the sample mean and standard deviation of each of them (hint: numpy arrays have a mean and std method) and make a xy marker plot of the 100 means vs the 100 standard deviations.plot(np.get_ydata() ind = event.add_subplot(111) ax.artist!=line: return True N = len(event.artist xdata = thisline.figure() ax = fig.ind print ’onpick points:’. Event handling and picking .1 if not N: return True figi = plt. transform=ax. va=’top’) ax.1.Matplotlib.subplotnum+1) ax. ys[dataind]). onpick) plt.text(0.ind): ax = figi. Release 1.0.canvas.5) figi.show() return True fig.transAxes.mpl_connect(’pick_event’.set_ylim(-0.3f ’%(xs[dataind].05.5. ’mu=%1.add_subplot(N. 0.plot(X[dataind]) ax.figure() for subplotnum.show() 106 Chapter 12. dataind in enumerate(event. 1.3f \nsigma=%1.9. the axes coordinate system. the transformation object you should use to work in that coordinate system. The transformations also know how to invert themselves. The table below summarizes the existing coordinate systems. Whenever you add data to the axes. 13. and -1 to 1 on the y-axis. most commonly updated with the set_xlim() and set_ylim() methods.1) is top right of the axes fig. controlled by the xlim and ylim ax. In the Transformation Object column. and you want to know where the mouse click or key-press occurred in your data coordinate system.CHAPTER THIRTEEN TRANSFORMATIONS TUTORIAL Like any graphics packages.0) is the bottom left of the display. height) is the top right of the display in pixels All of the transformation objects in the table above take inputs in their coordinate system. the data coordinate system. That is why the display coordinate system has None for the Transformation Object column – it already is in display coordinates.transforms). in the figure below. and (1.0) is bottom left of the figure. and the description of that system.transFigure coordinate system of the Figure. Coordinate data axes figure display TransforDescription mation Object ax. (0. which typically occur in display space. to go from display back to the native coordinate system. 107 . and (width.1) is top right of the figure None This is the pixel coordinate system of the display. matplotlib is built on top of a transformation framework to easily move between coordinate systems. as it happens under the hood. it helps to have an understanding of these objects so you can reuse the existing transformations matplotlib makes available to you.transAxes The coordinate system of the Axes. you won’t need to think about this. and transform the input to the display coordinate system. and fig is a Figure instance. but as you push the limits of custom figure generation. ax is a Axes instance. the data limits stretch from 0 to 10 on the x-axis. For example. and the display coordinate system. the figure coordinate system. (0.transData The userland data coordinate system. (0.1 Data coordinates Let’s start with the most commonly used coordinate. or create your own (see matplotlib. and The (1. matplotlib updates the datalimits. the userland data coordinate system.0) is bottom left of the axes. In 95% of your plotting. This is particularly useful when processing events from the user interface. sin(2*np.transData.1 import numpy as np import matplotlib.5 1.arange(0.transform([(5. Transformations Tutorial . 10. (1.5 0.005) y = np.set_ylim(-1.0 0.Matplotlib.175. Release 1.00 2 4 6 8 10 You can use the ax.2)]) Out[16]: 108 Chapter 13. either a single point or a sequence of points as shown below: In [14]: type(ax.0 0. 0.transData instance to transform from your data to your display coordinate system.) * np.transData. y) ax. 0).exp(-x/2.transform((5.add_subplot(111) ax.figure() ax = fig.transforms. 10) ax.set_xlim(0.0.CompositeGenericTransform’> In [15]: ax.show() 1.transData) Out[14]: <class ’ matplotlib.plot(x. 247. 1) plt.pyplot as plt x = np.pi*x) fig = plt. 0)) Out[15]: array([ 335. ]) In [16]: ax. 13.2 ]. 642..Matplotlib.CompositeGenericTransform’> In [43]: inv. ]]) You can use the inverted() method to create a transform which will take you from display to data coordinates: In [41]: inv = ax. 247. This is one good reason why you rarely want to work in display space.5 1. This is because the display point was computed before the figure was displayed.0. and the GUI backend may slightly resize the figure when it is created.inverted() In [42]: type(inv) Out[42]: <class ’ matplotlib.175. Data coordinates 109 .0 0. 0.5.]) 247. 180. the exact values of the display coordinates may differ if you have a different window size or dpi setting.5 0.0 0.transData.1 array([[ 335. Out[43]: array([ 5. see Event handling and picking. you may also find that the two arrows for the data and display annotations do not point to exactly the same point.0) data = (5. 1.)) If your are typing along with this tutorial. the display labeled points are probably not the same as in the ipython session because the documentation figure size defaults are different. in the figure below.175.transform((335. 0. [ 132.0.0) 2 4 6 8 10 Note: If you run the source code in the example above in a GUI backend. Likewise.1. The effect is more pronounced if you resize the figure yourself. Release 1.transforms.435.00 display = (225. but you can connect to the ’on_draw’ Event to update figure coordinates on figure draws. 1. import numpy as np import matplotlib.patches as patches 110 Chapter 13. the data limits are updated so the transformation yields a new display point. Use the pan/zoom tool to move around.transData.set_ylim(-1. but this is less useful in my experience than using ax.figure() for i. and overlays a semi-transparent Circle centered in the middle of the axes with a radius one quarter of the axes – if your axes does not preserve aspect ratio (see set_aspect()).transAxes for placing text.1. You can also refer to points outside the range. import numpy as np import matplotlib. More on this later when we talk about the Bbox. eg. both are altered. fontsize=16. 0)) Out[56]: array([ 335. 181. 20) In [58]: ax. ‘C’.add_subplot(2.13333333]) In [57]: ax. va=’top’) plt.transform((5. In [54]: ax. ’B’.transAxes. or manually change the data xlim and ylim.Matplotlib.0) is the bottom left of your axes or subplot. 2) In [56]: ax.2) Out[55]: (-1. ‘D’ as you often see in journals.675 .text(0. here is a silly example which plots some random dots in data space.show() You can also make lines or patches in the axes coordinate system. (0.0) is the top right. Release 1.0.5) is the center. the upper left of the axes pane.transform((5. ‘B’.1) is to the left and above your axes. but the circle will remain fixed because it is not in data coordinates and will always remain at the center of the axes. 0)) Out[58]: array([-171. label.pyplot as plt fig = plt. ’D’)): ax = fig. ’C’. transform=ax. 0.transData. 247. and you will see the data move.transform((5. axes is probably the second most useful coordinate system.05.i+1) ax. ]) In [55]: ax. This coordinate system is extremely useful when placing text in your axes. only the y-display coordinate is altered.95. label in enumerate((’A’.175 .2 Axes coordinates After the data coordinate system. 1. 181. 0)) Out[54]: array([ 335.1 When you change the x or y limits of your axes.pyplot as plt import matplotlib.20) Out[57]: (10.13333333]) 13.transData. Transformations Tutorial . and (1.5. 0. and when we change the xlim too.2. Note that when we just change the ylim. and have that location remain fixed when you pan or zoom.set_xlim(10. because you often want a text bubble in a fixed. so (-0.0. Nonetheless.175. Here the point (0. this will look like an ellipse. location. Here is a simple example that creates four panels and labels them ‘A’. fontweight=’bold’. 4 0.4 0.6 0.2 0.Matplotlib.transAxes.2 0. 13.1 1.5.6 0. y.0 1. This trick only works for separable transformations. etc.5) ax. 1000) ax.8 0.8 0. ’go’) # plot some data in data coordinates circ = patches.2 0.4 0.0 1. axhspan().6 0.2 0.0 0. transform=ax.0 A B 0.8 1. facecolor=’yellow’.add_subplot(111) x. alpha=0.6 0.figure() ax = fig.add_patch(circ) plt.rand(2. 0.4 0.8 1. like you see in normal Cartesian coordinate systems.0 0. we have built in functions to make them easy to plot (see axhline().plot(x.8 0.6 0. but not on inseparable transformations like the PolarTransform.0 0.2 0.2 0.0 0.show() 13.0 1. axvspan()) but for didactic purposes we will implement the horizontal span here using a blended transformation.0 0.4 0.0 0.4 0.0 D C 0. y = 10*np. pan or zoom level.4 0.5). axvline(). In fact these blended lines and spans are so useful.6 0.3 Blended transformations Drawing in blended coordinate spaces which mix axes with data coordinates is extremely useful.4 0.6 0.3. 0.0 0. Blended transformations 111 .0 0.2 0.0 0.Circle((0.0 0.8 1.25.0.8 1.2 0. for example to create a horizontal span which highlights some region of the y-data but spans across the x-axis regardless of the data limits. Release 1.8 0.random.6 0.0 fig = plt. blended_transform_factory( ax.random. fontsize=16) # the x coords of this transformation are data.transAxes) # highlight the 1.transforms as transforms fig = plt.randn(1000) ax.Matplotlib. alpha=0.0).5) 112 Chapter 13. # We want x to be in data coordinates and y to # span from 0. 30) ax. width=1.1 10 8 6 4 2 00 import import import import 2 4 6 8 10 numpy as np matplotlib..2 stddev region with a span. Release 1.hist(x.0..figure() ax = fig. color=’yellow’.set_title(r’$\sigma=1 \/ \dots \/ \sigma=2$’.Rectangle((1.add_subplot(111) x = np.1 in axes coords rect = patches. transform=trans.pyplot as plt matplotlib.transData. Transformations Tutorial .patches as patches matplotlib. ax. and the # y coord are axes trans = transforms. height=1. So in the example above.axes. where you draw one object identical to the first just to the right of it.0.Matplotlib. One use for an offset is to create a shadow effect.get_xaxis_transform() and matplotlib.get_xaxis_transform() 13.4 Using offset transforms to create a shadow effect One use of transformations is to create a new transformation that is offset from another transformation. adjusting the zorder to make sure the shadow is drawn first and then the object 13. Using offset transforms to create a shadow effect 113 .Axes.show() 120 100 80 60 40 20 04 3 2 σ =1 σ =2 1 0 1 2 3 4 Note: The blended transformations where x is in data coords and y in axes coordinates is so useful that we have helper methods to return the versions mpl uses internally for drawing ticks. etc.Axes.get_yaxis_transform(). ticklabels.add_patch(rect) plt. The methods are matplotlib. so that the shift effect is constant at different zoom levels and dpi settings. eg to place one object shifted a bit relative to another object. Release 1.axes. Typically you want the shift to be in some physical dimension. the call to blended_transform_factory() can be replaced by get_xaxis_transform: trans = ax.1 ax.4. like points or inches rather than in data coordinates. and just below it. wikipedia. color=’gray’. dy = 2/72. Transformations Tutorial . we’ll create the offset transform ourselves.pi*x) line.offset_copy(). fig. 0.ScaledTranslation(dx.figure() ax = fig. It is instantiated with: trans = ScaledTranslation(xt. yt.set_title(’creating a shadow effect with an offset transform’) plt.dpi_scale_trans transformation for the scale_trans argument.transData + offset # now plot the same data with our offset transform.transforms as transforms fig = plt. Note the use of the plus operator in: offset = transforms.5*line. your figure will look the same regardless of the dpi resolution it is saved in. 2. dy.. # use the zorder to make sure we are below the line ax.plot(x.plot(x.dpi_scale_trans) shadow_transform = ax.ScaledTranslation(dx. In typography. a‘point <http://en. transform=shadow_transform. zorder=0.dpi_scale_trans) shadow_transform = ax. -2/72. y. and by specifying your offsets in points. = ax.pyplot as plt matplotlib. The dpi and inches offset is a common-enough use case that we have a special helper function to create it in matplotlib. scale_trans) where xt and yt are the translation offsets. Release 1..show() 114 Chapter 13. fig. lw=3. and scale_trans is a transformation which scales xt and yt at transformation time before applying the offsets.1 it is shadowing above it.sin(2*np.add_subplot(111) # make a simple sine wave x = np. But in the example below. dy.patches as patches matplotlib.0. The transforms module has a helper transformation ScaledTranslation. offset = transforms.transforms. import import import import numpy as np matplotlib.arange(0.Matplotlib. This code says: first apply the data transformation ax. and down 2 points dx. A typical use case is to use the figure fig.01) y = np. to first scale xt and yt specified in points to display space before doing the final offset.transData and then translate the data by dx and dy points. lw=3. which returns a new transform with an added offset. color=’blue’) # shift the object over 2 points..get_zorder()) ax.transData + offset showing that can chain transformations using the addition operator.org/wiki/Point_%28typography%29>‘_ is 1/72 inches. y. 1) corners of the axes or subplot bounding box to display space. This is not true of all possible transformations.0 0. self.5 1.transLimits is the transformation that takes you from data to axes coordinates.5 The transformation pipeline The ax.e. We can see this in action here 13. which maps the (0.0 0. taking care to provide a clean API that segregated the nonlinear projections and scales that happen in polar and logarithmic plots. There is an efficiency here.transData = self. but you may not need to compute the potentially expensive nonlinear scales or projections on simple navigation events.0).0.transAxes) We’ve been introduced to the transAxes instance above in Axes coordinates.1 creating a shadow effect with an offset transform 1. Here is how the ax.transLimits + self. and then apply them to coordinates in one step.transScale + (self.5. It is also possible to multiply affine transformation matrices together. so let’s look at these other two pieces.0 0. because you can pan and zoom in your axes which affects the affine transformation.0 0.5 2.5 1.transData instance is defined in the basic separable axis Axes class: self. from the linear affine transformations that happen when you pan and zoom. (1. it maps your view xlim and ylim to the unit space of the axes (and transAxes then takes that unit space to display space).Matplotlib. Michael Droettboom implemented the transformations framework. Release 1.5 0.0 13. The transformation pipeline 115 .0 1.. i.transData transform we have been working with in this tutorial is a composite of three different transformations that comprise the transformation pipeline from data -> display coordinates. 0. the xaxis updates its scale to a matplotlib. There are several projection examples in the matplotlib. For example.0)) Out[87]: array([ 0. The transData matplotlib. when you call ax. Michael Droettboom has provided a nice tutorial example of creating a hammer projection axes. 116 Chapter 13.transProjectionAffine + self.projections.transLimits.1)) Out[86]: array([ 1.transProjection + \ (self.PolarAxes is similar to that for the typical separable matplotlib Axes. since the basic matplotlib axes has linear scale.polar. When an Axes is initially setup. with one additional piece transProjection: self. see apicustom_projection_example.]) In [85]: ax..5. For non-separable axes the PolarAxes. Transformations Tutorial .5]) and we can use this same inverted transformation to go from the unit axes coordinates back to data coordinates. eg.1) Out[82]: (-1. there is one more piece to consider.set_xlim(0.projections package.transform((0. 1) In [84]: ax. latitude and longitude for map data. and the best way to learn more is to open the source for those packages and see how to make your own.transAxes) transProjection handles the projection from the space.transLimits.Matplotlib. The scales transforms are properties of the respective xaxis and yaxis Axis instances. 10) In [82]: ax. eg.transScale + self. 10) Out[81]: (0.transScale attribute is set to handle the nonlinear projection.transScale attribute.-1)) Out[84]: array([ 0. for logarithmic axes.transform((10.25)) Out[90]: array([ 2.scale. 1.transform((5.]) In [86]: ax.transLimits. Release 1. but when you call a logarithmic scaling function like semilogx() or explicitly set the scale to logarithmic with set_xscale().-1)) Out[85]: array([ 1. 0.5. then the ax. since matplotlib supports extensible axes and projections.transData = self. or radius and theta for polar data. 0.transform((10.transform((0. 0. -0.transLimits. to a separable Cartesian coordinate system..25.set_ylim(-1. the projection transformation.]) In [87]: ax.1 In [80]: ax = subplot(111) In [81]: ax.set_xscale(’log’)..LogScale instance. In [90]: inv.5]) The final piece is the self. 0. this is just set to the identity transform. which is responsible for the optional non-linear scaling of the data. .figure() ax = fig. 0. 1. lw=2) ax.).LINETO. top right.patches as patches verts = [ (0.LINETO. bottom ignored codes = [Path.set_ylim(-2. 0.. 1. Path. (1. 0.show() The following path codes are recognized 117 ...add_subplot(111) patch = patches.).PathPatch(path..). ] path = Path(verts. (1. Path.pyplot as plt from matplotlib.y) vertices. For example to draw the unit rectangle from (0.patch objects is the Path.2) ax. bottom left. facecolor=’orange’.set_xlim(-2. Path.LINETO. codes) fig = plt.2) array of (x.). we could use this code import matplotlib. (0.CLOSEPOLY. top right.CHAPTER FOURTEEN PATH TUTORIAL The object underlying all of the matplotlib.).add_patch(patch) ax.0) to (1. lineto. (0.1).path import Path import matplotlib. ] # # # # # left. Path. curveto commands to draw simple and compound outlines consisting of line segments and splines. which supports the standard set of moveto. and a N-length array of path codes. The Path is instantiated with a (N.2) plt.MOVETO. Matplotlib.5 1.5 1. and the end point import matplotlib.0 0. Draw a line segment to the start point of the current polyline. Draw a cubic Bézier curve from the current position.5 2.pyplot as plt from matplotlib.0. Path Tutorial .5 2. Release 1.1 Bézier example Some of the path components require multiple vertices to specify them: for example CURVE 3 is a bézier curve with one control point and one end point.02.0 1.0 0. the two control points.0 0.0 0.0 1.path import Path 118 Chapter 14.5 0. The example below shows a CURVE4 Bézier spline – the bézier curve will be contained in the convex hull of the start point. with the given control points.1 2. to the given end point. Draw a line from the current position to the given vertex. to the given end point. 1 endpoint) CLOSEPOLY (point itself is 1 ignored) 14. Draw a quadratic Bézier curve from the current position.5 0. with the given control point. and CURVE4 has three vertices for the two control points and the end point.5 1.0 1.0 1. 1 1 2 (1 control point.5 1. 1 endpoint) CURVE4 3 (2 control points.0 Code STOP MOVETO LINETO CURVE3 Vertices 1 (ignored) Description A marker for the end of the entire path (currently not required and ignored) Pick up the pen and move to the given vertex. -0. The reason bar creates a list of rectangles and not a compound path is largely historical: the Path code is comparatively new and bar predates it. are implemented with simple path. (0. ys = zip(*verts) ax. the length of bins is 1 greater than the length of n in the example below: 14.1.plot(xs.2. color=’black’. eg a bunch of Rectangles. 1. so here we will cover how to create compound paths. 0. ys.8.. ’P2’) ax. Plotting functions like hist() and bar(). Because numpy returns the bin edges and not centers. which create a number of primitives. ms=10) ax.1 import matplotlib.05. Path. in case you need to do so in your own code for efficiency reasons.85.add_subplot(111) patch = patches.8). (0.2.show() 14.patches as patches verts = [ (0.2 Compound paths All of the simple patch primitives in matplotlib. While we could change it now. Release 1. ’P3’) ax. codes) fig = plt.).PathPatch(path. 1. 1. Polygon.set_ylim(-0.MOVETO. replacing the functionality in bar.add_patch(patch) xs. ’P0’) ax.15.1) plt. 1. Compound paths 119 .Matplotlib.05. 0. Path.85. lw=2.figure() ax = fig.CURVE4. ] path = Path(verts.). facecolor=’none’. can usually be implemented more efficiently using a compound path. Rectangle. eg you are creating an animated bar plot.05.05. -0.). (1. lw=2) ax. 0. it would break old code.1.CURVE4.text(1. ] # # # # P0 P1 P2 P3 codes = [Path.. Circle.text(0.text(-0. ’x--’. First we’ll create some random normally distributed data and compute the histogram. etc.1) ax.0. 0. ’P1’) ax.text(0. Path.05. We will make the histogram chart by creating a series of rectangles for each histogram bar: the rectangle width is the bin width and the rectangle height is the number of datapoints in that bin.CURVE4.set_xlim(-0. zeros(len(left)) top = bottom + n Now we have to construct our compound path.Path.array(bins[:-1]) right = np.0.0 P0 0.2 0. bottom. bins = np. arrays below is len(n).CLOSEPOLY verts[0::5.8 1. Release 1. and 1 for the CLOSEPOLY.array(bins[1:]) bottom = np.0] = left 120 Chapter 14.LINETO codes[0::5] = path.6 0. 2)) codes = np.MOVETO codes[4::5] = path. As indicated in the table above.histogram(data. 100) We’ll now extract the corners of the rectangles.2 0.0 P1 P2 P3 0. LINETO and CLOSEPOLY for each rectangle.Path. Path Tutorial . etc.Path.zeros((nverts. 3 for the LINETO. Each of the left.Matplotlib.8 0. we need 5 vertices: 1 for the MOVETO.1 1.6 0.4 0. the vertex for the closepoly is ignored but we still need it to keep the codes aligned with the vertices: nverts = nrects*(1+3+1) verts = np.random. For each rectangle.4 0.ones(nverts.0 # histogram our data with numpy data = np.0 0. where n is the array of counts for each histogram bar: # get the corners of the rectangles for the histogram left = np. int) * path.randn(1000) n. which will consist of a series of MOVETO. 0] verts[1::5.2.0] verts[2::5. edgecolor=’yellow’.0] verts[3::5.1] = = = = = = = bottom left top right top right bottom All that remains is to create the path.Path(verts.1] verts[3::5. facecolor=’green’.1 verts[0::5. Release 1.Matplotlib.5) ax. and add it to our axes: barpath = path. alpha=0.0.1] verts[1::5.add_patch(patch) Here is the result 30 25 20 15 10 5 03 2 1 0 1 2 14. Compound paths 121 .1] verts[2::5. codes) patch = patches.PathPatch(barpath. attach it to a PathPatch. 1 122 Chapter 14. Release 1.0.Matplotlib. Path Tutorial . text() and annotate()! 15.1 Annotating with Text with Box Let’s start with a simple example.CHAPTER FIFTEEN ANNOTATING AXES Do not proceed unless you already have read Annotating text. 4 3 2 1 0 1 2 3 44 3 2 1 0 1 2 3 4 Sample B Dir ec tio n Sample A 123 . An arrow connecting two point (xy & xytext) can be optionally drawn by specifying the arrowprops argument.3. lw=2) t = ax. can be accessed and modified as usual. To draw only an arrow. textcoords=’offset points’. xycoords=’data’.pad=0. 124 Chapter 15. size=15. ha="center".set_boxstyle("rarrow". Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0. use set_boxstyle method.text(0. ax. bb. bbox_props = dict(boxstyle="rarrow. edgewidth. Release 1.3 Note that the attributes arguments can be specified within the style name with separating comma (this form can be used as “boxstyle” value of bbox argument when initializing the text instance) bb.rounding_size=None pad=0. bbox=bbox_props) The patch object associated with the text can be accessed by: bb = t. fc="cyan". the annotated point is specified in the data coordinate and the annotating text in offset points. See annotate() for available coordinate systems.rounding_size=None pad=0. a box around the text is drawn.get_bbox_patch() The return value is an instance of FancyBboxPatch and the patch properties like facecolor. and when given. etc. xy=(x1.pad=0. va="center".3.3. ec="b".0.6") 15.3 pad=0. y1). xytext=(x2. following box styles are implemented.3". rotation=45.1 The text() function in the pyplot module (or text method of the Axes class) takes bbox keyword argument.Matplotlib.tooth_size=None pad=0. To change the shape of the box.3 pad=0. 0. pad=0.3.2 Annotating with Arrow The annotate() function in the pyplot module (or annotate method of the Axes class) is used to draw an arrow connecting two points on the plot. Annotating Axes .annotate("Annotation".tooth_size=None pad=0. Often. Currently. "Direction".set_boxstyle("rarrow. y2). ) This annotates a point at xy in the given coordinate (xycoords) with the text at xytext given in textcoords.6) The arguments are the name of the box style with its attributes as keyword arguments. use empty string as the first argument. 1 square sawtooth roundtooth rarrow larrow round4 round 15. Release 1.0. Annotating with Arrow 125 .2.Matplotlib. 2). 3. This is controlled by connectionstyle key value. Release 1.0 The arrow drawing takes a few steps. ) 1. Annotating Axes . xytext=(0. arrowprops=dict(arrowstyle="->".2 0.annotate("".6 0. a connecting path between two points are created.4 0. the path is clipped to avoid the patch. 0.0 0.2 0. xycoords=’data’. connectionstyle="arc3").1 ax. which is controlled by the arrowstyle key value.8).0.4 0. xy=(0.8 1.8 0.Matplotlib. 0. 1. The path is transmuted to arrow patch.6 0. If patch object is given (patchA & patchB). 126 Chapter 15. 2.2. textcoords=’data’. The path is further shrunk by given amount of pixels (shirnkA & shrinkB) 4.0 0. connect clip shrink mutate The creation of the connecting path between two points is controlled by connectionstyle key and following styles are available.0 0.8. 3 angle. rad=5 arc. angleB=10. armA=0.armB=0. As will be discussed below.angle=None Note that “3” in angle3 and arc3 is meant to indicate that the resulting path is a quadratic spline segment (three control points).rad=0. angleA=90. angleB=0. angleA=0.angleB=0. armA=30.0. according to the given arrowstyle. rad=5 bar. armB=30. rad=0 bar.angleB=0 angleA=0. armA=30. (Warning : The behavior of the bar style is currently not well defined. 15.rad=0.rad=0.fraction=0.2.0 armA=0. rad=0 bar. it may be changed in the future). angle=180. angleB=0.3.0 rad=0. rad=0 arc. The behavior of each connection style is (limitedly) demonstrated in the example below.2 The connecting path (after clipping and shrinking) is then mutated to an arrow patch. fraction=0. angleB=0 arc3. angleA=-90. angleB=180.0. armB=40.armB=None.rad=-0. Annotating with Arrow 127 . angleB=90 arc3. angle3.1 Name angle angle3 arc arc3 bar Attrs angleA=90.3 angle.0.3 angle3. fraction=-0.Matplotlib. angleA=-90. angleB=180. angleA=-90.rad=0. rad=0 arc. angleA=-90. Release 1.angleB=0. angleA=-90.armA=None. angleB=0. angle.3 arc3. angleA=-90. some arrow style option only can be used when the connecting path is a quadratic spline.0 angleA=90. armB=30. fraction=-0. 2 tail_width=0.2 head_length=0.0) means lower-left corner and 128 Chapter 15.head_width=0.2 head_length=0. The values are normalized to the extent of the text.tail_width=0.5.2 head_length=0.4. Release 1.4.lengthB=0. the starting point is set to the center of the text extent.Matplotlib.4.5.tail_width=0.head_width=0. (0.head_width=0.2 head_length=0. By default. For these arrow styles.head_width=0.5 -> -[ -| > <<.4. This can be adjusted with relpos key value.0.angleB=None head_length=0.head_width=0.4. a box around the text can be drawn using the bbox argument.head_width=0.1 Name -> -[ -|> <<-> <|<|-|> fancy simple wedge Attrs None head_length=0. They are fancy.4. For example.4 head_length=0. and wedge.head_width=0. simple.2 head_length=0. you must use “angle3” or “arc3” connection style.shrink_factor=0.4.> <|- <|-| > ]]-[ fancy simple wedge |-| Some arrowstyles only work with connection style that generates a quadratic-spline segment.2.head_width=0.2 widthB=1.4. Annotating Axes . If the annotation string is given. As in the text command. the patchA is set to the bbox patch of the text by default.3.0. 0.4 0.8 0.4 0.2 0.2. Annotating with Arrow 129 .0 0.6 0.8 1.0 0.6 0.8 0.0 0.2 0.0 0.Matplotlib.0 Test 1.2 0. Release 1.2 0.4 0.6 0.0 0.0 Test 15.4 0.8 1.6 0.0 0.1 1. 2") ax.3 Placing Artist at the anchored location of the Axes There are class of artist that can be placed at the anchored location of the Axes.axes_grid.4 0.pad=0. If you want to draw a circle with fixed size of 20 pixel x 20 pixel (radius = 10 pixel). Release 1. from mpl_toolkits.axes_grid. loc=1. The initial size only matters.6 0.2 0.add_artist(p1) 130 Chapter 15.drawing_area. 10). A simple application is when the size of the artist (or collection of artists) is known in pixel size during the time of creation.0 0.0 0.8 1.add_artist(at) Test The loc keyword has same meaning as in the legend command.patch.6 0.rounding_size=0. 10) ada.1 (1.2 0. 20.8 0. 1. Annotating Axes . A common example is the legend.set_boxstyle("round. ) at. And user can add arbitrary artist to the drawing area. 0. The instance is created with a size of the drawing area (in pixel).Matplotlib..1) means top-right.anchored_artists import AnchoredText at = AnchoredText("Figure 1a". from mpl_toolkits. Note that the extents of the artists that are added to the drawing area has nothing to do with the placement of the drawing area itself.0. pad=0.axes_grid. This type of artists can be created by using the OffsetBox class.anchored_artists.anchored_artists import AnchoredDrawingArea ada = AnchoredDrawingArea(20. A few predefined classes are available in mpl_toolkits. you can utilize AnchoredDrawingArea. For example.0 15. 0. prop=dict(size=8).4 0. loc=2. frameon=False) p1 = Circle((10.0 0.. frameon=True. 0 p2 = Circle((30.0 0.add_artist(p2) The artists that are added to the drawing area should not have transform set (they will be overridden) and the dimension of those artists are interpreted as a pixel coordinate.4 0. Placing Artist at the anchored location of the Axes 131 .0 0.4 0.2 0. fc="r") ada.8 1. 1.axes_grid. 5. loc=2) 15.2 Figure 1a 0. Release 1..e.Matplotlib.3.6 0. This is similar to AnchoredDrawingArea except that the extent of the artist is determined during the drawing time respecting the specified transform. i.0 0.0 0.0.1 1.4 0.6 0.0 0. from mpl_toolkits.drawing_area. the radius of the circles in above example are 10 pixel and 5 pixel.8 0.8 0.transData. You can use AnchoredAuxTransformBox class. 10).anchored_artists import AnchoredAuxTransformBox box = AnchoredAuxTransformBox(ax.8 1.4 0. respectively.0 0.6 0.2 0. you want to your artists scale with data coordinate (or other coordinate than canvas pixel).6 0.2 0.0 Sometimes. 2 0.2 Test : 0.drawing_area.8 1.0 0. angle=30) # in data coordinates! box.6 0.4 0.1.0 0. Annotating Axes .1 and 0.4 in data coordinate and will be automatically scaled when the view limits of the axes change. this is how the legend is created).0).0 Note that unlike the legend.4.4 0. 1.0 0. width=0.Matplotlib.2 0.6 0. 1.2 0. 132 Chapter 15. you can have an arrangement(?) of artist as in the legend (as a matter of fact.8 0.6 0. the bbox_transform is set to IdentityTransform by default.0 0.6 0.add_artist(el) The ellipse in the above example will have width and height corresponds to 0. the bbox_to_anchor argument can be set.0 0. Release 1.4 0.0. height=0.1 el = Ellipse((0.0 0.8 1. Using the HPacker and VPacker.0 As in the legend.8 0.4 0. 4 0. following two commands give identical results 15. 0. fc="w"). For example.2 0. arrowprops=dict(arrowstyle="->")) 2. 0. # (1. Using Complex Coordinate with Annotation 133 .5.5) of the an1’s bbox xytext=(30. it means that an2 needs to be drawn later than an1. 1.Matplotlib.8 1.4 0. 0. xy=(0.transData.annotate("Test 1". bbox=dict(boxstyle="round".5). Transform instance.4 Using Complex Coordinate with Annotation The Annotation in matplotlib support several types of coordinate as described in Annotating text. xy=(0. Artist instance. 0. xy=(0. it is same as 2.5. va="center". xycoords="axes fraction") With this. 0. In most cases.5).5. fc="w")) an2 = ax.annotate("Test 2". xycoords=ax.5. it is same as 1 and if bbox is returned.6 Test 1 Test 2 0. xy=(1. you can annotate a point in other axes.0 0.6 0. ha="left". bbox=dict(boxstyle="round".5). xycoords=an1.5). ax.5.0. subplot(122) ax2. xy=(0.5).4.5). 0.0 0. For an advanced user who wants more control. ax1. For example.annotate("Test". an1 = ax. arrowprops=dict(arrowstyle="->")) 1. A callable object that returns an instance of either BboxBase or Transform. xytext=(0. xycoords=ax1. Release 1.0.8 0. ha="center". ax2 = subplot(121).annotate("Test".2 0. The xy value (or xytext) is interpreted as a fractional coordinate of the bbox (return value of get_window_extent) of the artist. xycoords="data". If a transform is returned. va="center". textcoords=ax2. it supports a few other options.0 0.annotate("Test".transData. textcoords="offset points".1 15.0 Note that it is your responsibility that the extent of the coordinate artist (an1 in above example) is determined before an2 gets drawn. 3.0). The callable object should take a single argument of renderer instance.transAxes) is identical to ax. textcoords=(an1.0 0.2)) ax=plt. bbox=dict(boxstyle="round". and 1 is in normalized axes coordinate. You may use an atist or transform as with a tuple. annotate("Test".figure(figsize=(3.axes([0. xycoords="data".5. Sometimes.2 0. 0. import matplotlib. 0.5). xycoords=an1. 0. xy=(0. ha="center". OffsetFrom is a helper class for such case. xycoords="data". 0. 0.Matplotlib.6 Test 1 0.figure(figsize=(3. For example.axes([0. "axes fraction")) 0.0).1). textcoords="offset points") an2 = ax.8 1. xy=(1. bbox=dict(boxstyle="round".5). 0. va="bottom".pyplot as plt plt. xycoords=an1. fc="w")) an2 = ax.).0 0.4 0.8 0. va="center". "axes fraction"). xycoords=an1. xy=(0.text import OffsetFrom Test 2 134 Chapter 15.annotate("Test 2".1.annotate("Test 2". A tuple of two coordinate specification. 0. 1. xy=(1.7]) an1 = ax. 1).1. import matplotlib. xytext=(30.5.1.5. xytext=(0.annotate("Test 2".annotate("Test 1". Release 1.1.5.pyplot as plt plt.6 0. fc="w")) from matplotlib. Annotating Axes . fc="w").annotate("Test 1". arrowprops=dict(arrowstyle="->")) plt.5).8. xytext=(30. xy=(0.8.get_window_extent. For example. but not from the annotated point but from other point. The first item is for x-coordinate and the second is for ycoordinate.5.0 5.2)) ax=plt. xycoords=("data".show() 1. ha="center". va="center".5). 0.0). ha="center". 0.1 an2 = ax.2 0. you want your annotation with some “offset points”.0.5 is in data coordinate. bbox=dict(boxstyle="round". 0.4 0.0 0.1. textcoords="offset points") 4. xy=(0.7]) an1 = ax. 0 You may take a look at this example pylab_examples-annotation_demo3. arrowprops=dict(arrowstyle="->")) plt.1 offset_from = OffsetFrom(an1.0 0. xyB=xy.inset_locator defines some patch classes useful for interconnect two axes. Using ConnectorPatch 135 . 0.5. coordsB="data".0 0.1. xycoords=an1" va="top".5. the ConnectorPatch is useful when you want to connect points in different axes. ha="center". 15. bbox=dict(boxstyle="round". xycoords="data".2. But. but you may want it to be added to the axes in the latter (?) of the axes drawing order to prevent overlap (?) by other axes. from matplotlib.1 Advanced Topics 15. axesA=ax1.2) con = ConnectionPatch(xyA=xy. While the ConnectorPatch instance can be added to any axes. While the annotate function is recommended in most of situation.Matplotlib. coordsA="data". fc="w").2 0.6 0. 15. 0).2 0.5.show() 1.5 Using ConnectorPatch The ConnectorPatch is like an annotation without a text.4 0. textcoords=offset_from. axesB=ax2) ax2. 0)) an2 = ax.0.1).0 0.5. Here is a simple example. xytext=(0. xy=(0.8 0. (0. 15. utilizing it will be straight forward.patches import ConnectionPatch xy = (0. # xytext is offset points from "xy=(0.add_artist(con) The above code connects point xy in data coordinate of ax1 to point xy int data coordinate of ax2. Release 1. Understanding the code requires some knowledge of how mpl’s transform works. -10).4 Test 2 0.6 Zoom effect between Axes mpl_toolkits.axes_grid.6 Test 1 0.annotate("Test 2". 0.8 1. 0.1 0. *height* : location and size of the box . y0.7 Define Custom BoxStyle You can use a custom box style. width.8 1._Base class. """ path = .Matplotlib.3 0.4 0._Base as demonstrated below. return the path of the box around it. *width*. height. *y0*.BoxStyle.5 0.pyplot as plt # we may derive from matplotlib.1 1.8 0.4 0.6 0.5 0.patches import BoxStyle import matplotlib.: def __call__(self. aspect_ratio=1.1 0.2 0. .2 0.4 0.0 0.BoxStyle. # You need to overide transmute method in this case. return path Here is a complete example.patches. x0.0 0.*aspect_ratio* : aspect-ration for the mutation. Release 1. it is recommended that you derive from the matplotlib. class MyStyle(BoxStyle.4 0.00. . Annotating Axes .0 0. The value for the boxstyle can be a callable object in following forms.2 0.patches.3 0.*mutation_size* : a reference scale for the mutation.0 0.): """ Given the location and size of the box.2 0._Base): 136 Chapter 15.0 Exception occurred rendering plot.. from matplotlib.*x0*. mutation_size.6 0.path import Path from matplotlib. 15.. However. 1 1. the *mutation_size* is the font size of the text. y0.Matplotlib. width.*mutation_size* : a reference scale for the mutation.__init__() def transmute(self. Test 15. """ # padding pad = mutation_size * self. height. self).8 1.8 0. Often. Define Custom BoxStyle 137 .0 """ A simple box. You don’t need to worry about the rotation as it is automatically taken care of.6 0. mutation_size): """ Given the location and size of the box.4 0.4 0. *height* : location and size of the box .3): """ The arguments need to be floating numbers and need to have default values.pad # width and height with padding added.*x0*. pad=0.6 0. x0. .0 0.0 0.pad = pad super(MyStyle.7.2 0. Release 1. """ def __init__(self. return the path of the box around it. *y0*. *width*.2 0.0 0. *pad* amount of padding """ self.0. _style_list["angled"] plt.subplot(111) ax. (x0. # boundary of the padded box x0. rotation=30.1 width. Path. ha="center". y0).2)) del BoxStyle.LINETO. Path.6 0. alpha=0. Path.LINETO. y0).0 138 Chapter 15.4 0.Matplotlib. (y0+y1)/2.3)) ax = plt.text(0. Path. x1. y1 = x0+width.2 0.figure(1.). size=30.LINETO.MOVETO. y0 + height cp = [(x0. va="center".2 0. y0).*pad. \ height + 2.0 0._style_list["angled"] = MyStyle plt. Annotating Axes st Te . "Test".5.4 0.5". Release 1. Path. y1).8 1. bbox=dict(boxstyle="angled. figsize=(3. (x1.show() 1. y1). y0 = x0-pad. (x1. y0)] com = [Path. height = width + 2.5. (x0.0 0.LINETO.LINETO.pad=0. 0. com) return path # register the custom style BoxStyle.CLOSEPOLY] path = Path(cp. (x0-pad. (x0. Path.*pad.8 0.0 0. y0-pad.6 0.0. See the source code of 15.py and check how each style class is defined.Matplotlib. you can define custom ConnectionStyle and custom ArrowStyle. Release 1. Define Custom BoxStyle 139 .0.1 Similarly. lib/matplotlib/patches.7. Matplotlib.1 140 Chapter 15. Annotating Axes .0. Release 1. np.Line2D object at 0xb7d8fec>] 16. matplotlib Axes support a sharex and sharey attribute.2 Easily creating subplots In early versions of matplotlib.lines. examples and code snippets that illustrate some of the useful idioms and tricks to make snazzier figures and overcome some matplotlib warts. sharex=ax1) In [100]: ax2.pi*t)) Out[100]: [<matplotlib. sharex=ax1.plot(t.Line2D object at 0x98719ec>] In [99]: ax2 = plt.add_subplot(223.add_subplot(221) fig.figure() fig. Eg # old fig = ax1 = ax2 = ax3 = ax3 = style plt.subplot(211) In [98]: ax1.subplot(212. if you wanted to use the pythonic API and create a figure instance and from that create a grid of subplots. np.pi*t)) Out[98]: [<matplotlib. possibly with shared axes. When you create a subplot() or axes() instance. 10.add_subplot(224.sin(2*np. sharex=ax1.CHAPTER SIXTEEN OUR FAVORITE RECIPES Here is a collection of short tutorials.1 Sharing axis limits and views It’s common to make two or more plots which share an axis.arange(0. sharex=ax1. you can pass in a keyword indicating what axes you want to share with In [96]: t = np.lines.add_subplot(222. 16. 0. sharey=ax1) 141 .sin(4*np. sharey=ax1) fig. sharey=ax1) fig. eg two subplots with time as a common axis.plot(t. it involved a fair amount of boilerplate code. you want the other to move around with you. When you pan and zoom around on one.01) In [97]: ax1 = plt. To facilitate this. we can use method:matplotlib. (ax3.0.Line2D object at 0x92a6b6c>] you will see that the x tick labels are all squashed together. dtype=object) The dtype of the numpy record array for the field ‘date’ is ‘|O4’ which means it is a 4-byte python object pointer. 2. unpack the axes fig. 2. ’<f8’)]) In [66]: r.recarray) In [65]: r. and for the most part does a good job picking tick locations and string formats. In [67]: plot(r. .plot(x) or get them back as a numrows x numcolumns object array which supports numpy indexing: # new style method 2. in this case the objects are datetime. ’<f8’). 2004-08-20. What we’d like is for the location in the toolbar to have a higher degree of precision. and turn off x and y sharing for the whole bunch..date instances.1 Fernando Perez has provided a nice top level method to create in subplots() (note the “s” at the end) everything at once. 2008-10-10.0].date Out[66]: array([2004-08-19.dtype Out[65]: dtype([(’date’. sharex=True. you see that the x locations are formatted the same way the tick labels are. (’volume’. ax4)) = plt.npy’) In [64]: r = np. (’’. If you plot the data. sharey=True) ax1. (’close’. Release 1. axs = plt.view(np.subplots(2. 2008-10-13. Another annoyance is that if you hover the mouse over a the window and look in the lower right corner of the matplotlib toolbar (Interactive navigation) at the x and y coordinates.date objects in a numpy record array: In [63]: datafile = cbook. ax2). ((ax1.. 2004-08-23. ’<f8’). Our Favorite Recipes .. which we can see when we print some samples in the ipython terminal window. To fix the first problem. ’|V4’). ’|O4’).date. sharey=True) axs[0. eg giving us the exact date out mouse is hovering over.autofmt_xdate and to fix the second problem we can 142 Chapter 16. r.plot(x) 16. (’adj_close’.lines. eg “Dec 2004”.load(datafile). We’ll load up some sample date data which contains datetime. and here are some tricks to help you work around them.figure.Figure. ’<f8’).close) Out[67]: [<matplotlib. (’low’. ’<f8’).3 Fixing common date annoyances matplotlib allows you to natively plots python datetime instances. sharex=True. (’high’.Matplotlib.subplots(2.get_sample_data(’goog. ’<i8’). 2008-10-14]. use an axes array fig. There are a couple of things it does not handle so gracefully. You can either unpack the axes individually: # new style method 1. (’open’. 4. plt.subplots(1) ax. eg to just 16.1 Default date handling can cause overlapping labels 800 700 600 500 400 300 200 100 2004 2005 2005 2006 2006 2007 2007 2008 Dec Jun Dec Jun Dec Jun Dec Jun use the ax.Matplotlib. Fill Between and Alpha 143 .dates as mdates ax. Release 1.close) # rotate and align the tick labels so they look better fig.close(’all’) fig. 16.fmt_xdata = mdates.date. matplotlib has a number of date formatters built in. It has a very handy where argument to combine filling with logical ranges. you’ll see date format strings like 2004-12-01 in the toolbar. ax = plt.title(’fig.0.plot(r.autofmt_xdate fixes the labels’) Now when you hover your mouse over the plotted data. r.DateFormatter(’%Y-%m-%d’) plt. so we’ll use one of those.fmt_xdata attribute which can be set to any function that takes a scalar and returns a string.4 Fill Between and Alpha The fill_between() function generates a shaded region between a min and max boundary that is useful for illustrating ranges.autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar import matplotlib. 2.date.load(datafile). alpha=0.Matplotlib.get_sample_data(’goog. (ax1. sharey=True) pricemin = r.recarray) # create two subplots with the shared x and y axes fig.cbook as cbook # load up some sample financial data datafile = cbook.pyplot as plt import numpy as np import matplotlib.date.autofmt_xdate fixes the labels 100 5 6 7 8 6 7 4 5 200un 200 ec 200 n 200 ec 200un 200 ec 200 n 200 J Ju Ju D D D Dec J fill in a curve over some threshold value. lw=2) ax2.npy’) r = np. pricemin. Release 1. import matplotlib.close. ax2: ax. Let’s compare two graphs of a financial times with a simple line plot on the left and a filled line on the right.grid(True) 144 Chapter 16.close.min() ax1. sharex=True. facecolor=’blue’. fill_between can be use to enhance a graphs visual appearance. r.1 800 700 600 500 400 300 200 fig.0. r.subplots(1. At its most basic level. Our Favorite Recipes .5) for ax in ax1.close.view(np. ax2) = plt.fill_between(r.plot(r. Release 1. so when using alpha save your figures in PNG.1 ax1.01*np.one standard deviation of the mean position of the population.pyplot as plt import numpy as np Nsteps. Fill Between and Alpha 145 .set_ylabel(’price’) for label in ax2. PDF or SVG.get_yticklabels(): label. the alpha channel is functionally useful as the shaded regions can overlap and alpha allows you to see both. Nwalkers) 16.002 + 0. We use shared regions to plot +/.random.0. import matplotlib. Note that the postscript format does not support alpha (this is a postscript limitation. 250 t = np.Matplotlib. as we’ll see below.randn(Nsteps.arange(Nsteps) # an (Nsteps x Nwalkers) array of random walk steps S1 = 0. In other examples. Here the alpha channel is useful. not a matplotlib limitation). but it can be used to soften colors for more visually appealing plots. Nwalkers = 100.4. not just aesthetic.set_visible(False) fig. Our next example computes two populations of random walkers with a different mean and standard deviation of the normal distributions from which the steps are drawn.autofmt_xdate() 800 700 600 price 500 400 300 200 Google (GOOG) daily closing price 100 6 6 0 24 50 25 20 26 70 27 8 20 24 50 25 20 26 70 27 8 2n 0e0c02n 0e0c0un 0e0c02n 0 00 ec un 0e0c02n 0e0c0un 0e0c02n 0 00 DecJu D Ju D J D Ju D J D Ju D J D Ju The alpha channel is not necessary here.suptitle(’Google (GOOG) daily closing price’) fig. 1 S2 = 0.set_title(’random walkers empirical $\mu$ and $\pm \sigma$ interval’) ax.0. mu1. mu1.5) ax. mu2+sigma2. lw=2.mean(axis=1) sigma2 = X2.10 146 mean population 1 mean population 2 20 40 60 num steps 80 100 Chapter 16. Nwalkers) # an (Nsteps x Nwalkers) array of random walker positions X1 = S1.5 0.fill_between(t. mu1+sigma1.3 0.std(axis=1) # plot it! fig. color=’blue’) ax.fill_between(t.plot(t.set_ylabel(’position’) ax.cumsum(axis=0) # Nsteps length arrays empirical means and standard deviations of both # populations over time mu1 = X1. mu2-sigma2.02*np. color=’yellow’) ax.plot(t.random. Our Favorite Recipes .cumsum(axis=0) X2 = S2.grid() 0.1 0.randn(Nsteps. alpha=0. mu1-sigma1.004 + 0.subplots(1) ax.5) ax.set_xlabel(’num steps’) ax.legend(loc=’upper left’) ax. lw=2. label=’mean population 2’. alpha=0. facecolor=’yellow’. Release 1.0 0. label=’mean population 1’.4 position 0.Matplotlib.mean(axis=1) sigma1 = X1. ax = plt.2 0.6random walkers empirical µ and ± σ interval 0.std(axis=1) mu2 = X2. facecolor=’blue’. where=X>upper_bound. facecolor=’blue’. facecolor=’yellow’.002 sigma = 0.plot(t.fill_between(t.01 # the steps and position S = mu + sigma*np.legend(loc=’upper left’) # here we use the where argument to only fill the region where the # walker is above the population 1 sigma boundary ax. we simulate a single random walker and compute the analytic mean and standard deviation of the population positions. and the plus/minus one sigma deviation from the mean is showsn as the yellow filled region. color=’black’. 16. upper_bound.seed(1234) Nsteps = 500 t = np. X. color=’blue’) ax. Transparent.set_ylabel(’position’) ax. mu*t.subplots(1) ax. label=’population mean’.random.Matplotlib.legend(loc=’upper right’) Other times you don’t know where your data is.5. ax = plt. alpha=0.arange(Nsteps) mu = 0. fancy legends 147 . and mak know for instance that there won’t be much data in the upper right hand corner. X.fill_between(t.grid() Another handy use of filled regions is to highlight horizontal or vertical spans of an axes – for that matplotlib has some helper functions axhspan() and axvspan() and example pylab_examples-axhspan_demo.randn(Nsteps) X = S. ls=’--’) ax. upper_bound.plot(t. In the example below. lw=2. alpha=0.random.5 Transparent. and shade that region blue. Release 1.0. label=’walker position’.sigma*np. ymin and ymax arguments. and loc=’best’ will try and place the legend: 16.cumsum() # the 1 sigma upper and lower analytic population bounds lower_bound = mu*t . and only fills in the region where the boolean mask is True. np.sqrt(t) upper_bound = mu*t + sigma*np. Then you can safely create a legend that doesn’t overlay your data: ax.sqrt(t) fig.5. where takes a boolean mask the same length as the x. lower_bound. label=’1 sigma range’) ax. We use the where mask X>upper_bound to find the region where the walker is above the one sigma boundary. fancy legends Sometimes you know what your data looks like before you plot it. The population mean is shown as the black dashed line. lw=1.1 The where keyword argument is very handy for highlighting certain regions of the graph.5) ax.set_xlabel(’num steps’) ax. Matplotlib. Release 1.subplots(1) ax.plot(np.legend(loc=’upper right’) but still.1 1.6 0. transparent legends’) 16.random.set_ylim(-3.random. so the text doesn’t move around with changes in x or y limits.6 Placing text boxes When decorating axes with text boxes.seed(1234) fig.randn(300). Our Favorite Recipes . fancybox=True) leg.4 1.rand(300).4 0.20 walker position population mean 100 200 300 num steps 400 500 ax. label=’uniform distribution’) ax.0 position 0.set_alpha(0.random.2 0. 148 Chapter 16.5) ax.2 1.get_frame(). your legend may overlap your data. ax = plt. You can also use the bbox property of text to surround the text with a Patch instance – the bbox keyword argument takes a dictionary with keys that are Patch properties. np. label=’normal distribution’) ax.0.legend(loc=’best’.set_title(’fancy. ’o-’.plot(np. and in these cases it’s nice to make the legend frame transparent. 3) leg = ax.8 0. ’s-’.0 0. two useful tricks are to place the text in axes coordinates (see Transformations Tutorial). random. 50) # these are matplotlib.2f $\n$\sigma=%.transAxes.0.Matplotlib. fontsize=14.Patch properies props = dict(boxstyle=’round’. median.patch.text(0. facecolor=’wheat’. transparent legends normal distribution uniform distribution 50 100 150 200 250 300 np.hist(x.2f $’%(mu.seed(1234) fig. Release 1.randn(10000) mu = x. Placing text boxes 149 .6.random.mean() median = np.5) # place a text box in upper left in axes coords ax. verticalalignment=’top’.95.05.std() textstr = ’$\mu=%. sigma) ax.1 3 2 1 0 1 2 30 fancy. transform=ax. alpha=0. 0.subplots(1) x = 30*np. ax = plt. textstr.2f $\n$\mathrm{median}=%.median(x) sigma = x. bbox=props) 16. Release 1.86 400 300 200 100 0150 100 50 0 50 100 µ =0.48 150 Chapter 16.Matplotlib. Our Favorite Recipes .1 600 500 median =0.54 σ =29.0. CHAPTER SEVENTEEN TOOLKITS Toolkits are collections of application-specific functions that extend matplotlib. 17. Not the fastest or feature complete 3D library out there. This requires a separate installation of the natgrid toolkit from the sourceforge download page. 17. but ships with matplotlib and thus may be a lighter weight solution for some use cases. This toolkit ships with matplotlib. but requires xlwt 17. 151 . 17.mplot3d provides some basic 3D plotting (scatter.3 Excel Tools mpl_toolkits. See toolkit_mplot3d-index for more documentation and examples. This toolkit ships with matplotlib.2 GTK Tools mpl_toolkits. see basemap docs.1 Basemap Plots data on map projections.exceltools provides some utilities for working with Excel.4 Natgrid mpl_toolkits. with continental and political boundaries. 17. mesh) tools.gtktools provides some utilities for working with GTK. line. surf. but requires pygtk.natgrid is an interface to natgrid C library for gridding irregularly spaced data.5 mplot3d mpl_toolkits. See toolkit_axesgrid-index for documentations.1 17.6 AxesGrid The matplotlib AxesGrid toolkit is a collection of helper classes to ease displaying multiple images in matplotlib. Release 1.0. The AxesGrid toolkit is distributed with matplotlib source. Toolkits .Matplotlib. 152 Chapter 17. with text labels 1.0 153 .0 0.CHAPTER EIGHTEEN SCREENSHOTS Here you will find a host of example figures with the code that generated them 18.0 0.0 About as simple as it gets.0 time (s) 1.1 Simple Plot The most basic plot().5 voltage (mV) 0.5 2.0 0. folks 0.5 1.5 1. 6 0.0 18.0 A tale of 2 subplots Damped oscillation 1 2 3 4 5 Undamped 0. wireframe.2 Subplot demo Multiple regular axes (numrows by numcolumns) are created with the subplot() command.5 mplot3d The mplot3d toolkit (see toolkit_mplot3d-tutorial and mplot3d-examples-index) has support for simple 3d graphs including surface. 18.0 0.5 1.4 Path demo You can add aribitrary paths in matplotlib as of release 0.0.0 0.5 0.5 1.1 18.2 0. See the matplotlib. Jonathon Taylor and Reinier Heeres for the mplot3d toolkit.4 0.0 time (s) 1.2 0.0 0. scatter.0 0.5 2. and bar charts (added in matlpotlib-0. Screenshots . 1. 154 Chapter 18.3 Histograms The hist() command automatically generates histograms and will return the bin counts or probabilities 18.4 0. The toolkit is included with all standard matplotlib installs.path.8 0.0 0.80 1. Release 1.99). Thanks to John Porter.98.6 0.Matplotlib. nine lines of code.030 0.6 Ellipses Histogram of IQ : µ =100.6.py for another example.015 0.010 0. Ellipses 155 .8 Pie charts The pie() command uses a MATLAB compatible syntax to produce pie charts. Optional features include auto-labeling the percentage of area.7 Bar charts The bar() command takes error bars as an optional argument. This provides a scale free. 18.0..025 0. candlestick bars.. which used matplotlib in ground tracking of the spacecraft. exploding one or more wedges out from the center of the pie.1 0.000 40 18.Matplotlib. accurate graph of the arc regardless of zoom level 18. 18. . See bar_stacked. σ =15 60 80 100 120 Smarts 140 160 In support of the Phoenix mission to Mars. Take a close look at the attached code that produced this figure. Michael Droettboom built on work by Charlie Moad to provide an extremely accurate 8-spline approximation to elliptical arcs (see Arc) in the viewport. and a shadow effect. etc.005 0. You can also use up and down bars.020 Probability 0. You can make horizontal bar charts with the barh() command. Release 1. stacked bars. 10 Scatter demo The scatter() command makes a scatter plot with (optional) size and color arguments.0.widgets and the widget examples <examples/widgets> 156 Chapter 18. Release 1. Here the alpha attribute is used to make semitransparent circle markers with the Agg backend (see What is a backend?) 18. allowing you to write cross GUI figures and widgets.1 4 3 2 1 0 1 2 33 18.11 Slider demo Matplotlib has basic GUI widgets that are independent of the graphical user interface you are using.9 Table demo spline paths 2 1 0 1 2 3 4 The table() command will place a text table on the axes 18. Screenshots . This example plots changes in Google stock price from one day to the next with the sizes coding trading volume and the colors coding price change in day i.Matplotlib. See matplotlib. Fill demo 157 .4 0.ticker and matplotlib.2 0.1 4 2 0 2 4 4 0 2 1. are real financial data. Thanks to Andrew Straw for providing this function 18.13 Date demo You can plot date data with major and minor ticks and custom tick formatters for both the major and minor ticks. Some of the data in the plot.337 0.6 0. some are random traces that I used since the goal was to illustrate plotting techniques.12 Fill demo The fill() command lets you plot filled polygons.010 4 2 0.12.112 -0.14 Financial charts You can make much more sophisticated financial plots.786 0.561 0.2 0.Matplotlib.dates for details and usage. 18.112 -0.786 -1.337 -0.4 0.6 0. see matplotlib.8 0.0 0.0. not market analysis! 18. Release 1.561 -0. This example emulates one of the ChartDirector financial plots.010 0.8 18. lambert conformal conic.Matplotlib. semilogy() and loglog() functions generate log scaling on the respective axes. albers equal area conic and stereographic. Darren Dale and Gregory Lielens for contributions to the log scaling infrastructure. See the tutorial entry on the wiki. The lower subplot uses a base10 log on the xaxis and a base 4 log on the yaxis. mercator. 158 Chapter 18. 18.16 Log plots The semilogx().0. Exception occurred rendering plot.17 Polar plots The polar() command generates polar plots. Many map projections are handled via the proj4 library: cylindrical equidistant. Thanks to Andrew Straw. lambert azimuthal equal area. Screenshots .1 10 8 6 4 2 00 18. 2 4 6 8 10 18. Release 1.15 Basemap demo Jeff Whitaker provided this example showing how to efficiently plot a collection of lines over a colormap image using the Basemap . 18. 18.18 Legends Scores by group and gender 35 Men 34 35 32 Women 30 25 20 20 27 25 G2 G3 G4 G5 The legend() command automatically generates figure legends.0. The mathtext module provides TeX style mathematical expressions using freetype2 and the BaKoMa computer modern or STIX fonts. sometimes you need TeX. See the matplotlib.20 Native TeX rendering Although matplotlib’s internal math rendering engine is quite powerful.1 40 35 30 25 Scores 20 15 10 5 0 G1 18. and matplotlib supports external TeX rendering of strings with the usetex option. and does not required TeX or any external packages installed on your computer. Release 1.19 Mathtext_examples A sampling of the many TeX expressions now supported by matplotlib’s internal mathtext engine.Matplotlib.mathtext module for additional. Thanks to Charles Twardy for input on the legend command 18.18. See the tutorial at Writing mathematical expressions. Legends 159 . with MATLAB compatible legend placement commands. matplotlib mathtext is an independent implementation. 0% 15.0% 10.Matplotlib.1 Raining Hogs and Dogs Hogs 30. Release 1.0. Screenshots .0% 45.0% Dogs Frogs Logs 160 Chapter 18. 8 1368.Matplotlib. For an example of how to use the navigation toolbar in your applications.1 18. If you want to use matplotlib in a wx application.4 174. see user_interfaces-embedding_in_gtk2.7 10 year 124. FLTK or Qt applications.0 305. see user_interfaces-mpl_with_glade.8 456.6 50 year 292.5 1049.21 EEG demo You can embed matplotlib into pygtk.3 75.2 677. Here is a screenshot of an eeg viewer called pbrain which is part of the NeuroImaging in Python suite NIPY.8 636. Pbrain is written in pygtk using matplotlib.4 20 year 213.2 5 year 66.4 153.21.0.6 796.9 865. see user_interfaces-embedding_in_wx2. Quake 2149.0 18. The lower axes uses specgram() to plot the spectrogram of one of the EEG channels. wxpython.2 577.0 192.2 717. Release 1.9 Hail 917.1 Loss by Disaster 2000 Loss $1000's 1500 1000 500 0 Freeze Wind Flood 100 year 431.4 799. EEG demo 161 .5 32.5 1175. If you want to work with glade. Tk.6 555. 0.25 ∆i 162 Chapter 18.10 0.00 0.10 Volume and percent change ∆i +1 0.20 0.10 0.Matplotlib.15 0.00 0.15 0.05 0.10 0. Release 1.05 0. Screenshots .20 0.25 0.05 0.15 0.05 0.1 0.15 0. 1 10 5 red blue green 0 5 10 0. Release 1.0 5. EEG demo 163 .0 Amp Freq 0.6 0.00 3.00 Reset 18.Matplotlib.0.21.8 1.2 0.4 0. 6 0.4 0.2 0.2 0.0 164 Chapter 18.0.6 0.Matplotlib.3 0. Screenshots .1 0.0 0.1 0.8 1.5 0.0 0.2 0.4 0.1 0. Release 1. 0.Matplotlib.1 800 700 600 500 400 300 200 100 4 200 200 5 6 200 7 200 200 8 200 9 18.21. Release 1. EEG demo 165 . 06 MA (20) MA (200) MACD (12. V:133.0.72 L:126. 9) 200 7 8 200 9 200 201 0 201 1 166 Chapter 18.64.58 H:127.Matplotlib. 26. Screenshots .46 C:127.1 70 30 140 120 100 80 5 0 5 10 RSI (14) SPY daily >70 = overbought <30 = oversold 06-Jan-2011 O:126. Release 1.9M Chg:+1. 0 0.21.5 15 201.0 0.0 -2 10-1 100 101 102 10 18.1 100 10-1 10-2 0 102 semilogy 104 103 101 102 101 100 100 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 10-1 -1 0 2 2 2 2 2 2 2 2 2 2 2 2 25 10 10 101 102 103 loglog base 4 on x 105Errorbars go negative 5 10 semilogx 1.Matplotlib.0.5 0. EEG demo 167 . Release 1. Matplotlib.5 1.0 0° 180° 225° 270° 315° 168 Chapter 18.1 And there was90° rejoicing! much 135° 0.5 2.0. Screenshots . Release 1.0 45° 1. EEG demo 169 . Release 1.0.21.1 Minimum Message Length Model length Data length Total message length Message length ---> Model complexity ---> 18.Matplotlib. Release 1.Matplotlib.00 α_ $100.00 y xy x + y x = y x <y x .y x@y 100%y x ∗ y x/yx$y x ← y x∀y x−y xxxXx xx x x x x y x Chapter 18.y x. Screenshots 9 .1 0 1 2 3 4 5 6 7 8 170 ˙ a +b + +s + x y $100.0. 5 1.0 0.6 0. Release 1.0 1.21.0 18. EEG demo 171 .0.0 0.0 ∞ n=1 −eiπ ! 2n voltage (mV) 2.8 1.1 TEX is Number 3.2 0.5 2.Matplotlib.4 time (s) 0. Release 1.0.Matplotlib. Screenshots .1 172 Chapter 18. subplots(2.0 19. see the CHANGELOG 19. The backend features client/server interactive navigation of matplotlib figures in an html5 compliant browser. See gridspec-guide for a tutorial overview.0]. 173 .plot([1. 2) axarr[0.2 Sophisticated subplot grid layout Jae-Joon Lee has written gridspec.3]) # upper.CHAPTER NINETEEN WHAT’S NEW IN MATPLOTLIB This page just covers the highlights – for the full story.1 HTML5/Canvas backend Simon Ratcliffe and Ludwig Schwardt have released an HTML5/Canvas backend for matplotlib. left See pylab_examples-subplots_demo for several code examples.1.2.1.1.1 new in matplotlib-1.1. axarr = plt. 19. Basic usage allows you to create the figure and an array of subplots with numpy indexing (starts with 0). 19. The backend is almost feature complete. Eg: fig. and they have done a lot of work comparing their html5 rendered images with our core renderer Agg.3 Easy pythonic subplots Fernando Perez got tired of all the boilerplate code needed to create a figure and multiple subplots when using the matplotlib API. a new module for doing complex subplot layouts. and the boundaries of line and filled contours coincide.4 Contour fixes and and triplot Ian Thomas has fixed a long-standing bug that has vexed our most talented developers for years. contourf() now handles interior masked regions. and wrote a subplots() helper function. featuring row and column spans and more. 19. Eric Firing has done a lot of work on rationalizing show across backends. This has been difficult because it is hard to get consistent behavior across operating systems. but it is not possible to test them all. 19. with the desired behavior to make show raise all newly created figures and block execution until they are closed.5 multiple calls to show supported A long standing request is to support multiple calls to show().1. using the “projection” keyword argument to add_axes or add_subplot.1. user interface toolkits and versions. Release 1. and/or multiple 3D graphs in a single figure. 174 Chapter 19.6 mplot3d graphs can be embedded in arbitrary axes You can now place an mplot3d graph into an arbitrary axes location. Thanks Ben Root. What’s new in matplotlib .0.Matplotlib.tri and helper function triplot() for creating and plotting unstructured triangular grids. supporting mixing of 2D and 3D graphs in the same figure. he has contributed a new module matplotlib. 19. Repeated calls to show should raise newly created figures since the last call.1 subplot2grid ax1 ax2 ax3 ax4 ax5 Additionally. so please report problems to the mailing list and bug tracker. Eric has done a lot of testing on the user interface toolkits and versions and platforms he has access to. Release 1.7 tick_params 0. particularly the alpha channel.0.1. See pyplot function tick_params() and associated Axes method tick_params(). and the ability to zoom in to a single pixel • Local installs of documentation work better • Improved “widgets” – mouse grabbing is supported • More accurate snapping of lines to pixel boundaries • More consistent handling of color.0 0. auto-generating a set of images and comparing them against a set of known-goods. sending emails to developers on failures 19.01. We now have a buildbot which runs a suite of nose regression tests on every svn commit.1.0 0.1 1.9 Much improved software carpentry The matplotlib trunk is probably in as good a shape as it has ever been.5 1.0 175 .5 0. a convenience method for changing the appearance of ticks and tick labels.1.0 Eric Firing wrote tick_params. 19.5 0. new in matplotlib-1.Matplotlib.8 Lots of performance and feature enhancements • Faster magnification of large images. throughout the API 19.0 19.5 triplot of Delaunay triangulation 1.0 0.1. thanks to improved software carpentry. John Hunter has written two new tutorials on working with paths and transformations: Path Tutorial and Transformations Tutorial. 19. Michael Sarahan has written Image tutorial. allowing active new feature development to happen in the trunk while keeping the release branches stable.1 triplot of user-specified triangulation 58 Latitude (degrees) 176 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) with a pixel-by-pixel image comparison. Christoph Gohlke and Michiel de Hoon. 19.1. Michael Droettboom. Thanks to Andrew Straw.2.10 Bugfix marathon Eric Firing went on a bug fixing and closing marathon.99 19. closing over 100 bugs on the bug tracker with help from Jae-Joon Lee.2 new in matplotlib-0.1 New documentation Jae-Joon Lee has written two new guides Legend guide and Annotating Axes. Release 1. Chapter 19. Michael Droettboom and other matplotlib developers for the heavy lifting. What’s new in matplotlib . Releases and release bugfixes happen in branches.Matplotlib.0. 19.0 4 2 0 42 2 02 4 4 0. as well as “detach” the spine to offset it away from the data.6 0.6 0. See axes_grid-examples-index and axes_grid_users-guide-index. The toolkit is included standard with all new mpl installs.8 0. No longer are your axis lines constrained to be a simple rectangle around the figure – you can turn on or off left.Matplotlib.0 0.4 0.2 0. Release 1.0 0.3 axes grid toolkit Jae-Joon Lee has added a new toolkit to ease displaying multiple images in matplotlib. as well as some support for curvilinear grids to support the world coordinate system. See pylab_examples-spine_placement_demo and matplotlib. See mplot3d-examples-index and toolkit_mplot3d-tutorial 19.4 0.0.2 mplot3d Reinier Heeres has ported John Porter’s mplot3d over to the new matplotlib transformations framework.4 Axis spine placement Andrew Straw has added the ability to place “axis spines” – the lines that denote the data limits – in various arbitrary locations.99 177 .2.2. new in matplotlib-0.2.0 0.5 1.spines.1 1. bottom. 19.2 0.mplot3d (which now comes standard with all mpl installs).8 80 60 40 20 0 20 40 60 20 10 30 0 20 10 10 010 20 20 30 19. right and top.Spine.5 0.2. and it is now available as a toolkit mpl_toolkits. Legend. 178 Chapter 19. and added support for multiple columns and rows.0.6 and 3. Release 1.5 (2. as well as fancy box drawing.98.3 new in 0. Eric Firing.0 will not be available until numpy is available on those releases). See legend() and matplotlib. Manuel Metz.3.5 0. Thanks to the many developers who contributed to this release.legend. Michiel de Hoon and many others who submitted patches 19.4 and 2.Matplotlib.4 It’s been four months since the last matplotlib release.5 4 4 2 0 2 4 4 2 0 2 19.3. with contributions from Jae-Joon Lee. David Kaplan. What’s new in matplotlib .2 Fancy annotations and arrows Jae-Joon has added lot’s of support to annotations for drawing fancy boxes and connectors in annotations. See annotate() and BoxStyle.0 0. Darren Dale. including binaries for OS X and Windows for python 2.1 0. 19. Seppänen.1 Legend enhancements Jae-Joon has rewritten the legend class. and there are a lot of new features and bug-fixes. and ConnectionStyle. Jouni K. Ryan May. Thanks to Charlie Moad for testing and preparing the source release. ArrowStyle. Michael Droettboom. Jeff Whitaker. 4 psd amplitude scaling Ryan May did a lot of work to rationalize the amplitude scaling of psd() and friends.5 Fill between Added a fill_between() function to make it easier to do shaded region plots in the presence of masked data.4 179 . but in principle it should to work there as well.3. See pylab_examplespsd_demo2. no third-party libraries are needed other than Python and NumPy. depending on the application. new in 0.1 10 8 6 4 2 0 2 4 6 8 19. and pylab_examples-psd_demo3.0.Matplotlib.3. The backend is interactive from the usual terminal application on Mac using regular Python. and an optional where argument 19. You can pass an x array and a ylower and yupper array to fill betweem. The backend can therefore use Quartz directly and.py -dmacosx 19. It hasn’t been tested with ipython yet. or run your script with: > python myfile. Release 1.3. In addition. The changes should increase MATLAB compatabililty and increase scaling options. can be orders of magnitude faster than the existing backends. Set ‘backend : macosx’ in your matplotlibrc file. 19.98.3.3 Native OS X backend Michiel de Hoon has provided a native Mac OSX backend that is almost completely implemented in C. Matplotlib.5 2.0.0 1. I added a new rc param docstring. -RM 180 Chapter 19.harcopy.5 0. 19.JDH Return the list of Some of the changes Michael made to improve the output of the property tables in the rest docs broke of made difficult to use some of the interactive doc helpers. pprinted strings instead .0 1.5 1. Ther ArtistInspector could use a little refactoring now since there is duplication of effort between the rest out put and the non-rest output .0 1. eg setp and getp.4 notes from the CHANGELOG: Added mdehoon’s native macosx backend from sf patch 2179017 .0 0. to format the docstrings differently for hardcopy and other use. scale all densities by the sampling frequency.5 1.98.) to scale one-sided densities by a factor of 2 and. optionally.5 2. What’s new in matplotlib . Release 1.0 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 which is a logical mask where you want to do the filling.5 1.JDH Updated spectral methods (psd.1 2.0 0.0 0. etc.5 1.5 0. This gives better MATLAB compatibility.0 2. Having all the rest markup in the ipython shell also confused the docstrings.JDH Removed the prints in the set_*style commands.0 0.0 1.6 Lots more Here are the 0.3. csd. -JJL The transmuter classes in the patches. Also applied some changes for better look.0 Fixed alignment of ticks in colorbars.4 0.0.0 0.3.4 181 . new in 0. -MGD drop the deprecated "new" keyword of np.4 0.8 0.histogram() for numpy 1.0 n=1 n=2 n=3 n=4 0.g. -JJL 19.6 0.1 1.Matplotlib. etc. -RM Added fancybox keyword to legend.0 0.2 0.py are reorganized as subclasses of the Style classes. dates) to Axes.98. A few more box and arrow styles are added. Release 1.2 or later. -JJL Fixed a bug in svg backend that new_figure_manager() ignores keywords arguments such as figsize.6 0. including baseline adjustment of the multiline texts so that it is center aligned.2 0. -JJL Fixed a bug in the new legend class that didn’t allowed a tuple of coordinate vlaues as loc.fill_between. -JJL Fixed a bug that the handlelength of the new legend class set too short when numpoints=1 -JJL Added support for data with units (e.8 1. Matplotlib.0. Release 1. What’s new in matplotlib .1 square sawtooth roundtooth rarrow larrow round4 round <|<|-|> ]]-[ fancy simple wedge |-| 182 Chapter 19. MGD Added static helper method BrokenHBarCollection. .JDH Add x_isdata and y_isdata attributes to Artist instances.5 2.MM Added rcParam axes. new in 0. See examples/pylab/fill_between.5 0. multi-column.5 1.DSD Reimplementaion of the legend which supports baseline alignement.unicode_minus which allows plain hypen for minus when False . .4 183 . using subprocess (instead of deprecated popen*) and distutils (for version checking) .0 Improve checks for external dependencies. and expand mode.span_where and Axes/pyplot method fill_between.5 fill between where 1.0 1.0.JJL Fixed histogram autoscaling bug when bins or range are given explicitly (fixes Debian bug 503148) . and use them to determine whether either or both coordinates are used when 19.0 0.0 0. patch by Erik Tollerud JJL Fix crash in log ticking.1 1. Release 1.5 0.5 1.py .0 1.JDH Added scatterpoints support in Legend.98.3.0 0.Matplotlib. EF Experimental new kwarg borderpad to replace pad in legend. generalize is_string_like to accept numpy and numpy. .g. which might help when saving pdf files from the qt backend.EF Fixed exception in dviread that happened with Minion .RM and EF Fix a possible EINTR problem in dviread. .psd() to allow controlling of zero padding and returning of negative frequency components. . . . for easy access to the set_powerlimits method of the major ScalarFormatter.EF 184 Chapter 19. . axvspan. . we now flush the object at the end.ma string array scalars. This is used to fix autoscaling problems that had been triggered by axhline. axhspan. in a wep app.RM Add ’pad_to’ and ’sides’ parameters to mlab.JKS Add path simplification support to paths with gaps. e. based on suggestion by Jae-Joon Lee.py Autoscaling is now supported with shared axes . . box and annotation enhancements -see examples/pylab_examples/annotation_demo2. axvline.py . under the hood. .RM Fix handling of c kwarg by scatter. What’s new in matplotlib .JDH Applied scatleg patch based on ideas and work by Erik Tollerud and Jae-Joon Lee. . Release 1.MM Fixed bug in pdf backend: if you pass a file object for output instead of a filename.JKS Fix bug with zoom to rectangle and twin axes . In fact. See examples/misc/image_thumbnail.JKS Added ’scilimits’ kwarg to Axes.EF Fix problem with AFM files that don’t specify the font’s full name or family name. cohere().MGD Added Jae Joon’s fancy arrow. csd().0. and specgram() methods of Axes and the csd() cohere().thumbnail.JKS set_xlim.Matplotlib. .1 updating dataLim. and specgram() functions in mlab to be in sync with the changes to psd(). These are added in a way that does not change the API.ticklabel_format() method. respecitively. these all call the same core to do computations.image.EF Update the psd(). ylim now return a copy of the viewlim array to avoid modify inplace surprises Added image thumbnail generating function matplotlib. EF Fix hatching in PS backend . fixed contour labeling bug. .98. . .DMK Fix backtick in Postscript output. Release 1.MGD [ 2089958 ] Path simplification for vector output backends Leverage the simplification code exposed through path_to_polygons to simplify certain well-behaved paths in the vector backends (PDF. .intersects_path and Path.EF Added support for multiple histograms with data of different length . .EF Fix polar interpolation to handle negative values of theta . PS and SVG).Matplotlib. Patch by Jae-Joon Lee.simplify" must be set to True in matplotlibrc for this to work.MGD 19.MM Fix step plots with log scale .MGD Add "filled" kwarg to Path. new in 0.MM Fixed quiver and quiverkey bugs (failure to scale properly when resizing) and added additional methods for determining the arrow angles .py Also.4 185 .MGD Reorganized cbook and mlab methods related to numerical calculations that have little to do with the goals of those two modules into a separate module numerical_methods.1 Allow spy to ignore zero values in sparse arrays.MGD Fix masked arrays with markers in non-Agg backends .3.EF Introduce drawstyles for lines. based on patch by Tony Yu.JKS Added 5-point star marker to plot command q. "path. added ability to select points and stop point selection with keyboard in ginput and manual contour labeling code. .MGD Fix log with base 2 . .MGD Changed full arrows slightly to avoid an xpdf rendering problem reported by Friedrich Hagedorn. patch by Gregory Lielens. Transparently split linestyles like ’steps--’ into drawstyle ’steps’ and linestyle ’--’.intersects_bbox. .0. .JKS Fix conversion of quadratic to cubic Bezier curves in PDF and PS backends.MGD Added support for bilinear interpolation in NonUniformImage. Finally. and fixed handling of markers in figlegend. Also fixed plot to handle empty data arrays. Legends always use drawstyle ’default’. DSD Fix more bugs in NaN/inf handling.MGD Fix locale problems in SVG backend .1 Fix clip_on kwarg so it actually works correctly .MGD fix quiver so masked values are not plotted . Release 1.0.JSW improve interactive pan/zoom in qt4 backend on windows . Also masked arrays are now converted to arrays with NaNs for consistent handling of masks and NaNs .MGD and EF 186 Chapter 19. In particular.Matplotlib. What’s new in matplotlib . path simplification (which does not handle NaNs or infs) will be turned off automatically when infs or NaNs are present. distribute. JDH hereby grants Licensee a nonexclusive. and wants to make the derivative work available to others as provided herein.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. SPECIAL. BUT NOT LIMITATION. and otherwise use matplotlib 1. and its license is based on the PSF license. DISTRIBUTING. then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 1. JDH MAKES NO REPRESENTATIONS OR WARRANTIES. EVEN IF ADVISED OF THE POSSIBILITY THEREOF. OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING.e. and the Individual or Organization (“Licensee”) accessing and otherwise using matplotlib software in source or binary form and its associated documentation. perform and/or display publicly.0.1 FOR ANY INCIDENTAL. world-wide license to reproduce.1. Hunter.1. analyze.0. All Rights Reserved” are retained in matplotlib 1. This License Agreement will automatically terminate upon a material breach of its terms and conditions.0.0. For a discussion of the motivations behind the licencing choice. “Copyright (c) 2002-2009 John D. 187 . BY WAY OF EXAMPLE. 3.0.1 or any part thereof. Non-BSD compatible licenses (eg LGPL) are acceptable in matplotlib Toolkits.CHAPTER TWENTY LICENSE Matplotlib only uses BSD compatible code. JDH is making matplotlib 1.1 alone or in any derivative version prepared by Licensee.. royalty-free.0. This LICENSE AGREEMENT is between John D. Hunter (“JDH”). however. see Testing. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 1. that JDH’s License Agreement and JDH’s notice of copyright. 20.1 License agreement for matplotlib 1. 2. JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 1. prepare derivative works.0. EXPRESS OR IMPLIED.0. provided. 6.1 alone or in any derivative version. Subject to the terms and conditions of this License Agreement. See the Open Source Initiative licenses page for details on individual licenses. i. test.1 available to Licensee on an “AS IS” basis. 4. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 1.0. OR OTHERWISE USING MATPLOTLIB 1. OR ANY DERIVATIVE THEREOF. 5.1 1. By copying. installing or otherwise using matplotlib 1. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee. License .1 7. Release 1.0. 188 Chapter 20.Matplotlib. Nothing in this License Agreement shall be deemed to create any relationship of agency. 8.0. or any third party. partnership. or joint venture between JDH and Licensee.1. Licensee agrees to be bound by the terms and conditions of this License Agreement. which allows matplotlib to work with either numeric or numarray. 189 .CHAPTER TWENTYONE CREDITS matplotlib was written by John Hunter and is now developed and maintained by a number of active developers. Steve Chaplin served as the GTK maintainer and wrote the Cairo and GTKCairo backends. Jim Benson provided the patch to handle vertical mathttext. Jared Wahlstrand wrote the initial SVG backend. with much pain and suffering. and added a number of new marker types to plot. Gary Ruben made many enhancements to errorbar to support x and y errorbar plots. and provided many examples. helped with support for auto-legend placement. PIL support for imshow. Paul Barrett supported by STSCI overhauled font management to provide an improved. John Gill wrote the table class and examples. free-standing. and has provided many suggestions and a lot of insight to the overall design and organization of matplotlib. and added support for legending scatter plots. platform independent font manager with a WC3 compliant font finder and cache mechanism and ported truetype and mathtext to PS. He also ported image support to the postscript backend. David Moore wrote the paint backend (no longer used) Todd Miller supported by STSCI contributed the TkAgg backend and the numerix module. Perry Greenfield supported by STSCI overhauled and modernized the goals and priorities page. Charles Twardy provided the impetus code for the legend class and has made countless bug reports and suggestions for improvement. Special thanks to those who have made valuable contributions (roughly in order of first contribution by date) Jeremy O’Donoghue wrote the wx backend Andrew Straw provided much of the log scaling architecture. implemented an improved colormap framework. the fill command. He also wrote the support for dropped axis spines and the buildbot unit testing infrastructure which triggers the JPL/James Evans platform specific builds and regression test image comparisons from svn matplotlib across platforms on svn commits. Charlie Moad contributed work to matplotlib’s Cocoa support and has done a lot of work on the OSX and win32 binary releases. in addition to ongoing support and enhancements in performance. Jouni K. Fernando Perez has provided numerous bug reports and patches for cleaning up backend imports and expanding pylab functionality. James Evans and colleagues at the JPL collaborated on the QtAgg backend and sponsored development of a number of features including custom unit types. masked array. See dashpointlabel. The brainvisa Orsay team and Fernando Perez added Qt support to ipython in pylab mode. He has made substantial contributions to extending and maintaining the PS and Qt backends. and provided matplotlib support in the pylab mode for ipython. image and quiver support. added improved support for scalar formatting.0. which are more efficient in CPU and memory. Jochen Voss served as PS backend maintainer and has contributed several bugfixes. pcolor. and made a number of optimizations to the matplotlib mathtext grammar. Seppänen wrote the PDF backend and contributed numerous fixes to the code. He also provided the matshow() command. datetime support. design and code quality in most aspects of matplotlib. James Amundson did the initial work porting the qt backend to qt4 Eric Firing has contributed significantly to contouring.py and TextWithDash. Andrew Dalke of Dalke Scientific Software contributed the strftime formatting code to handle years earlier than 1900. and wrote TConfig. and support for log ticking with alternate bases and major and minor log ticking. Paul Mcguire provided the pyparsing module on which mathtext relies. Daishi Harada added support for “Dashed Text”. and did the lions share of the psfrag LaTeX support for postscript. scale free ellipses. Baptiste Carvello provided the key ideas in a patch for proper shared axes support that underlies ganged plots and multiscale plots. broken bar plots and more. and wrote the site. Release 1. Darren Dale did the work to do mathtext exponential labeling for log plots. Jeffrey Whitaker at NOAA wrote the Basemap tookit Sigve Tjoraand. He setup the infrastructure for the sphinx documentation that powers the mpl docs.Matplotlib. Credits . Nicolas Young added support for byte images to imshow.cfg and matplotlib. to tex support and to the get_sample_data handler 190 Chapter 21. which is the basis for the experimental traited mpl configuration.conf build and runtime configuration support. Ted Drain. Nadia Dencheva supported by STSCI provided the contouring and contour labeling code.1 Gregory Lielens provided the FltkAgg backend and several patches for the frontend. The JPL team wrote the unit testing image comparison infrastructure for regression test image comparisons. including contributions to toolbar2. and added support for irregularly sampled images. Matplotlib. implementing Knuth’s box layout algorithms. He also rewrote the transformation infrastructure to support custom projections and scales. Michael Droettboom supported by STSCI wrote the enhanced mathtext support. Jonathon Taylor and Reinier Heeres John Porter wrote the mplot3d module for basic 3D plotting in matplotlib. and feature and performance enhancements across the matplotlib code base. and has made numerous contributions to the code and documentation 191 . saving to file-like objects across backends. rewrote the legend support to handle multiple columns and fancy text boxes. and with Alex Mont contributed fast rendering code for quadrilateral meshes. much better font and unicode support. and Jonathon Taylor and Reinier Heeres ported it to the refactored transform trunk. John Porter. Release 1. and is responsible for numerous bug-fixes.0. Jae-Joon Lee implemented fancy arrows and boxes. wrote the axes grid toolkit.1 Paul Kienzle improved the picking infrastruture for interactive plots. Matplotlib. Release 1. Credits .0.1 192 Chapter 21. Part II The Matplotlib FAQ 193 . . Open up a UNIX shell or a DOS command 195 . but nothing shows up with plot – Cleanly rebuild and reinstall everything * Easy Install * Windows installer * Source install – Install from svn – Install from git – Backends * What is a backend? * Compile matplotlib with PyGTK-2.1 Report a compilation problem See Report a problem.4 – OS-X questions * Which python for OS X? * Installing OSX binaries * easy_install from egg * Building and installing from source on OSX with EPD – Windows questions * Binary installers for windows 22.CHAPTER TWENTYTWO INSTALLATION FAQ Contents • Installation FAQ – Report a compilation problem – matplotlib compiled fine. but nothing shows up with plot The first thing to try is a clean install and see if that helps. the best way to test your install is by running a script. rather than working interactively from a python shell or an integrated development environment such as IDLE which add additional complexities. If not.2 matplotlib compiled fine. 22. 3.1 prompt and cd into a directory containing a minimal example in a file.3 Cleanly rebuild and reinstall everything The steps depend on your platform and installation method.Matplotlib. 2.3]) show() and run it with: python simple_plot. 22.2. 22. see Report a problem. Use Start → Control Panel to start the Add and Remove Software utility. Installation FAQ .py --verbose-helpful This will give you additional information about which backends matplotlib is loading. governed by the matplotlibrc configuration file which contains instructions within and the concept of the matplotlib backend.egg files or directories from your installation directory.matplotlib configuration directory. Delete the caches from your . and does nothing to the install directory. Delete the caches from your . version information. Run: easy_install -m PackageName 3. To cleanly rebuild: 1.matplotlib configuration directory. If you are still having trouble. or for example: from pylab import * plot([1. 22.0.3.3 Source install Unfortunately: python setup.py clean does not properly clean the build directory. and more. At this point you might want to make sure you understand matplotlib’s configuration process. Something like simple_plot.3. 22. Delete the build directory in the source tree 196 Chapter 22. 2.py. 2. Delete any . Delete the caches from your .matplotlib configuration directory. Release 1.2 Windows installer 1.1 Easy Install 1. 1 3. 22. If C files have changed. matplotlib targets many different use cases and output formats. Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. the “frontend” is the user facing code. if you want to update your matplotlib at any time. Release 1.svn. Install from svn 197 .5 Install from git See Using git. matplotlib can target different outputs. Some people embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications.6. Then. and each of these capabililities is called a backend.4 Install from svn Checking out the main source: svn co https://matplotlib.sourceforge. Delete any matplotlib directories or eggs from your installation directory <locating-matplotlibinstall> 22. just do: > svn update When you run svn update. Others use matplotlib in batch scripts to generate postscript images from some numerical simulations. and still others in web application servers to dynamically serve up graphs. you are all set. There are two types of backends: user interface 22. ie the plotting code.0. To support all of these use cases.6 Backends 22.py install If you want to be able to follow the development branch as it changes just replace the last step with (Make sure you have setuptools installed): > python setupegg. you need to run the python setupegg develop command again to compile them.py develop This creates links in the right places and installs the command line script to the appropriate places. if the output shows that only Python files have been updated. whereas the “backend” does all the dirty work behind the scenes to make the figure. There is more information on using Subversion in the developer docs.net/svnroot/matplotlib/trunk/matplotlib matplotlib and build and install as usual with: > cd matplotlib > python setup.4.1 What is a backend? A lot of documentation on the website and in the mailing lists refers to the “backend” and many new users are confused by this term. 22.Matplotlib. pylab. tkinter. png jpg tiff . this must be done before importing matplotlib. eg WXAgg. Vector graphics languages issue drawing commands like “draw a line from this point to this point” and hence are scale free. you can also select GDK rendering (backend GTK) or Cairo rendering (backend GTKCairo). PDF. macosx. and is smart enough to do the right thing when you ask for postscript. or need a better understanding of what is going on.. Description raster graphics – high quality images using the Anti-Grain Geometry engine vector graphics – Postscript output vector graphics – Portable Document Format vector graphics – Scalable Vector Graphics vector graphics – Cairo graphics raster graphics – the Gimp Drawing Kit And here are the user interfaces and renderer combinations supported: 198 Chapter 22. This will do the right thing for 95% of the users. TkAgg. It gives you the option of running your scripts in batch or working interactively from the python shell. GTKAgg. QTAgg.pyplot or matplotlib. or other image formats. The canonical renderer for user interfaces is Agg which uses the antigrain C++ library to make a raster (pixel) image of the figure.1 backends (for use in pygtk. with the least amount of hassles. For example. One is to set the backend parameter in you matplotlibrc file (see Customizing matplotlib): backend : WXAgg # use wxpython with antigrain (agg) rendering The other is to use the matplotlib use() directive: import matplotlib matplotlib. PS). read on. For the rendering engines. SVG.Matplotlib. All of the user interfaces can be used with agg rendering. Installation FAQ . qt. you want to write graphical user interfaces. In addition. Release 1. wxpython. one can also distinguish between vector or raster renderers. or fltk) and hardcopy backends to make image files (PNG. To make things a little more customizable for graphical user interfaces. If you are unsure what to do. some of the user interfaces support other rendering engines.. and just want to get cranking. Here is a summary of the matplotlib renderers (there is an eponymous backed for each): Renderer AGG PS PDF SVG Cairo GDK Filetypes png ps eps pdf svg png ps pdf svg .. CocoaAgg. If however. and raster backends generate a pixel represenation of the line whose accuracy depends on a DPI setting.use(’PS’) # generate postscript output by default If you use the use directive. with GTK. or a web application server (Matplotlib in a web application server). There are a two primary ways to configure your backend. just set your backend to TkAgg.0. matplotlib separates the concept of the renderer (the thing that actually does the drawing) from the canvas (the place where the drawing goes).. or pdf. OS-X questions 199 .6.5-macosx10. and will have a name like file:matplotlib-0. You need to edit pygobject.4. and rename typename parameter to typename_: + const char *typename.1 Which python for OS X? Apple ships with its own python. it will run the Installer.0.99. You need to unzip this file using either the “unzip” command on OSX.__version__. which you can install via setuptools easy_install.h to add the G_BEGIN_DECLS and G_END_DECLS macros. 22. which is a typical Installer.7.zip depending on the python. Release 1. matplotlib.0. print matplotlib.99.2 Compile matplotlib with PyGTK-2.5/site-packages/. many users have had trouble with it so there are alternatives.2 Installing OSX binaries If you want to install matplotlib from one of the binary installers we build.0.__file__’ If you get an error like: 22. The mkpg installer will have a “zip” extension.5. This directory may not be in your python path. so you can test your installation with: > python -c ’import matplotlib. 22.1 Backend GTKAgg GTK GTKCairo WXAgg WX TkAgg QtAgg Qt4Agg FLTKAgg macosx Description Agg rendering to a GTK canvas (requires PyGTK) GDK rendering to a GTK canvas (not recommended) (requires PyGTK) Cairo rendering to a GTK Canvas (requires PyGTK) Agg rendering to to a wxWidgets canvas (requires wxPython) Native wxWidgets drawing to a wxWidgets Canvas (not recommended) (requires wxPython) Agg rendering to a Tk canvas (requires TkInter) Agg rendering to a Qt canvas (requires PyQt) Agg rendering to a Qt4 canvas (requires PyQt4) Agg rendering to a FLTK canvas (requires pyFLTK) Cocoa rendering in OSX windows 22.4 There is a bug in PyGTK-2.7.Matplotlib.rc1-py2. or an binary OSX egg.7 OS-X questions 22. When you double click on the resultant mpkd directory.org. prompt you for a password if you need system wide installation privileges. If it is feasible for you. again depedending on your python version.app.rc1py2. or simply double clicking on it to run StuffIt Expander.app. matplotlib. and install to a directory like file:/Library/Python/2. we recommend the enthought python distribution EPD for OS X (which comes with matplotlib and much more) or the MacPython or the official OS X version from python.5_mpkg. you have two choices: a mpkg installer.5macosx10.mpkg. const char *typename_.7. and OSX versions. which will have a name like file:matplotlib-0. rc1-py2.1 Traceback (most recent call last): File "<string>"./matplotlib-0.3-fat. We recommend you download the latest egg from our download site directly to your harddrive. still.0-py2.0’) If you rename matplotlib-0.98..7. eg: export PYTHONPATH=/Library/Python/2. easy_install will install it from the disk. with easy_install.5-macosx-10.5macosx-10.matplotlib folder (“rm -rf ~/.parse(’matplotlib==0. Installation FAQ .org/pypi/matplotlib/0. line 1.0-py2.99.sourceforge.5-i386.0-py2.0-py2.snip.egg Processing matplotlib-0. Reading http://matplotlib. Release 1. and manually install it with > easy_install –install-dir=~/dev/lib/python2.98.egg Some users have reported problems with the egg for 0.5 .98.7.3-fat.5. which prevents their installation through easy_install.98.5-macosx-10.0.5. in <module> ImportError: No module named matplotlib then you will need to set your PYTHONPATH.3-fat. 200 Chapter 22.egg. You can try: > easy_install matplotlib which should grab the latest egg from the sourceforge site.98 from the matplotlib download site.5/site-packages/matplotlib-0. it might turn out to be rather tricky to install a new version of matplotlib from source on the Mac OS 10. getting an error: > easy_install .98.python.3 easy_install from egg You can also us the eggs we build for OSX (see the installation instructions for easy_install if you do not have it on your system already).Matplotlib.net Reading http://cheeseshop. Renaming is all it takes to install them.egg to matplotlib-0.91.. Many Mac OS X eggs with cruft at the end of the filename. at least sometimes: 0. 22.matplotlib”).5/site-packages/ matplotlib-0.0. but the naming conventions for OSX eggs appear to be broken (see below) so there is no guarantee the right egg will be found.5-macosx-10. 22.98...4 Building and installing from source on OSX with EPD If you have the EPD installed (Which python for OS X?).egg removing ’/Library/Python/2. Here’s a procedure that seems to work.0-py2.0 error: Could not find suitable distribution for Requirement. Remove the ~/.98.5/site-packages:$PYTHONPATH See also ref:environment-variables. it’s annoying.3 No local packages or download links found for matplotlib==0. 8.98.5.3-fat.py build python setup.5) which have the exe extension.sh) in the directory in which you want the source code to be placed.framework/Versions/Current/lib/pythonX.egg)./install-matplotlib-epd-osx.5/config/Makefile.sdk 2. PKG_CONFIG_PATH.net/svnroot/$NAME/trunk/$NAME $NAME cd $NAME fi if [ $branch = "release" ] then echo getting the maintenance branch svn co https://matplotlib.Y is the version of Python you are building against) Comment out the line containing the name of the directory in which the previous version of MPL was installed (Looks something like .sourceforge. or simply type the commands in the terminal command line. builds and installs it. This script sets some local variable (CFLAGS.5.8 Windows questions 22. removing all occurrences of the string -arch ppc. In /Library/Frameworks/Python.net/svnroot/matplotlib/branches/v${VERSION}_maint $NAME$VER cd $NAME$VERSION fi export CFLAGS="-Os -arch i386" export LDFLAGS="-Os -arch i386" export PKG_CONFIG_PATH="/usr/x11/lib/pkgconfig" export ARCHFLAGS="-arch i386" python setup. If you haven’t already installed python./install-matplotlib-epd-osx.1 1. Run this script (for example sh . ARCHFLAGS). Release 1.0. you can use one of the matplotlib binary installers for windows – you can get these from the sourceforge download site.Matplotlib.Y/site-packages/easy-inst (where X. removes previous installations. Edit the file (make a backup before you start.2n2-py2. LDFLAGS.1 Binary installers for windows If you have already installed python. Windows questions 201 . 3. changing the line MACOSX_DEPLOYMENT_TARGET=10.8.5 and changing the occurrences of MacOSX10.. 22. for example .sdk into MacOSX10.3 to MACOSX_DEPLOYMENT_TARGET=10. Save the following as a shell script .framework/Versions/Current/lib/python2.4u./matplotlib-0.sh NAME=matplotlib VERSION=0_99 PREFIX=$HOME #branch="release" branch="trunk" if [ $branch = "trunk" ] then echo getting the trunk svn co https://matplotlib. 22.5-macosx-10.svn. checks out the source from svn.py install #--prefix=$PREFIX #Use this if you don’t want it installed into your de cd .sf. just in case): /Library/Frameworks/Python. The backend seems to be set to MacOSX. Choose the files that match your version of python (eg py2.svn.5 if you installed Python 2. Installation FAQ . Release 1. There are also two packaged distributions of python that come preloaded with matplotlib and many other tools like ipython. • the enthought python distribution EPD • python (x. numpy. These packages are quite large because they come with so much. y) 202 Chapter 22.Matplotlib.1 you can get the official version from the python web site.0. but you get everything with a single click installer. scipy. vtk and user interface toolkits. arange. Pylab combines the pyplot functionality (for plotting) with the numpy functionality (for mathematics and for working with arrays) in a single namespace. plt. np.show. pylab. plt. using “from pylab import *”. either pyplot or the object-oriented style is used for the remainder of the plotting code. np.pyplot is a module in matplotlib.zeros. to a preferred style in which pyplot is used for some convenience functions. 0.pi. 10. Example. and pyplot: how are they related? 23. making that namespace (or environment) even more MATLABlike.2) y = sin(x) 203 .plot. and numpy is used explicitly for numeric array operations.CHAPTER TWENTYTHREE USAGE Contents • Usage – Matplotlib. and matplotlib. pylab.figure.1 Matplotlib. the imports at the top are: import matplotlib. This is what you get if you use the ipython shell with the -pylab option.pyplot as plt import numpy as np Then one calls. plt. etc. np. Pyplot provides a MATLAB-style state-machine interface to the underlying object-oriented plotting library in matplotlib. In this preferred style. pylab is a module in matplotlib that gets installed alongside matplotlib. which imports everything from pylab and makes plotting fully interactive. pure MATLAB-style: from pylab import * x = arange(0. We have been gradually converting the matplotlib examples from pure MATLAB-style. for example. and pyplot: how are they related? Matplotlib is the whole package. arange(0. but object-orientation for the rest: import matplotlib.figure() ax = fig.2) y = np.sin(x) plt. why do all the extra typing required as one moves away from the pure MATLAB-style? For very simple things like this example. more clear as to where things come from and what is going on.pyplot as plt import numpy as np x = np.plot(x. 0.plot(x.Matplotlib.sin(x) fig = plt. 10. Usage . the only advantage is educational: the wordier styles are more explicit.pyplot as plt import numpy as np x = np.0. Release 1.add_subplot(111) ax.arange(0. the explicitness and clarity become increasingly valuable. y) plt. and the richer and more complete object-oriented interface will likely make the program easier to write and maintain. 10.1 plot(x.2) y = np.show() So. 0. For more complicated applications. y) show() Now in preferred style. 204 Chapter 23. y) plt. but still using pyplot interface: import matplotlib.show() And using pyplot convenience functions. CHAPTER TWENTYFOUR HOWTO Contents • Howto – Plotting: howto * Find all objects in figure of a certain type * Save transparent figures * Save multiple plots in one pdf file * Move the edge of an axes to make room for tick labels * Automatically make room for tick labels * Configure the tick linewidths * Align my ylabels across multiple subplots * Skip dates where there is no data * Test whether a point is inside a polygon * Control the depth of plot elements * Make the aspect ratio for plots equal * Make a movie * Multiple y-axis scales * Generate images without having a window popup * Use show() – Contributing: howto * Submit a patch * Contribute to matplotlib documentation – Matplotlib in a web application server * matplotlib with apache * matplotlib with django * matplotlib with zope * Clickable images for HTML – Search examples – Cite Matplotlib 205 . there is currently no global alpha setting. linestyle. if True. the following snippet finds every object in the figure which has a set_color property and makes the object blue: def myfunc(x): return hasattr(x. If you need finer grained control.backends.5) ax = fig. For example.3 Save multiple plots in one pdf file Many image file formats can only have one image per file.backend_pdf import PdfPages pp = PdfPages(’multipage. You can set any property on them directly (facecolor. edgecolor. eg you do not want full transparency or you to affect the screen displayed version as well.5) 24.set_alpha(0.add_subplot(111) ax. Currently only the pdf backend has support for this. eg: ax. alpha=0. but will not affect the displayed image on the screen.set_xlabel(’volts’.findobj(text. y.set_color(’blue’) You can also filter on class instances: import matplotlib. Release 1.patches. first initialize the file: from matplotlib. you can set the alpha properties directly.1 Find all objects in figure of a certain type Every matplotlib artist (see Artist tutorial) has a method called findobj() that can be used to recursively search the artist for any artists it may contain that meet some criteria (eg match all Line2D instances or match some arbitrary filter function). linewidth.5) ax.1.1.2 Save transparent figures The savefig() command has a keyword argument transparent which. To make a multi-page pdf file.Matplotlib. but some formats support multi-page files.pdf’) 206 Chapter 24.patch.1 24.set_alpha(0. Howto .Rectangle instance called patch and the axes has a Rectangle instance called patch. The figure has a matplotlib.findobj(myfunc): o.set_fontstyle(’italic’) 24.plot(x. alpha).1 Plotting: howto 24. but you can set the alpha channel on individual elements.5) If you need all the figure elements to be transparent. ’set_color’) for o in fig.figure() fig.patch.Text): o. will make the figure and axes backgrounds transparent when saving. Eg: fig = plt.0.text as text for o in fig. alpha=0.1. subplot.bottom : 0.1.py for an example of placing axes manually. but you have to specify the format: savefig(pp. the multipage pdf object has to be closed: pp. to make the above setting permanent. Release 1.close() 24.1. you would set: figure. to move the bottom of the subplots up to make room for some rotated x tick labels: fig = plt.9 the top of the subplots of the figure wspace = 0.9 the right side of the subplots of the figure bottom = 0.Figure.add_subplot(111) You can control the defaults for these parameters in your matplotlibrc file. See axes_demo.2) ax = fig.2 # the bottom of the subplots of the figure The other parameters you can configure are. For example.add_axes() method). bottom.subplots_adjust() method (in pyplot it is subplots_adjust()).Matplotlib. it is enough to simpy change the subplots adjust parameters as described in Move the edge of an axes to make room for tick labels. you don’t know ahead of time what your 24.1.figure. you can control the default spacing on the left. But in some cases. with their defaults left = 0. Plotting: howto 207 .figure.1 the bottom of the subplots of the figure top = 0.1 You can give the PdfPages object to savefig(). bottom. which allows you to specify the location explicitly: ax = fig. width.125 the left side of the subplots of the figure right = 0.savefig() Finally. right. height]) where all values are in fractional (0 to 1) coordinates.5 Automatically make room for tick labels In most use cases.subplots_adjust(bottom=0.4 Move the edge of an axes to make room for tick labels For subplots.0. see Customizing matplotlib.figure() fig. For example.2 the amount of height reserved for white space between subplots If you want additional control.Figure. 24. format=’pdf’) A simpler way is to call PdfPages.2 the amount of width reserved for blank space between subplots hspace = 0. and top as well as the horizontal and vertical spacing between multiple rows and columns using the matplotlib.add_axes([left.savefig: pp. you can create an Axes using the axes() command (or equivalently the figure matplotlib. ’labels’)) def on_draw(event): bboxes = [] for label in labels: bbox = label. which is used to calculate the text size.7)) labels = ax.figure() ax = fig.Text.figure.left < bbox.mpl_connect(’draw_event’.Bbox.RendererBase instance. Here is that gets a bounding box in relative figure coordinates (0. etc) and a marker (circle. Release 1. square.pyplot as plt import matplotlib.width) # pad a little fig.draw()). dashed.plot(range(10)) ax.text. Any matplotlib.. on_draw) plt.subplotpars. and then do something with it.mpl_connect()) to the “on_draw” signal (DrawEvent) and get the window extent there. eg move the left of the canvas over. really. After the window is drawn and the text instance knows its renderer.show() 24. you can call matplotlib.get_window_extent(). again in relative # figure coords bbox = mtransforms. ’long’.inverse_transformed(fig. One way to solve this chicken and egg problem is to wait until the figure is draw by connecting (matplotlib.1*bbox.add_subplot(111) ax. All Line2D objects support a line (solid. really’.append(bboxi) # this is the bbox that bounds all the bboxes. The tick linewidth is controlled by the “markeredgewidth” property: 208 Chapter 24.Matplotlib. The matplotlib. see Event handling and picking.text.FigureCanvasBase. or how large they will be (data and labels outside your control may be being fed into your graphing application).backend_bases.1.canvas. tick). the ticks are markers.canvas.set_yticks((2.Text instance can report its extent in window coordinates (a negative x coordinate is outside the window). and you may need to automatically adjust your subplot parameters based on the size of the tick labels. but there is a rub.1) of each of the labels and uses it to move the left of the subplots over so that the tick labels fit in the figure import matplotlib.width: # we need to move it over fig.set_yticklabels((’really.transFigure) bboxes.Figure.6 Configure the tick linewidths In matplotlib.0. Howto .union(bboxes) if fig.draw() return False fig. is not known until the figure is drawn (matplotlib.backend_bases.get_window_extent() # the figure transform goes from relative coords->pixels and we # want the inverse of that bboxi = bbox.subplots_adjust(left=1.1 tick labels will be.5.transforms as mtransforms fig = plt. The example below shows the default behavior in the left subplots.get_yticklines(): line. you can often get ylabels that do not align vertically across the multiple subplots. markersize. and all markers. 24. see Axis containers and Tick containers.Matplotlib. matplotlib positions the x location of the ylabel so that it does not overlap any of the y ticks. and the manual setting in the right subplots. which can be unattractive. Plotting: howto 209 . Release 1.1.show() The other properties that control the tick marker.set_markersize(10) plt. You can override this default behavior by specifying the coordinates of the label.1. markeredgecolor.0. and the y data have different scales. really 0 1 2 3 4 5 6 7 8 9 import matplotlib.pyplot as plt fig = plt.plot(range(10)) for line in ax.figure() ax = fig. 24.1 labels long really.7 Align my ylabels across multiple subplots If you have multiple subplots over one another.get_xticklines() + ax. markeredgewidth. are markerfacecolor. By default. For more information on configuring ticks. really.add_subplot(111) ax. one often wants to leave out days on which there is no data.set_title(’ylabels not aligned’) ax1. Howto . 0. eg weekends. pad=5.random.add_subplot(222) ax2.set_ylabel(’aligned 2’.plot(2000*np. bbox=box) ax2. bbox=box) ax4.subplots_adjust(left=0.pyplot as plt matplotlib.5) ax2.rand(10)) ax4.plot(np. 2000) ax4 = fig. The solution is to pass in some proxy x-data. The example below shows how to use an ‘index formatter’ to achieve the desired plot: import import import import numpy as np matplotlib. alpha=0. and then use a custom formatter to format these as dates.add_subplot(221) ax1.5) plt.2) fig = plt.set_label_coords(labelx.3 # axes coords ax2 = fig.1 import numpy as np import matplotlib. 2000) ax3 = fig.plot(np.random.csv’) r.yaxis.Matplotlib.pyplot as plt box = dict(facecolor=’yellow’.set_ylabel(’aligned 1’.6) ax1 = fig.random.0.plot(2000*np.yaxis.rand(10)) ax1. Release 1.rand(10)) ax2. eg evenly sampled indicies. By passing in dates on the x-xaxis.add_subplot(224) ax4.ticker as ticker r = mlab.sort() r = r[-30:] # get the last 30 days 210 Chapter 24. you get large horizontal gaps on periods when there is not data.add_subplot(223) ax3.random. eg financial time series.set_ylabel(’misaligned 2’.set_ylim(0..8 Skip dates where there is no data When plotting time series. bbox=box) ax1.figure() fig.set_label_coords(labelx.1.show() 24.set_title(’ylabels aligned’) ax2.2. wspace=0.set_ylabel(’misaligned 1’.set_ylim(0. 0.bbox=box) ax3.rand(10)) labelx = -0.csv2rec(’.mlab as mlab matplotlib./data/aapl. 1.0 0.FuncFormatter(format_date)) fig. ’o-’) ax.nxutils provides two high performance methods: for a single point use pnpoly() and for an array of points use points_inside_poly().show() # the evenly spaced plot indices def format_date(x.9 Test whether a point is inside a polygon The matplotlib. Plotting: howto 211 .autofmt_xdate() 24. In [25]: import numpy as np 24.1.set_major_formatter(ticker.adj_close.plot(ind.5 0.2 0.Matplotlib.8 0.4 0.00 1 2 3 4 5 6 7 8 9 N = len(r) ind = np.3 0. r.0. 0.4 0.9 0.1 0.00 1 2 3 4 5 6 7 8 9 aligned 1 aligned 2 1500 1500 1000 500 00 1 2 3 4 5 6 7 8 9 0.date[thisind].strftime(’%Y-%m-%d’) fig = plt.figure() ax = fig.1 ylabels not aligned 2000 ylabels aligned 2000 misaligned 1 1000 500 00 1 2 3 4 5 6 7 8 9 1.clip(int(x+0.8 0.5). N-1) return r.2 0.xaxis.arange(N) misaligned 2 plt.6 0.7 0.add_subplot(111) ax. For a discussion of the implementation see pnpoly.6 0. Release 1. pos=None): thisind = np. Matplotlib, Release 1.0.1 In [26]: import matplotlib.nxutils as nx In [27]: verts = np.array([ [0,0], [0, 1], [1, 1], [1,0]], float) In [28]: nx.pnpoly( 0.5, 0.5, verts) Out[28]: 1 In [29]: nx.pnpoly( 0.5, 1.5, verts) Out[29]: 0 In [30]: points = np.random.rand(10,2)*2 In [31]: Out[31]: array([[ [ [ [ [ [ [ [ [ [ points 1.03597426, 1.94061056, 1.08593748, 0.9255139 , 1.54564936, 1.71514397, 1.19133536, 0.40939549, 1.8944715 , 0.03128518, 0.61029911], 0.65233947], 1.16010789], 1.79098751], 1.15604046], 1.26147554], 0.56787764], 0.35190339], 0.61785408], 0.48144145]]) In [32]: nx.points_inside_poly(points, verts) Out[32]: array([False, False, False, False, False, False, False, True, False, True], dtype=bool) 24.1.10 Control the depth of plot elements Within an axes, the order that the various lines, markers, text, collections, etc appear is determined by the matplotlib.artist.Artist.set_zorder() property. The default order is patches, lines, text, with collections of lines and collections of patches appearing at the same level as regular lines and patches, respectively: line, = ax.plot(x, y, zorder=10) You can also use the Axes property matplotlib.axes.Axes.set_axisbelow() to control whether the grid lines are placed above or below your other plot elements. 24.1.11 Make the aspect ratio for plots equal The Axes property matplotlib.axes.Axes.set_aspect() controls the aspect ratio of the axes. You can set it to be ‘auto’, ‘equal’, or some ratio which controls the ratio: ax = fig.add_subplot(111, aspect=’equal’) 212 Chapter 24. Howto Matplotlib, Release 1.0.1 24.1.12 Make a movie If you want to take an animated plot and turn it into a movie, the best approach is to save a series of image files (eg PNG) and use an external tool to convert them to a movie. You can use mencoder, which is part of the mplayer suite for this: #fps (frames per second) controls the play speed mencoder ’mf://*.png’ -mf type=png:fps=10 -ovc \\ lavc -lavcopts vcodec=wmv2 -oac copy -o animation.avi The swiss army knife of image tools, ImageMagick’s convert works for this as well. Here is a simple example script that saves some PNGs, makes them into a movie, and then cleans up: import os, sys import matplotlib.pyplot as plt files = [] fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) for i in range(50): # 50 frames ax.cla() ax.imshow(rand(5,5), interpolation=’nearest’) fname = ’_tmp%03d.png’%i print ’Saving frame’, fname fig.savefig(fname) files.append(fname) print ’Making movie animation.mpg - this make take a while’ os.system("mencoder ’mf://_tmp*.png’ -mf type=png:fps=10 \\ -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg") 24.1.13 Multiple y-axis scales A frequent request is to have two scales for the left and right y-axis, which is possible using twinx() (more than two scales are not currently supported, though it is on the wish list). This works pretty well, though there are some quirks when you are trying to interactively pan and zoom, since both scales do not get the signals. The approach twinx() (and its sister twiny()) uses is to use 2 different axes, turning the axes rectangular frame off on the 2nd axes to keep it from obscuring the first, and manually setting the tick locs and labels as desired. You can use separate matplotlib.ticker formatters and locators as desired since the two axes are independent: import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) t = np.arange(0.01, 10.0, 0.01) s1 = np.exp(t) ax1.plot(t, s1, ’b-’) 24.1. Plotting: howto 213 Matplotlib, Release 1.0.1 ax1.set_xlabel(’time (s)’) ax1.set_ylabel(’exp’) ax2 = ax1.twinx() s2 = np.sin(2*np.pi*t) ax2.plot(t, s2, ’r.’) ax2.set_ylabel(’sin’) plt.show() 24.1.14 Generate images without having a window popup The easiest way to do this is use an image backend (see What is a backend?) such as Agg (for PNGs), PDF, SVG or PS. In your figure generating script, just place call matplotlib.use() directive before importing pylab or pyplot: import matplotlib matplotlib.use(’Agg’) import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.savefig(’myfig’) See Also: Matplotlib in a web application server For information about running matplotlib inside of a web application. 24.1.15 Use show() The user interface backends need to start the GUI mainloop, and this is what show() does. It tells matplotlib to raise all of the figure windows and start the mainloop. Because the mainloop is blocking, you should only call this once per script, at the end. If you are using matplotlib to generate images only and do not want a user interface window, you do not need to call show (see Generate images without having a window popup and What is a backend?). Because it is expensive to draw, matplotlib does not want to redrawing the figure many times in a script such as the following: plot([1,2,3]) xlabel(’time’) ylabel(’volts’) title(’a simple plot’) show() # # # # draw here ? and here ? and here ? and here ? It is possible to force matplotlib to draw after every command, which is what you usually want when working interactively at the python console (see Using matplotlib in a python shell), but in a script you want to defer all drawing until the script has executed. This is especially important for complex figures that take some time to draw. show() is designed to tell matplotlib that you’re all done issuing commands and you want to draw the figure now. Note: show() should be called at most once per script and it should be the last line of your script. At that point, the GUI takes control of the interpreter. If you want to force a figure draw, use draw() instead. 214 Chapter 24. Howto Matplotlib, Release 1.0.1 Many users are frustrated by show because they want it to be a blocking call that raises the figure, pauses the script until the figure is closed, and then allows the script to continue running until the next figure is created and the next show is made. Something like this: # WARNING : illustrating how NOT to use show for i in range(10): # make figure i show() This is not what show does and unfortunately, because doing blocking calls across user interfaces can be tricky, is currently unsupported, though we have made some progress towards supporting blocking events. 24.2 Contributing: howto 24.2.1 Submit a patch First obtain a copy of matplotlib svn (see Install from svn) and make your changes to the matplotlib source code or documentation and apply a svn diff. If it is feasible, do your diff from the top level directory, the one that contains setup.py. Eg,: > cd /path/to/matplotlib/source > svn diff > mypatch.diff and then post your patch to the matplotlib-devel mailing list. If you do not get a response within 24 hours, post your patch to the sourceforge patch tracker, and follow up on the mailing list with a link to the sourceforge patch submissions. If you still do not hear anything within a week (this shouldn’t happen!), send us a kind and gentle reminder on the mailing list. If you have made lots of local changes and do not want to a diff against the entire tree, but rather against a single directory or file, that is fine, but we do prefer svn diffs against the top level (where setup.py lives) since it is nice to have a consistent way to apply them. If you are posting a patch to fix a code bug, please explain your patch in words – what was broken before and how you fixed it. Also, even if your patch is particularly simple, just a few lines or a single function replacement, we encourage people to submit svn diffs against HEAD or the branch they are patching. It just makes life simpler for us, since we (fortunately) get a lot of contributions, and want to receive them in a standard format. If possible, for any non-trivial change, please include a complete, free-standing example that the developers can run unmodified which shows the undesired behavior pre-patch and the desired behavior post-patch, with a clear verbal description of what to look for. The original developer may have written the function you are working on years ago, and may no longer be with the project, so it is quite possible you are the world expert on the code you are patching and we want to hear as much detail as you can offer. When emailing your patch and examples, feel free to paste any code into the text of the message, indeed we encourage it, but also attach the patches and examples since many email clients screw up the formatting of plain text, and we spend lots of needless time trying to reformat the code to make it usable. You should check out the guide to developing matplotlib to make sure your patch abides by our coding conventions The Matplotlib Developers’ Guide. 24.2. Contributing: howto 215 Matplotlib, Release 1.0.1 24.2.2 Contribute to matplotlib documentation matplotlib is a big library, which is used in many ways, and the documentation we have only scratches the surface of everything it can do. So far, the place most people have learned all these features are through studying the examples (Search examples), which is a recommended and great way to learn, but it would be nice to have more official narrative documentation guiding people through all the dark corners. This is where you come in. There is a good chance you know more about matplotlib usage in some areas, the stuff you do every day, than many of the core developers who write most of the documentation. Just pulled your hair out compiling matplotlib for windows? Write a FAQ or a section for the Installing page. Are you a digital signal processing wizard? Write a tutorial on the signal analysis plotting functions like xcorr(), psd() and specgram(). Do you use matplotlib with django or other popular web application servers? Write a FAQ or tutorial and we’ll find a place for it in the User’s Guide. Bundle matplotlib in a py2exe app? ... I think you get the idea. matplotlib is documented using the sphinx extensions to restructured text ReST. sphinx is a extensible python framework for documentation projects which generates HTML and PDF, and is pretty easy to write; you can see the source for this document or any page on this site by clicking on Show Source link at the end of the page in the sidebar (or here for this document). The sphinx website is a good resource for learning sphinx, but we have put together a cheat-sheet at Documenting matplotlib which shows you how to get started, and outlines the matplotlib conventions and extensions, eg for including plots directly from external code in your documents. Once your documentation contributions are working (and hopefully tested by actually building the docs) you can submit them as a patch against svn. See Install from svn and Submit a patch. Looking for something to do? Search for TODO. 24.3 Matplotlib in a web application server Many users report initial problems trying to use maptlotlib in web application servers, because by default matplotlib ships configured to work with a graphical user interface which may require an X11 connection. Since many barebones application servers do not have X11 enabled, you may get errors if you don’t configure matplotlib for use in these environments. Most importantly, you need to decide what kinds of images you want to generate (PNG, PDF, SVG) and configure the appropriate default backend. For 99% of users, this will be the Agg backend, which uses the C++ antigrain rendering engine to make nice PNGs. The Agg backend is also configured to recognize requests to generate other output formats (PDF, PS, EPS, SVG). The easiest way to configure matplotlib to use Agg is to call: # do this before importing pylab or pyplot import matplotlib matplotlib.use(’Agg’) import matplotlib.pyplot as plt For more on configuring your backend, see What is a backend?. Alternatively, you can avoid pylab/pyplot altogeher, which will give you a little more control, by calling the API directly as shown in agg_oo.py . You can either generate hardcopy on the filesystem by calling savefig: 216 Chapter 24. Howto Matplotlib, Release 1.0.1 # do this before importing pylab or pyplot import matplotlib matplotlib.use(’Agg’) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3]) fig.savefig(’test.png’) or by saving to a file handle: import sys fig.savefig(sys.stdout) Here is an example using the Python Imaging Library PIL. First the figure is saved to a StringIO objectm which is then fed to PIL for further processing: import StringIO, Image imgdata = StringIO.StringIO() fig.savefig(imgdata, format=’png’) imgdata.seek(0) # rewind the data im = Image.open(imgdata) 24.3.1 matplotlib with apache TODO; see Contribute to matplotlib documentation. 24.3.2 matplotlib with django TODO; see Contribute to matplotlib documentation. 24.3.3 matplotlib with zope TODO; see Contribute to matplotlib documentation. 24.3.4 Clickable images for HTML Andrew Dalke of Dalke Scientific has written a nice article on how to make html click maps with matplotlib agg PNGs. We would also like to add this functionality to SVG and add a SWF backend to support these kind of images. If you are interested in contributing to these efforts that would be great. 24.4 Search examples The nearly 300 code examples-index included with the matplotlib source distribution are full-text searchable from the search page, but sometimes when you search, you get a lot of results from the The Matplotlib API or other documentation that you may not be interested in if you just want to find a complete, free-standing, 24.4. Search examples 217 Matplotlib, Release 1.0.1 working piece of example code. To facilitate example searches, we have tagged every code example page with the keyword codex for code example which shouldn’t appear anywhere else on this site except in the FAQ and in every example. So if you want to search for an example that uses an ellipse, search for codex ellipse. 24.5 Cite Matplotlib If you want to refer to matplotlib in a publication, you can use “Matplotlib: A 2D Graphics Environment” by J. D. Hunter In Computing in Science & Engineering, Vol. 9, No. 3. (2007), pp. 90-95 (see citeulike): @article{Hunter:2007, Address = {10662 LOS VAQUEROS CIRCLE, PO BOX 3014, LOS ALAMITOS, CA 90720-1314 USA}, Author = {Hunter, John D.}, Date-Added = {2010-09-23 12:22:10 -0700}, Date-Modified = {2010-09-23 12:22:10 -0700}, Isi = {000245668100019}, Isi-Recid = {155389429}, Journal = {Computing In Science \& Engineering}, Month = {May-Jun}, Number = {3}, Pages = {90--95}, Publisher = {IEEE COMPUTER SOC}, Times-Cited = {21}, Title = {Matplotlib: A 2D graphics environment}, Type = {Editorial Material}, Volume = {9}, Year = {2007}, Abstract = {Matplotlib is a 2D graphics package used for Python for application development, interactive scripting, and publication-quality image generation across user interfaces and operating systems.}, Bdsk-Url-1 = {http://gateway.isiknowledge.com/gateway/Gateway.cgi?GWVersion=2&SrcAuth=Alerting&S 218 Chapter 24. Howto CHAPTER TWENTYFIVE TROUBLESHOOTING Contents • Troubleshooting – Obtaining matplotlib version – matplotlib install location – .matplotlib directory location – Report a problem – Problems with recent svn versions 25.1 Obtaining matplotlib version To find out your matplotlib version number, import it and print the __version__ attribute: >>> import matplotlib >>> matplotlib.__version__ ’0.98.0’ 25.2 matplotlib install location You can find what directory matplotlib is installed in by importing it and printing the __file__ attribute: >>> import matplotlib >>> matplotlib.__file__ ’/home/jdhunter/dev/lib64/python2.5/site-packages/matplotlib/__init__.pyc’ 25.3 .matplotlib directory location Each user has a .matplotlib/ directory which may contain a matplotlibrc file and various caches to improve matplotlib’s performance. To locate your .matplotlib/ directory, use matplotlib.get_configdir(): 219 Matplotlib, Release 1.0.1 >>> import matplotlib as mpl >>> mpl.get_configdir() ’/home/darren/.matplotlib’ On unix like systems, this directory is generally located in your HOME directory. On windows, it is in your documents and settings directory by default: >>> import matplotlib >>> mpl.get_configdir() ’C:\\Documents and Settings\\jdhunter\\.matplotlib’ If you would like to use a different configuration directory, you can do so by specifying the location in your MPLCONFIGDIR environment variable – see setting-linux-osx-environment-variables. 25.4 Report a problem If you are having a problem with matplotlib, search the mailing lists first: there’s a good chance someone else has already run into your problem. If not, please provide the following information in your e-mail to the mailing list: • your operating system; on Linux/UNIX post the output of uname -a • matplotlib version: python -c ‘import matplotlib; print matplotlib.__version__‘ • where you obtained matplotlib (e.g. your Linux distribution’s packages or the matplotlib Sourceforge site, or the enthought python distribution EPD. • any customizations to your matplotlibrc file (see Customizing matplotlib). • if the problem is reproducible, please try to provide a minimal, standalone Python script that demonstrates the problem. This is the critical step. If you can’t post a piece of code that we can run and reproduce your error, the chances of getting help are significantly diminished. Very often, the mere act of trying to minimize your code to the smallest bit that produces the error will help you find a bug in your code that is causing the problem. • you can get very helpful debugging output from matlotlib by running your script with a verbose-helpful or --verbose-debug flags and posting the verbose output the lists: > python simple_plot.py --verbose-helpful > output.txt If you compiled matplotlib yourself, please also provide • any changes you have made to setup.py or setupext.py • the output of: rm -rf build python setup.py build 220 Chapter 25. Troubleshooting Matplotlib, Release 1.0.1 The beginning of the build output contains lots of details about your platform that are useful for the matplotlib developers to diagnose your problem. • your compiler version – eg, gcc --version Including this information in your first e-mail to the mailing list will save a lot of time. You will likely get a faster response writing to the mailing list than filing a bug in the bug tracker. Most developers check the bug tracker only periodically. If your problem has been determined to be a bug and can not be quickly solved, you may be asked to file a bug in the tracker so the issue doesn’t get lost. 25.5 Problems with recent svn versions First make sure you have a clean build and install (see Cleanly rebuild and reinstall everything), get the latest svn update, install it and run a simple test script in debug mode: rm -rf rm -rf svn up python python build /path/to/site-packages/matplotlib* setup.py install > build.out examples/pylab_examples/simple_plot.py --verbose-debug > run.out and post build.out and run.out to the matplotlib-devel mailing list (please do not post svn problems to the users list). Of course, you will want to clearly describe your problem, what you are expecting and what you are getting, but often a clean build and install will help. See also Report a problem. 25.5. Problems with recent svn versions 221 Matplotlib, Release 1.0.1 222 Chapter 25. Troubleshooting Part III The Matplotlib Developers’ Guide 223 CHAPTER TWENTYSIX CODING GUIDE 26.1 Version control 26.1.1 svn checkouts Checking out everything in the trunk (matplotlib and toolkits): svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk \ matplotlib --username=youruser --password=yourpass Checking out the main source: svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/\ matplotlib mpl --username=youruser --password=yourpass Branch checkouts, eg the 1.0.x maintenance branch: svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/\ v1_0_maint mpl1 --username=youruser --password=yourpass 26.1.2 Committing changes When committing changes to matplotlib, there are a few things to bear in mind. • if your changes are non-trivial, please make an entry in the CHANGELOG • if you change the API, please document it in doc/api/api_changes.rst, and consider posting to matplotlib-devel • Are your changes python2.4 compatible? We still support 2.4, so avoid features new to 2.5 • Can you pass examples/tests/backend_driver.py? This is our poor man’s unit test. • Can you add a test to unit/nose_tests.py to test your changes? • If you have altered extension code, do you pass unit/memleak_hawaii3.py? • if you have added new files or directories, or reorganized existing ones, are the new files included in the match patterns in MANIFEST.in. This file determines what goes into the source distribution of the mpl build. 225 Matplotlib, Release 1.0.1 • Keep the maintenance branch (0.91) the latest release branch (eg 0.98.4) and trunk in sync where it makes sense. If there is a bug on both that needs fixing, use svnmerge.py to keep them in sync. See Using svnmerge below. 26.1.3 Using svnmerge svnmerge is useful for making bugfixes to a maintenance branch, and then bringing those changes into the trunk. The basic procedure is: • install svnmerge.py in your PATH: > wget http://svn.apache.org/repos/asf/subversion/trunk/contrib/\ client-side/svnmerge/svnmerge.py • get a svn checkout of the branch you’ll be making bugfixes to and the trunk (see above) • Create and commit the bugfix on the branch. • Then make sure you svn upped on the trunk and have no local modifications, and then from your checkout of the svn trunk do: svnmerge.py merge -S BRANCHNAME Where BRANCHNAME is the name of the branch to merge from, e.g. v1_0_maint. If you wish to merge only specific revisions (in an unusual situation), do: > svnmerge.py merge -rNNN1-NNN2 where the NNN are the revision numbers. Ranges are also acceptable. The merge may have found some conflicts (code that must be manually resolved). Correct those conflicts, build matplotlib and test your choices. If you have resolved any conflicts, you can let svn clean up the conflict files for you: > svn -R resolved . svnmerge.py automatically creates a file containing the commit messages, so you are ready to make the commit: > svn commit -F svnmerge-commit-message.txt Setting up svnmerge Note: The following applies only to release managers when there is a new release. Most developers will not have to concern themselves with this. • Creating a new branch from the trunk (if the release version is 1.0 at revision 8503): 226 Chapter 26. Coding guide Matplotlib, Release 1.0.1 > svn copy \ https://matplotlib.svn.sf.net/svnroot/matplotlib/trunk/matplotlib@8503 \ https://matplotlib.svn.sf.net/svnroot/matplotlib/branches/v1_0_maint \ -m "Creating maintenance branch for 1.0" • You can add a new branch for the trunk to “track” using “svnmerge.py init”, e.g., from a working copy of the trunk: > svnmerge.py init https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/branches/v1_0_maint property ’svnmerge-integrated’ set on ’.’ After doing a “svn commit” on this, this merge tracking is available to everyone, so there’s no need for anyone else to do the “svnmerge init”. • Tracking can later be removed with the “svnmerge.py uninit” command, e.g.: > svnmerge.py -S v1_0_maint uninit 26.1.4 Using git Some matplotlib developers are experimenting with using git on top of the subversion repository. Developers are not required to use git, as subversion will remain the canonical central repository for the foreseeable future. Cloning the git mirror There is an experimental matplotlib github mirror of the subversion repository. To make a local clone of it in the directory matplotlib, enter the following commands: # Download the entire git repository into "matplotlib", name the source repository "svn". git clone --origin svn
[email protected]:astraw/matplotlib.git # Change into the newly created git repository. cd matplotlib # Setup the subversion mirroring. git svn init --trunk=trunk/matplotlib --prefix=svn/ https://matplotlib.svn.sourceforge.net/svnroot/matpl # Tell git svn to analyze the subversion history git svn rebase -l To install from this cloned repository, use the commands in the svn installation section: > cd matplotlib > python setup.py install Note that it is not possible to interact with the matplotlib maintenance branches through git due to different representations of source code repositories in svnmerge and git. 26.1. Version control 227 Matplotlib, Release 1.0.1 An example git workflow The following is a suggested workflow for git/git-svn. Start with a virgin tree in sync with the svn trunk on the git branch “trunk”: git checkout trunk git svn rebase To create a new, local branch called “whizbang-branch”: git checkout -b whizbang-branch Do make commits to the local branch: # hack on a bunch of files git add bunch of files git commit -m "modified a bunch of files" # repeat this as necessary Now, go back to the trunk branch and append the history of your branch to the git trunk branch, which will end up as the svn trunk: git git git git git checkout trunk svn rebase # Ensure we rebase whizbang-branch svn dcommit -n # Check svn dcommit # Actually have most recent svn # Append whizbang changes to trunk branch that this will apply to svn apply to svn Finally, you may want to continue working on your whizbang-branch, so rebase it to the new trunk: git checkout whizbang-branch git rebase trunk How was this git mirror set up? These are notes for those interested in mirroring a subversion repository on github. I pieced this together by lots of trial-and-error. Step 1: Create a local mirror of the svn repository rsync -avzP rsync://matplotlib.svn.sourceforge.net/svn/matplotlib/ matplotlib-svn-rsync/ Step 2: Import the svn history into a new git repository #!/bin/bash set -e TARGET=mpl.git.fixed GIT=/home/astraw/git/bin/git TRUNKBRANCH=trunk SVNBRANCHPREFIX="svn/" 228 Chapter 26. Coding guide Matplotlib, Release 1.0.1 rm -rf $TARGET mkdir $TARGET cd $TARGET $GIT init $GIT svn init --rewrite-root=https://matplotlib.svn.sourceforge.net/svnroot/matplotlib \ --trunk=trunk/matplotlib --prefix=$SVNBRANCHPREFIX file:///mnt/workdisk/tmp/matplotlib-svn-rsync $GIT svn fetch # now, make master branch track ${SVNBRANCHPREFIX}trunk $GIT checkout master -b tmp $GIT branch -d master $GIT checkout ${SVNBRANCHPREFIX}trunk -b $TRUNKBRANCH $GIT branch -D tmp $GIT svn rebase -l Step 3: Upload the git repository to github #!/bin/bash set -e TARGET=mpl.git.fixed GIT=/home/astraw/git/bin/git TRUNKBRANCH=trunk SVNBRANCHPREFIX="svn/" cd $TARGET $GIT remote add github
[email protected]:astraw/matplotlib.git git push github $TRUNKBRANCH:master 26.2 Style guide 26.2.1 Importing and name spaces For numpy, use: import numpy as np a = np.array([1,2,3]) For masked arrays, use: import numpy.ma as ma For matplotlib main module, use: import matplotlib as mpl mpl.rcParams[’xtick.major.pad’] = 6 For matplotlib modules (or any other modules), use: 26.2. Style guide 229 use parentheses to break it. and similarly for c++-mode-hook and c-mode-hook (add-hook ’python-mode-hook (lambda () (add-hook ’write-file-functions ’delete-trailing-whitespace))) for older versions of emacs (emacs<22) you need to do: 230 Chapter 26.cbook. use the prefix ‘m’ with the import some.transforms as transforms matplotlib.1 import matplotlib.py before checking changes into svn. please use reindent. Keep docstrings uniformly indented as in the example below. It may be preferable to use a temporary variable to replace a single long line with two shorter and more readable lines.0. if there is a file with tabs or a different number of spaces it is a bug – please fix it.lines or matplotlib.2 Naming.transforms as mtrans # OK # OK.dedent() function is needed to remove excess indentation only if something will be interpolated into the docstring.transforms as mtransforms matplotlib. do not use an escaped newline.Matplotlib. with nothing to the left of the triple quotes. again as in the example below. Configure your editor to use spaces.emacs will cause emacs to strip trailing white space upon saving for python. we want to hew as closely as possible to the standard coding guidelines for python written by Guido in PEP 0008. Coding guide . use reindent. if you want to disambiguate # OK. Release 1. C and C++: . The matplotlib. Tell your editor to strip whitespace from line ends when saving a file. though we do not do this throughout.py as a command-line script.2. • functions and class methods: lower or lower_underscore_separated • attributes and variables: lower or lowerUpper • classes: Upper or MixedCase Prefer the shortest names that are still readable.colors. If you are an emacs user. the following in your . Limit line length to 80 characters. Unless you are sure your editor always does the right thing. eg matplotlib. If a logical line needs to be longer. The standard indentation unit is always four spaces.lines as mlines matplotlib. There are some modules with names that match commonly used local variable names. Please do not commit lines with trailing white space. as it causes noise in svn diffs. and formatting conventions In general. To detect and fix these and other whitespace errors (see below). To avoid the clash.cbook as cbook if cbook. spacing.iterable(z): pass We prefer this over the equivalent from matplotlib import cbook because the latter is ambiguous as to whether cbook is a module or a function. not hard tabs. The former makes it explicit that you are importing a module or package. if you want to abbreviate 26. eg: import import import import matplotlib.thing as mthing syntax. and let others pass through. no one looks at the keywords.py def __init__(self. the use of **kwargs should be reserved for pass-through keyword arguments.update(kwargs) update does the work looking for methods named like set_property if property is a keyword argument.. x=0. i. text=’’.0. True) if not self. x. **kwargs): scalex = kwargs.Text. True) scaley = kwargs. you may want to consume some keys in the local function.pop(’scaley’. as in the example above. in plot().py def text(self.py def text(*args. The definition of the pylab text function is a simple pass-through to matplotlib.pylab. y=y.Artist. and not passed on. **kwargs): t = Text(x=x.1 (add-hook ’python-mode-hook (lambda () (add-hook ’local-write-file-hooks ’delete-trailing-whitespace))) 26.Axes._hold: self. fontdict=None.text(*args. *args. For example. If all the keyword args are to be used in the function._get_lines(*args.text(). y. withdash=False. You can pop the ones to be used locally and pass on the rest.__init__(): # in axes. **kwargs): ret = gca().2. **kwargs) draw_if_interactive() return ret text() in simplified form looks like this.2. A typical example is in matplotlib. y=0.text(): # in pylab.axes. Release 1.cla() lines = [] for line in self. text=s.text.update() method: illustration) just passes them on to the # in text. **kwargs): self.artist. scalex and scaley are local arguments and the rest are passed on as Line2D() keyword arguments: # in axes. Style guide 231 .add_line(line) lines.append(line) 26. they just get passed through the API to the artist constructor which looks for suitably named methods and calls them with the value. As a general rule.3 Keyword argument processing Matplotlib makes extensive use of **kwargs for pass-through customizations from one function to another. s. In some cases. **kwargs) and __init__() (again with liberties for matplotlib.py def plot(self.__init__(self) self. I.pop(’scalex’..e. **kwargs): Artist. use the key/value keyword args in the function definition rather than the **kwargs idiom.e. it just passes all args and kwargs on to matplotlib.Matplotlib. plot(): 232 Chapter 26.lines. 1) self..Axes.levels)) elif len(args) == 1: . The functions matplotlib.).kwdocd[’Line2D’] = artist. python will not allow you to use named keyword args after the *args usage.’ | ’:’ | ’steps’ | ’None’ | ’ ’ | ’’ ] """ Since matplotlib uses a lot of pass-through kwargs.artist. Here is an example from matplotlib. etc.1 Note: there is a use case when kwargs are meant to be used locally in the function (not passed on). **kwargs): fontsize = kwargs. the docs are updated automagically. semilogy(). Yes.py artist. eg. 2. In this case.. An example is matplotlib.fmt = kwargs.kwdoc(Line2D) Then in any function accepting Line2D pass-through kwargs.Line2D: # in lines.get(’fontsize’. None) if len(args) == 0: levels = self. All properties that you want to support through setp and getp should have a set_property and get_property method in the Artist class.get(’colors’.3f ’) colors = kwargs..get(’inline’.clabel(): # in contour. Release 1. but it is a historical legacy for now.lines: # in lines. That is when you want to use *args to allow variable numbers of nonkeyword args.. linestyle): """ Set the linestyle of the line ACCEPTS: [ ’-’ | ’--’ | ’-.py def set_linestyle(self. 26. Matplotlib uses a docstring interpolation scheme to support documentation of every function that takes a **kwargs.Matplotlib.0.levels indices = range(len(self. in every function that creates a line (plot(). The requirements are: 1. in matplotlib. single point of configuration so changes to the properties don’t require multiple docstring edits. The kwdocd is a single dictionary that maps class name to a docstring of kwargs.py def clabel(self. so you will be forced to use **kwargs. ’%1. as automated as possible so that as properties change. this is not ideal given python properties or enthought traits. semilogx(). Coding guide .etc. but you still need the **kwargs idiom. The setter methods use the docstring with the ACCEPTS token to indicate the type of argument the method accepts.artist.get(’fmt’. it can be difficult for the new user to know which kwargs are supported.3 Documentation and docstrings Matplotlib uses artist introspection of docstrings to support properties. Eg. None) inline = kwargs.axes. They combine python string interpolation in the docstring with the matplotlib artist introspection facility that underlies setp and getp.. eg..contour. matplotlib.kwdocd and matplotlib.ContourLabeler.kwdoc() to facilitate this. *args. the backend setting in matplotlibrc (Customizing matplotlib) supports an external backend via the module directive.0. Release 1. if defined. *args.use(’module://my_backend’) • from the command shell with the -d flag: > python simple_plot.py is a matplotlib backend in your PYTHONPATH. eg. if my_backend. which can then be accessed using matplotlib. There are some some manual hacks in this case. Developing a new backend 233 .4 Developing a new backend If you are working on a custom backend. See Axes.py def plot(self.__init__().4.cbook.Patch. and these are automatically generated when the website it built to show up both in the examples and gallery sections of the website. violating the “single entry point” requirement above – see the artist.kwdocd[’Patch’] setting in matplotlib. since the artist inspector cannot work until the class is fully defined and we can’t modify the Patch.__doc__) % artist.__doc__ = cbook.5 Writing examples We have hundreds of examples in subdirectories of file:matplotlib/examples in the trunk. Thus any example data that is required for the example should be provided through the sample_data svn directory.patches. default True.get_sample_data(). and do not have ready access to the file:examples directory in which they reside. matplotlib.autoscale_view for more information """ pass plot.patches. First get a copy of the repository and svn add your data: 26. you can set use it on one of several ways • in matplotlibrc: backend : module://my_backend • with the use directive is your script: import matplotlib matplotlib.py -d module://my_backend 26. Many people find these examples from the website. **kwargs): """ Some stuff omitted The kwargs are Line2D properties: %(Line2D)s kwargs scalex and scaley. 26.__doc__ docstring outside the class definition.__init__. are passed on to autoscale_view to determine whether the x and y axes are autoscaled. which supports Patch kwargs.1 # in axes.Matplotlib.dedent(plot.kwdocd Note there is a problem for Artist __init__ methods. svn. (There is other old testing cruft around. 234 Chapter 26. here is a test from Nose determines which functions are tests by searching for functions beginning with “test” in their name.2 Writing a simple test Many elements of Matplotlib can be tested using standard tests.sourceforge. The tests are in matplotlib. (this is assuming the test is installed): nosetests matplotlib.dat sample_data/ cd sample_data svn add mydata.1 Running the tests Running the tests is simple. eg. and customizations to the nose testing infrastructure are in matplotlib.test() To run a single test from the command line.Matplotlib.6.0. If you prefer just to get the full path to the file instead of an file object: import matplotlib.6. matplotlib.test_simplification:test_clipping 26. please ignore it while we consolidate our testing to these locations.test_basic: from nose.tests.cbook as cbook fh = cbook.dat svn commit -m ’added my data’ and then in your example code you can load it into a file handle with: import matplotlib.get_sample_data(’mydata.2) For example.1 svn co https://matplotlib.cbook as cbook datafile = cbook.dat’.tests. asfileobj=False) print ’datafile’. datafile 26.net/svnroot/matplotlib/trunk/sample_data cp ~/path/to/mydata. you can provide a dot-separated path to the module and function. Release 1.6 Testing Matplotlib has a testing infrastructure based on nose.dat’) The file will be fetched from the svn repo using urllib and updated when the revision number changes. making it easy to write new tests.) 26.tests. Coding guide . Make sure you have nose installed and type from within Python: import matplotlib matplotlib.get_sample_data(’mydata.testing.tools import assert_equal def test_simple(): ’’’very simple example test’’’ assert_equal(1+1. sin(x) ax = fig.spines[’right’].plot(x.pyplot as plt @image_comparison(baseline_images=[’spines_axes_positions.6. The main consideration is that you must specify the “baseline”. For example.pi.yaxis. you may mark it as a known failing test with the knownfailureif() decorator.2*np. The correspondence is done by matching filenames.25)) ax.spines[’bottom’].6. although the following test will fail.set_color(’none’) fig. (See Writing examples above for a description of how to add files to the sample_data repository. it is an expected failure: from nose.3 Writing an image comparison test Writing an image based test is only slightly more difficult than a simple test.set_ticks_position(’top’) ax.1 26.100) y = 2*np. Release 1.figure() x = np.png’]) def test_spines_axes_positions(): # SF bug 2852168 fig = plt.add_subplot(1.png’) The mechanism for comparing images is extremely simple – it compares an image saved in the current directory with one from the Matplotlib sample_data repository. images in the image_comparison() decorator.spines[’top’].0.spines[’left’].0.testing.decorators import image_comparison import matplotlib.6.) 26.4 Known failing tests If you’re writing a test.linspace(0.savefig(’spines_axes_positions.tools import assert_equal from matplotlib. • The correct image gets added to the sample_data respository with the name test_baseline_<IMAGE_FILENAME. or expected.set_color(’none’) ax.y) ax.xaxis. This allows the test to be added to the test suite and run on the buildbots without causing undue alarm.1)) ax.3) 26.1.set_position((’axes’.set_title(’centered spines’) ax.testing.0. this test generates a single image and automatically tests it: import numpy as np import matplotlib from matplotlib. Testing 235 .decorators import knownfailureif @knownfailureif(True) def test_simple_fail(): ’’’very simple example test that should fail’’’ assert_equal(1+1. For example.png>.set_ticks_position(’right’) ax. so ensure that: • The filename given to savefig() is exactly the same as the filename given to image_comparison() in the baseline_images argument.set_position((’axes’.1) ax.Matplotlib. py.tests. Coding guide . False. Distributing binary-only versions of Python. which in addition to granting you full rights to the source code including redistribution. python itself is released under a BSD compatible license. whatever. which can be a value such as True. These basically allow you to do whatever you want with the code: ignore it. Non-BSD compatible licenses are acceptable in matplotlib toolkits (eg basemap). you may consider contacting the author and asking them to relicense it.1 Note that the first argument to the knownfailureif() decorator is a fail condition. You can also write extension modules for Python and provide them only in binary form. I.6. append its name to default_test_modules in lib/matplotlib/__init__. python and TeX. or ‘indeterminate’. possibly a toolkit. The second major class are the BSD-style licenses (which includes MIT and the python PSF license).. gcc. 26. There are countless other licenses that place specific restrictions on code reuse. carries with it an extra obligation.7. in the sense that. or may be a dynamically evaluated expression. you are required to give the source code to other people and give them the right to redistribute it as well. The best known and perhaps most widely used license is the GPL. and we choose a license that was based on the python license (BSD compatible). Many of the most famous and widely used open source projects are released under the GPL. your product must be released under a GPL compatible license. quoting from the PSF license page: There is no GPL-like "copyleft" restriction.Matplotlib.5 Creating a new module in matplotlib.tests Let’s say you’ve added a new module named matplotlib. make sure you include a copy of that code’s license in the license directory if the code’s license requires you to distribute the license with it. but there is an important difference to be considered in the GPL and BSD variants. include it in your own open source project. Famous projects released under a BSD-style license in the permissive sense of the last paragraph are the BSD operating system. emacs and sage. sell it. MIT or compatible license (see the Open Source Initiative licenses page for details on individual licenses).test_whizbang_features.0. If it doesn’t. BSD. or link with it.7 Licenses Matplotlib only uses BSD compatible code. 26. GPL and LGPL code are not acceptable in the main code base. 236 Chapter 26. Release 1. matplotlib is a python extension. If you include code. To add this module to the list of default tests. but make sure you clearly state the licenses you are using. If you use GPL code in your own code. If you bring in code from another project make sure it has a PSF. include it in your proprietary product.1 Why BSD compatible? The two dominant license variants in the wild are GPL-style and BSD-style. 26. There is no requirement to release any of your source code.e. though we are considering an alternative way of distributing L/GPL code through an separate channel. modified or not. is allowed. There are several reasons why early matplotlib developers selected a BSD compatible license. including linux. 7.0. and many software companies will not use GPL code in software they plan to distribute. Companies and institutions who use matplotlib often make significant contributions.1 Also. even those that are highly committed to open source development. scipy. we wanted to attract as many users and developers as possible. Two of the matplotlib backends (FLTK and WX) were contributed by private companies. 26. they want to retain the right to release some proprietary code. the enthought tool suite and python itself are all distributed under BSD compatible licenses. In effect. out of legitimate concern that use of the GPL will “infect” their code base by its viral nature. Licenses 237 . the enthought tool suite and python itself are all distributed under BSD compatible licenses. such as enthought. The final reason behind the licensing choice is compatibility with the other python extensions for scientific computing: ipython. numpy. even a boring one. Release 1. The other reason is licensing compatibility with the other python extensions for scientific computing: ipython. scipy.Matplotlib. because they have the resources to get a job done. numpy. Matplotlib. Release 1.1 238 Chapter 26. Coding guide .0. api reference. The documentation suite is built as a single document in order to make the most effective use of cross referencing. To build the users guide in html format.rst extension is not necessary) in the table of contents. Sphinx-0.py install The documentation sources are found in the doc/ directory in the trunk.py html you can also pass a latex flag to make. doc/api and doc/faq. 27.rst. developers guide.1 Getting started The documentation for matplotlib is generated from ReStructured Text using the Sphinx documentation generation tool./make.py file located in the doc/. You might still run into problems. we want to make navigating the Matplotlib documentation as easy as possible. or pass no arguments to build everything. The main entry point is doc/index. Additional files can be added to the various guides by including their base file name (the .rst file for the users guide. The output produced by Sphinx can be configured by editing the conf.py to build a pdf. and faqs.CHAPTER TWENTYSEVEN DOCUMENTING MATPLOTLIB 27. doc/devel. so most developers work from the sphinx source repository (Mercurial based) because it is a rapidly evolving project: hg clone http://bitbucket.org/birkenfeld/sphinx/ cd sphinx python setup. It is also possible to include other documents through the use of an include statement.5 or later is required.py html or: . which pulls in the index.2 Organization of matplotlib’s documentation The actual ReStructured Text files are kept in doc/users. such as: 239 . cd into doc/ and do: python make. and in the usual way by latex.0. • Mathematical expressions can be rendered as png images in html. use the :file: directive. when referring to external files.3]) 240 Chapter 27. • Sphinx does not support tables with column.1) • Interactive IPython sessions can be illustrated in the documentation using the following directive: . For example. Documenting matplotlib . and: . Matplotlib’s documentation makes heavy use of cross-referencing and other semantic markup. • Function arguments and keywords should be referred to using the emphasis role. Such tables can not be used when documenting matplotlib..or row-spanning cells for latex output.. sourcecode:: ipython In [69]: lines = plot([1. This will keep matplotlib’s documentation consistant with Python’s documentation: Here is a description of *argument* Please do not use the default role: Please do not describe ‘argument‘ like this.3]) which would yield: In [69]: lines = plot([1.. math:: \int_{-\infty}^{\infty}\frac{e^{i\phi}}{1+x^2\frac{e^{i\phi}}{1+x^2}} yields: ∞ −∞ eiφ e 1 + x2 1+x2 iφ (27. nor the literal role: Please do not describe ‘‘argument‘‘ like this./.. include:: .Matplotlib. Release 1./TODO 27..1 .2. For example: 2 :math:‘\sin(x_n^2)‘ yields: sin(xn ). Here are a few additional things to keep in mind: • Please familiarize yourself with the Sphinx directives for inline markup.2.3 Formatting The Sphinx website contains plenty of documentation concerning ReST markup and working with Sphinx in general. use something else.. • Use the seealso directive.3.98 This feature is obsolete.. for example: . seealso:: Using ReST :ref:‘emacs-helpers‘: One example A bit about :ref:‘referring-to-mpl-docs‘: One more yields: See Also: Using ResT Emacs helpers: One example A bit about Referring to mpl documents: One more • Please keep the Glossary in mind when writing documentation... deprecated:: 0.98: The transforms have been completely revamped. Formatting 241 . [#] • Use the note and warning directives. use something else.0. 1 For example. to draw attention to important comments: . note:: Here is a note yields: Note: here is a note also: Warning: here is a warning • Use the deprecated directive when appropriate: .98 The transforms have been completely revamped. 27.. rubric:: Footnotes . which have similar syntax to the deprecated role: . sparingly.Matplotlib. yields: Deprecated since version 0. • Use the versionadded and versionchanged directives. Release 1.1 • Footnotes 1 can be added using [#]_. New in version 0.98: This feature is obsolete. followed later by: .. You can create a references to a term in the glossary with the :term: role. versionadded:: 0. Please run the doc/pyplots/make. • Keyword arguments should be described using a definition list..py) for generating the images from the python script and including either a png copy for html or a pdf for latex: . in order to keep the prerequisites to the documentation effort as low as possible. each will be given a numbered file name and included. a PDF).3. Note: matplotlib makes extensive use of keyword arguments as pass-through arguments.2 Static figures Any figures that rely on optional system configurations need to be handled a little differently.4 Figures 27. plot:: pyplots/pyplot_simple.1 Dynamically generated figures Figures can be automatically generated from scripts and included in the docs. there are a many cases where a table is used in place of a definition list for autogenerated sections of docstrings.py script when adding such figures.py :include-source: If the script produces multiple figures (through multiple calls to pyplot. Documenting matplotlib . 27. this will be done automatically at build time to ensure that the code that is included runs and produces the advertised figure. Plots from the examples directory may be referenced through the symlink mpl_examples in the doc directory. and commit the script and the images to svn. Several figures will be saved with the same basename as the filename when the documentation is generated (low and high res PNGs..4. eg. though we don’t recommend using this in most cases since it is probably better to choose the correct figure size and dpi in mpl and let it handle the scaling.1 Docstrings In addition to the aforementioned formatting suggestions: • Please limit the text width of docstrings to 70 characters.0.Matplotlib. but additional entries in the index need to be explicitly added. marked up as source code. These figures are not to be generated during the documentation build. plot:: mpl_examples/pylab_examples/simple_plot. It is not necessary to explicitly save the figure in the script. Release 1.py The :scale: directive rescales the image to some percentage of the original size. 27. The path should be relative to the doc directory. Please also add a line to the README in doc/pyplots for any 242 Chapter 27.: .figure()). 27. Matplotlib includes a Sphinx extension (sphinxext/plot_directive. Any plots specific to the documentation should be added to the doc/pyplots directory and committed to SVN.4. :include-source: will present the contents of the file.1 • The autodoc extension will handle index entries for the API. refer to it via a relative path from the document where the rst file resides./.. a license file or an image file from mpl-data. it is easier to simply include a symlink to the files at the top doc level directory./.pyplot..5. eg. In the top level doc directory we have symlinks pointing to the mpl examples: home:~/mpl/doc> ls -l mpl_* mpl_examples -> . in users/navigation_toolbar./lib/matplotlib/mpl-data/images/subplots.plot() can refer to the examples in a known location.4. but the distro becomes very large on platforms that do not support links (eg the font files are duplicated and large) 27.rst: ... if I want to refer to a file in the mpl-data directory. so without getting into the dirty details. Release 1.png In the users subdirectory.. This way. For example. e.1 additional requirements necessary to generate a new figure./examples So we can include plots from the examples dir using the symlink: ..py We used to use a symlink for mpl-data too. API documents like matplotlib.0.Matplotlib. these figures can be included in the usual way: ... eg: 27.5 Referring to mpl documents In the documentation.noplot -*- 27. you may want to include to a document in the matplotlib src. Once these steps have been taken. use hypen separated. plot:: mpl_examples/pylab_examples/simple_plot. image:: . Relative paths are extremely confusing in the sphinx plot extensions.py :include-source: 27. plot:: pyplots/tex_unicode_demo. insert the following special comment anywhere in the script: # -*.. we refer to the image icons with: . Referring to mpl documents 243 . I use the symlink directory.3 Examples The source of the files in the examples directory are automatically included in the HTML docs.g. An image is generated and included for all examples in the api and pylab_examples directories. descriptive labels for section references. from customizing.6 Internal section references To maximize internal consistency in section labeling and references. To exclude the example from having an image rendered. literalinclude:: .rst./lib/matplotlib/mpl-data/matplotlibrc One exception to this is when referring to the examples dir. Patch is shown as Patch. please use Upper lower for section titles. Documenting matplotlib . _what-is-a-backend is better than: . To use it.patches.text :parts: 2 244 Chapter 27. If a module name is provided. If parts == 0. If parts == 2. eg Possible hangups rather than Possible Hangups 27. Release 1. it is shown as patches.7 Section names. you provide the directive with a number of class or module names (separated by whitespace). etc For everything but top level chapters. 27. inheritance-diagram:: matplotlib. if parts == 1.1 .lines matplotlib. so let’s avoid top level names in references like user or devel or faq unless necesssary. so the label: ..Patch. because for example the FAQ “what is a backend?” could later become part of the users guide...8 Inheritance diagrams Class inheritance diagrams can be generated with the inheritance-diagram directive.Matplotlib. A single option is available: parts controls how many of parts in the path to the class are shown. All of the ancestors of these classes will be included in the inheritance diagram.patches matplotlib. let’s prefer hyphens to separate words. _faq-backend In addition. Example: .0. the class matplotlib. all classes in that module will be used. since underscores are widely used by Sphinx itself. _howto-webapp: and refer to it using the standard reference syntax: See :ref:‘howto-webapp‘ Keep in mind that we may want to reorganize the contents later.. For example. the full path is shown. Matplotlib.FancyArrowPatch patches.Circle patches.Polygon patches.txt$" .emacs configuration: (require ’rst) (setq auto-mode-alist (append ’(("\\.rst-toc-update Update the table of contents at point 27.OffsetFrom patches.Line2D patches.BoxStyle patches. Emacs helpers 245 .YAArrow text.Shadow patches.Artist lines.VertexSelector patches._Style patches.ConnectionPatch artist.rst-toc-insert Insert table of contents at point C-c C-u . Release 1.0.Arc patches.T extWithDash text.W edge patches.rst$" .9 Emacs helpers There is an emacs mode rst.FancyBboxPatch patches.Patch patches. rst-mode) ("\\.FancyArrow patches. and promoting or demoting section headings.ConnectionStyle patches. rst-mode)) auto-mode-alist)) Some helpful functions: C-c TAB .Annotation 27. rst-mode) ("\\._AnnotationBase text.PathPatch patches.RegularPolygon lines.9.Arrow patches.CirclePolygon patches. Here is the basic .ArrowStyle patches.rest$" .1 patches.T ext text.Ellipse text.el which automates many important ReST tasks like building and updateing table-of-contents.Rectangle patches. 0.1 C-c C-l rst-shift-region-left Shift region to the left C-c C-r rst-shift-region-right Shift region to the right 246 Chapter 27. Release 1.Matplotlib. Documenting matplotlib . etc.py and bump the version number When doing a release 28. you need to create a release branch and configure svn-merge to use it. PDF.2 Branching Once all the tests are passing and you are ready to do a release.CHAPTER TWENTYEIGHT DOING A MATPLOLIB RELEASE A guide for developers who are doing a matplotlib release • Edit __init__. eg simple_plot. do any additional testing you want to do.1 Testing • Make sure examples/tests/backend_driver.py and make sure all the unit tests are passing • try some GUI examples.py runs without errors and check the output of the PNG.3 Packaging • Make sure the MANIFEST.. 28.py with GTKAgg.in • run svn-clean from in the mpl svn directory before building the sdist • unpack the sdist and make sure you can build from that directory 247 .py and make sure there are no memory leaks • Run unit/nose_tests. but if he is not available see instructions at Setting up svnmerge.. PS and SVG backends • Run unit/memleak_hawaii3.in us up to date and remove MANIFEST so it will be rebuilt by MANIFEST.matplotlib and test with and without cache on some example script 28. On the bracnh. • remove font cache and tex cache from . and then build binaries and source distributions for testing as release candidates. Michael Droettboom should probably handle this step. TkAgg. gz to /incoming/j/jd/jdh2358/uploads/matplotlib-0. so use this to prepare the OS X releases. and upload them to the sourceforge release area. 28.net Connecting to frs.com/binary-installers-for-python2. Importantly.2.cfg before rebuilding since cruft in the build dir can get carried along..net/project/admin/explorer.sf.gz • go https://sourceforge. but this is currently broken for python2.tar. you can do: > scp somefile. binaries and eggs.sf.98.Matplotlib. sftp> cd uploads sftp> ls sftp> lls matplotlib-0. and then the “File Releases” tab.gz sftp> put matplotlib-0.6 as described at http://www.1 • Use setup.py sdist mpl> cd dist/ dist> sftp jdh2358@frs. For windows and OSX. Doing a matplolib release . You should also turn on or off any platform specific build options you need. you also need to make sure that you delete the build dir after any changes to file:setup. To post to the server. the default backend should be TkAgg.DLL-and-%09mingw-td23971661.tgz jdh2358. Any changes to fix bugs in the release candidate should be fixed in the release branch and merged into the trunk with svn-merge. Pester us if we don’t respond • ftp the source and binaries to the anonymous FTP site: mpl> svn-clean mpl> python setup. unix2dos the rc file • We have a Makefile for the OS X builds in the mpl source dir release/osx.html 28.net/release-candidates and post a message to matplotlibusers and devel requesting testing. build the final sdist.98.5 Uploading • Post the win32 and OS-X binaries for testing and make a request on matplotlib-devel for testing. Click on the “Admin” tab to log in as an admin.cfg to set the default backends.0. • on windows.6–libpngsegfault%
[email protected]. When the release candidate is signed off on.php?group_id=80706 and do a file release.2.2. see Using svnmerge.sourceforge.net:/home/groups/m/ma/matplotlib/htdocs/release-candidate replacing ‘jdh2358’ with your sourceforge login.. • We have a Makefile for the win32 mingw builds in the mpl source dir release/win32 which you can use this to prepare the windows releases.nabble.98.tar.sourceforge.tar. Release 1. Go to the bottom and click “add release” and enter the package name but not the version number in the “Package Name” 248 Chapter 28.gz Uploading matplotlib-0.98.tar.2.4 Release candidate testing: Post the release candidates to http://matplotlib. 0. Announcing 249 . and select which packages from the incoming ftp archive you want to include in this release. matplotlib-users and matplotlib-devel. You will then be taken to a fairly self explanatory page where you can enter the Change notes.1 and click “Create this release”. you will need to select the platform and file type. For each binary. 28. You will then be prompted for the “New release name” at which point you can add the version number.6 Announcing Announce the release on matplotlib-announce. eg somepackage-0. Release 1. Include a summary of highlights from the CHANGELOG and/or post the whole CHANGELOG since the last release. the release notes.1 box.6.Matplotlib. and when you are done you click on the “notify users who are monitoring this package link” 28. Matplotlib.0. Release 1. Doing a matplolib release .1 250 Chapter 28. and contributes to better interactive performance. their parents are automatically invalidated.CHAPTER TWENTYNINE WORKING WITH TRANSFORMATIONS Affine2D BlendedAffine2D T ransformedBbox CompositeAffine2D BboxBase Bbox BboxT ransformT o Path AffineBase Affine2DBase IdentityT ransform T ransformNode T ransform CompositeGenericT ransform BboxT ransform T ransformedPath T ransformW rapper BboxT ransformFrom BlendedGenericT ransform ScaledT ranslation BboxT ransformT oMaxOnly 29. it is recomputed to reflect those changes.1 matplotlib. For example. This invalidation/caching approach prevents unnecessary recomputations of transforms. The next time an invalidated transform is accessed. Transforms are composed into trees of TransformNode objects whose actual value depends on their children. When the contents of children change.transforms matplotlib includes a framework for arbitrary geometric transformations that is used determine the final position of all elements drawn on the canvas. here is a graph of the transform tree used to plot data to the graph: 251 . For any transform: full transform == non-affine part + affine part The backends are not expected to handle non-affine transformations themselves. it is possible to perform just the affine or non-affine part of a transformation on a set of data. we want use the backend renderers to perform affine transformations whenever possible. for speed. 252 Chapter 29. The affine is always assumed to occur after the non-affine.1 The framework can be used for both affine and non-affine transformations. Release 1. Therefore. However. Working with transformations .0.Matplotlib. bounds (property) Returns (x0. bottom.‘SE’ for bottom-left . to let the invalidation system know which transforms can invalidate this transform. Creates a new TransformNode. 29. invalidate() Invalidate this TransformNode and all of its ancestors. The frozen copy will not update when its children change.Matplotlib. and provides read-only access to its data.transforms.deepcopy() might normally be used. frozen() Returns a frozen copy of this transform node. it defaults to the initial Bbox. cy) where cx and cy range from 0 to 1. The canonical representation is as two points.transforms.‘C’ for centered .etc. c: may be either: •a sequence (cx.‘E’ for left .transforms.0.transforms 253 . width.‘S’ for bottom-center . contains(x. container=None) Return a copy of the Bbox. matplotlib. anchored(c. class matplotlib. containsx(x) Returns True if x is between or equal to x0 and x1.1 class matplotlib. Should be called from the constructor of any transforms that depend on other transforms. Convenience properties are provided to get the left. Creates a new TransformNode. Optional argument container is the box within which the Bbox is positioned. right and top edges and width and height. such as bounding boxes.BboxBase Bases: matplotlib. height).TransformNode Bases: object TransformNode is the base class for anything that participates in the transform tree and needs to invalidate its parents or be invalidated. since some transforms depend on bounding boxes to compute their values. set_children(*children) Set the children of the transform. y) Returns True if (x. with no restrictions on their ordering. y0. shifted to position c within a container.1.TransformNode This is the base class of all bounding boxes. Useful for storing a previously known state of a transform where copy. but these are not stored explicity. where 0 is left or bottom and 1 is right or top •a string: . This includes classes that are not really transforms. Should be called any time the transform changes. A mutable bounding box is provided by the Bbox class. Release 1. y) is a coordinate inside the bounding box or on its edge. b) and (c. such as bounding boxes. since some transforms depend on bounding boxes to compute their values. if this Bbox is defined by the points (a. intervaly (property) intervaly is the pair of y coordinates that define the bounding box. extents (property) Returns (x0. height (property) The height of the bounding box. count_contains(vertices) Count the number of vertices contained in the Bbox. y1). 254 Chapter 29. statically transformed by the inverse of the given transform. count_overlaps(bboxes) Count the number of bounding boxes that overlap this one. sh) Return a new Bbox which is this Bbox expanded around its center by the given factors sw and sh. b) and (c. corners() Return an array of points which are the four corners of this rectangle. intervalx (property) intervalx is the pair of x coordinates that define the bounding box. y) is a coordinate inside the bounding box. corners() returns (a. d). fully_containsx(x) Returns True if x is between but not equal to x0 and x1. fully_containsy(y) Returns True if y is between but not equal to y0 and y1. d). vertices is a Nx2 Numpy array. It may be negative if y1 < y0. b).1 containsy(y) Returns True if y is between or equal to y0 and y1. For example. bboxes is a sequence of BboxBase objects expanded(sw.Matplotlib. inverse_transformed(transform) Return a new Bbox object. fully_overlaps(other) Returns True if this bounding box overlaps with the given bounding box other. It is not guaranteed to be sorted from left to right. but not on its edge. This includes classes that are not really transforms. d).0. (c. It is not guaranteed to be sorted from bottom to top. (a. but not on its edge alone. x1. Release 1. y) Returns True if (x. y0. Working with transformations . frozen() TransformNode is the base class for anything that participates in the transform tree and needs to invalidate its parents or be invalidated. fully_contains(x. fig_aspect=1.g. f2. . min (property) min is the bottom-left corner of the bounding box.. For that.) Returns a list of new Bbox objects formed by splitting the original one with vertical lines at fractional positions f1. container=None.. overlaps(other) Returns True if this bounding box overlaps with the given bounding box other.0) Return a copy of the Bbox.. It is not guaranteed to be the top-right corner. but this is not enforced. Release 1. rotated(radians) Return a new bounding box that bounds a rotated version of this bounding box by the given radians.0. The lower left corner of the box remains unchanged. use min. y) coordinates that define the bounding box.transforms 255 . padded(p) Return a new Bbox that is padded on all four sides by the given value. bbox. y) coordinates that define the bounding box. p1 (property) p1 is the second pair of (x. max (property) max is the top-right corner of the bounding box.Matplotlib. bbox. shrunk so that it is as large as it can be while having the desired aspect ratio. of course... box_aspect. shrunk by the factor mx in the x direction and the factor my in the y direction. p0 (property) p0 is the first pair of (x. It is not guaranteed to be the bottom-left corner.1 is_unit() Returns True if the Bbox is the unit bounding box from (0. in the same way as width and height. For that.splitx(f1. my) Return a copy of the Bbox. The new bounding box is still aligned with the axes.g. fractions of a larger box such as a figure—then the physical aspect ratio of that figure is specified with fig_aspect. May be negative. splity(*args) e. f2. not the relative dimensions. shrunk_to_aspect(box_aspect. . .. Normally mx and my will be less than 1.. size (property) The width and height of the bounding box.1. 29. splitx(*args) e. matplotlib. ... shrunk(mx. so that box_aspect can also be given as a ratio of the absolute dimensions.) Returns a list of new Bbox objects formed by splitting the original one with horizontal lines at fractional positions f1. If the box coordinates are relative—that is. use max.. f2. 1). 0) to (1. f2.splitx(f1. width (property) The width of the bounding box. 256 Chapter 29.1 transformed(transform) Return a new Bbox object. use xmin.BboxBase A mutable bounding box.Matplotlib. x0 (property) x0 is the first of the pair of x coordinates that define the bounding box. It may be negative if x1 < x0. class matplotlib. x0 is not guaranteed to be less than x1. points: a 2x2 numpy array of the form [[x0. y1 (property) y1 is the second of the pair of y coordinates that define the bounding box. use ymax.transforms. height) (staticmethod) Create a new Bbox from x0. use xmax. y0 is not guaranteed to be less than y1. consider the static methods unit(). ymin (property) ymin is the bottom edge of the bounding box. y0]. Release 1. ymax (property) ymax is the top edge of the bounding box. If you require that. Working with transformations . xmax (property) xmax is the right edge of the bounding box. y0 (property) y0 is the first of the pair of y coordinates that define the bounding box. width. y1]] If you need to create a Bbox object from another form of data. from_bounds() and from_extents(). x1 (property) x1 is the second of the pair of x coordinates that define the bounding box. static from_extents(*args) (staticmethod) Create a new Bbox from left. statically translated by tx and ty.Bbox(points) Bases: matplotlib. If you require that. [x1. use ymin. static union(bboxes) Return a Bbox that contains all of the given bboxes.0. ty) Return a copy of the Bbox. right and top. y0. static from_bounds(x0. If you require that. width and height may be negative. width and height.transforms. statically transformed by the given transform. bottom. If you require that. y1 is not guaranteed to be greater than y0. translated(tx. xmin (property) xmin is the left edge of the bounding box. y0. x1 is not guaranteed to be greater than x0. matplotlib. as this method is mainly for internal use. updatey=True) Update the bounds of the Bbox based on the passed in data. update_from_data_xy(xy. 1). [x1. y. static unit() (staticmethod) Create a new unit Bbox from (0. • when False.Matplotlib. the bounds will have positive width and height. get_points() Get the points of the bounding box directly as a numpy array of the form: [[x0. use the last value passed to ignore(). After updating. value: •When True.0. •When False. ignore(value) Set whether the existing bounds of the box should be ignored by subsequent calls to update_from_data() or update_from_data_xy(). xy: a numpy array of 2D points 29. updatex=True. [x1. subsequent calls to update_from_data() will ignore the existing bounds of the Bbox. ignore=None. Release 1. include the existing bounds of the Bbox. ignore=None) Update the bounds of the Bbox based on the passed in data. x0 and y0 will be the minimal values. ignore the existing bounds of the Bbox. set_points(points) Set the points of the bounding box directly from a numpy array of the form: [[x0. y0]. x: a numpy array of x-values y: a numpy array of y-values ignore: • when True. After updating. subsequent calls to update_from_data() will include the existing bounds of the Bbox. x0 and y0 will be the minimal values.1. • when None. the bounds will have positive width and height. y0]. 0) to (1. No error checking is performed. update_from_data(x. mutated() return whether the bbox has changed since init mutatedx() return whether the x-limits have changed since init mutatedy() return whether the y-limits have changed since init set(other) Set this bounding box from the “frozen” bounds of another Bbox. y1]].1 The y-axis increases upwards.transforms 257 . y1]]. x0 and y0 will be the minimal values. update the y values update_from_path(path.transforms. the bounds will have positive width and height. updatey=True) Update the bounds of the Bbox based on the passed in data. ignore the existing bounds of the Bbox. include the existing bounds of the Bbox. update the x values updatey: when True. class matplotlib. update the y values class matplotlib.transforms. use the last value passed to ignore(). After updating. • when None.Transform Bases: matplotlib. Release 1. updatex: when True. • when None. Working with transformations . ignore=None. bbox: a child Bbox transform: a 2D Transform get_points() Get the points of the bounding box directly as a numpy array of the form: [[x0. include the existing bounds of the Bbox.1 ignore: • when True.BboxBase A Bbox that is automatically transformed by a given transform.Matplotlib. updatex=True. • when False. New affine transformations should be subclasses of Affine2D. [x1. the bounds of this bbox will update accordingly. update the x values updatey: when True.0. • when False. Subclasses of this class should override the following members (at minimum): •input_dims •output_dims •transform() •is_separable 258 Chapter 29.transforms. ignore the existing bounds of the Bbox. y0]. When either the child bounding box or transform changes.TransformedBbox(bbox. path: a Path instance ignore: • when True. updatex: when True.TransformNode The base class of all TransformNode instances that actually perform a transformation. transform) Bases: matplotlib. y1]]. All non-affine transformations should be subclasses of this class. use the last value passed to ignore().transforms. Path objects. this is generally a no-op. In non-affine transformations. get_affine() Get the affine part of this transform. numpy array). The pts must be a two-column numpy array of x. radians=False.0000000000000001e-05) Performs transformation on a set of angles anchored at specific locations. In affine transformations.inverted(). Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). this is equivalent to transform(values).path. radians indicates whether or not input angles are given in radians (True) or degrees (False. the default).y positions (angle transforms currently only work in 2D). such as adding curves where there were once line segments. 29.transform(x)) transform(values) Performs the transformation on the given array of values. as well as locations very close to pts. The angles must be a column vector (i. Release 1. The transformed angles are returned in an array with the same size as angles.. An update to self does not cause a corresponding update to its inverted copy. inverted() Return the corresponding inverse transformation.transforms 259 . transform(values) is always equivalent to transform_affine(transform_non_affine(values)).0. pushoff is the distance to move away from pts for determining transformed angles (see discussion of method below). pts. This array must have the same number of rows as angles. transform_angles(angles.Matplotlib. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). transform_affine(values) Performs only the affine part of this transformation on the given array of values. The generic version of this method uses a very generic algorithm that transforms pts.e. to find the angle in the transformed system.1.1 •has_inverse •inverted() (if has_inverse() can return True) If the transform needs to do something non-standard with mathplotlib. matplotlib.transform(self. pushoff=1. it should override: •transform_path() Creates a new TransformNode. The return value of this method should be treated as temporary. x === self. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path. The point is given as a sequence of length input_dims. this transform may insert curves into the path that began as line segments. transformed only by the affine part of this transform. In non-affine transformations. so the child transform may only be replaced with another child transform of the same dimensions. path: a Path instance. Note that TransformWrapper instances must have the same input and output dimensions during their entire lifetime. Working with transformations . transform_path(path) Returns a transformed copy of path.Matplotlib. In some cases. path: a Path instance. class matplotlib. transform_path_affine(path) Returns a copy of path.transforms. child: A class:Transform instance. This is useful if a node of the transform tree must be replaced at run time with a transform of a different type. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_point(point) A convenience function that returns the transformed copy of a single point.0.deepcopy() might normally be used. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).TransformWrapper(child) Bases: matplotlib. this is generally equivalent to transform(values). frozen() Returns a frozen copy of this transform node. path: a Path instance. Release 1. This child may later be replaced with set(). transformed only by the non-affine part of this transform. The frozen copy will not update when its children change. 260 Chapter 29. In affine transformations. This class allows that replacement to correctly trigger invalidation. this is always a no-op. Useful for storing a previously known state of a transform where copy.transforms.Transform A helper class that holds a single child transform and acts equivalently to it.1 transform_non_affine(values) Performs only the non-affine part of the transformation. The transformed point is returned as a sequence of length output_dims. use Affine2D. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path. path: a Path instance. this is generally equivalent to transform(values). transformed only by the non-affine part of this transform.1. get_matrix() Get the underlying transformation matrix as a numpy array. In affine transformations.Affine2DBase Bases: matplotlib. Subclasses of this class will generally only need to override a constructor and get_matrix() that generates a custom 3x3 matrix. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).0. matplotlib. In non-affine transformations. transformed only by the affine part of this transform.transforms. The frozen copy will not update when its children 29. frozen() Returns a frozen copy of this transform node.transforms.1 set(child) Replace the current child of this transform with another one. Release 1. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).transforms. transform_non_affine(points) Performs only the non-affine part of the transformation.Transform The base class of all affine transformations of any number of dimensions. The new child must have the same number of input and output dimensions as the current child. class matplotlib. get_affine() Get the affine part of this transform.AffineBase Bases: matplotlib. this is always a no-op. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values class matplotlib.AffineBase The base class of all 2D affine transformations. path: a Path instance.Matplotlib. For a mutable 2D affine transformation.transforms 261 . transform_path_affine(path) Returns a copy of path.transforms. 2D affine transformations are performed using a 3x3 numpy array: a c e b d f 0 0 1 This class provides the read-only interface. f ) (staticmethod) Create a new transformation matrix as a 3x3 numpy array of the form: a c e b d f 0 0 1 to_values() Return the values of the matrix as a sequence (a.d. Useful for storing a previously known state of a transform where copy. Initialize an Affine transform from a 3x3 numpy float array: 262 Chapter 29.e. class matplotlib.b. b.inverted(). In affine transformations. Release 1. x === self.f) transform(points) Performs only the affine part of this transformation on the given array of values.transform(x)) static matrix_from_values(a. this is generally a no-op.transforms.deepcopy() might normally be used. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).Affine2D(matrix=None) Bases: matplotlib. c.c. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). this is generally a no-op. An update to self does not cause a corresponding update to its inverted copy. d.1 change. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).0. inverted() Return the corresponding inverse transformation.Affine2DBase A mutable 2D affine transformation. e. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).Matplotlib. transform_point(point) A convenience function that returns the transformed copy of a single point. transform_affine(points) Performs only the affine part of this transformation on the given array of values. The transformed point is returned as a sequence of length output_dims.transforms. In non-affine transformations. this is equivalent to transform(values). Working with transformations . The return value of this method should be treated as temporary. In affine transformations. this is equivalent to transform(values). The point is given as a sequence of length input_dims.transform(self. In non-affine transformations. theta) Add a rotation (in radians) around the point (x. b. translate() and scale(). rotate_around(x. rotate_deg(). Returns self. 29. y) in place. the same scale is applied in both the x. sy=None) Adds a scale in place.and y-directions. initialize with the identity transform. rotate_deg(degrees) Add a rotation (in degrees) to this transform in place. static from_values(a. so this method can easily be chained with more calls to rotate(). so this method can easily be chained with more calls to rotate().1. rotate_deg(). e. c. scale(sx. y. Unless this transform will be mutated later on. matplotlib. y) in place. translate() and scale(). so this method can easily be chained with more calls to rotate().Matplotlib. clear() Reset the underlying matrix to the identity transform. Returns self. translate() and scale(). rotate_deg(). translate() and scale(). rotate(theta) Add a rotation (in radians) to this transform in place. consider using the faster IdentityTransform class instead. Returns self. Returns self. d.transforms 263 . degrees) Add a rotation (in degrees) around the point (x. y. f ) (staticmethod) Create a new Affine2D instance from the given values: a c e b d f 0 0 1 get_matrix() Get the underlying transformation matrix as a 3x3 numpy array: a c e b d f 0 0 1 static identity() (staticmethod) Return a new Affine2D object that is the identity transform. rotate_deg(). Release 1. rotate_deg_around(x.1 a c e b d f 0 0 1 If matrix is None.0. If sy is None. so this method can easily be chained with more calls to rotate(). translate() and scale(). x === self. An update to self does not cause a corresponding update to its inverted copy. inverted() Return the corresponding inverse transformation.IdentityTransform Bases: matplotlib. An update to self does not cause a corresponding update to its inverted copy. rotate_deg(). this is always a no-op. Useful for storing a previously known state of a transform where copy. rotate_deg().1 Returns self. the identity transform.transform(x)) transform(points) Performs only the non-affine part of the transformation. so this method can easily be chained with more calls to rotate().transforms.inverted(). so this method can easily be chained with more calls to rotate(). The return value of this method should be treated as temporary. In affine transformations. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). frozen() Returns a frozen copy of this transform node. Returns self. The frozen copy will not update when its children change.transform(x)) get_matrix() Get the underlying transformation matrix as a numpy array. The return value of this method should be treated as temporary. in a fast way.transform(self.transform(self. get_affine() Return the corresponding inverse transformation. set_matrix(mtx) Set the underlying transformation matrix from a 3x3 numpy array: a c e b d f 0 0 1 translate(tx. Release 1.deepcopy() might normally be used. ty) Adds a translation in place. set(other) Set this transformation from the frozen copy of another Affine2DBase object.inverted(). 264 Chapter 29. translate() and scale(). Working with transformations . this is generally equivalent to transform(values).0. class matplotlib.Affine2DBase A special class that does on thing.transforms. In non-affine transformations.Matplotlib. x === self. and another transform for the ydirection. this is generally equivalent to transform(values). In affine transformations. which can determine automatically which kind of blended transform to create.1. this is always a no-op. this is always a no-op. transformed only by the non-affine part of this transform. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values class matplotlib. transform_affine(points) Performs only the non-affine part of the transformation. this is generally equivalent to transform(values). transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path.1 Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_affine(path) Returns a copy of path.transforms 265 .Matplotlib.Transform A “blended” transform uses one transform for the x-direction. In non-affine transformations. transform_non_affine(points) Performs only the non-affine part of the transformation. Release 1. 29. transformed only by the non-affine part of this transform. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). transform(values) is always equivalent to transform_affine(transform_non_affine(values)).transforms. transform_path(path) Returns a copy of path. This “generic” version can handle any given child transform in the x. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). matplotlib.BlendedGenericTransform(x_transform.transforms. In non-affine transformations. path: a Path instance. Create a new “blended” transform using x_transform to transform the x-axis and y_transform to transform the y-axis. In affine transformations. transformed only by the non-affine part of this transform. You will generally not call this constructor directly but use the blended_transform_factory() function instead. y_transform) Bases: matplotlib. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).0. path: a Path instance. path: a Path instance.and y-directions. get_affine() Get the affine part of this transform. Both x_transform and y_transform must be 2D affine transforms. The frozen copy will not update when its children change. The return value of this method should be treated as temporary. and another transform for the ydirection.transform(x)) transform(points) Performs the transformation on the given array of values. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).1 frozen() Returns a frozen copy of this transform node. This version is an optimization for the case where both child transforms are of type Affine2DBase. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In affine transformations. this is equivalent to transform(values). this is always a no-op. Useful for storing a previously known state of a transform where copy. 266 Chapter 29. Working with transformations . In non-affine transformations.0. In affine transformations. this is generally equivalent to transform(values).transform(self. An update to self does not cause a corresponding update to its inverted copy. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).BlendedAffine2D(x_transform. inverted() Return the corresponding inverse transformation. x === self. In non-affine transformations. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). Release 1. transform_affine(points) Performs only the affine part of this transformation on the given array of values.Matplotlib.transforms. Create a new “blended” transform using x_transform to transform the x-axis and y_transform to transform the y-axis. class matplotlib. transform_non_affine(points) Performs only the non-affine part of the transformation.Affine2DBase A “blended” transform uses one transform for the x-direction.inverted().transforms. this is generally a no-op.deepcopy() might normally be used. y_transform) Bases: matplotlib. The frozen copy will not update when its children change.transform(x)) transform(points) Performs the transformation on the given array of values. y_transform) Create a new “blended” transform using x_transform to transform the x-axis and y_transform to transform the y-axis. which can determine automatically which kind of blended transform to create.deepcopy() might normally be used. get_affine() Get the affine part of this transform. In non-affine transformations. matplotlib.Matplotlib. You will generally not call this constructor directly but use the composite_transform_factory() function instead.1.CompositeGenericTransform(a. Create a new composite transform that is the result of applying transform a then transform b.transforms 267 . x === self. class matplotlib. this is equivalent to transform(values). Release 1. In affine transformations. A faster version of the blended transform is returned for the case where both child transforms are affine.transforms. Useful for storing a previously known state of a transform where copy. The return value of this method should be treated as temporary. inverted() Return the corresponding inverse transformation. frozen() Returns a frozen copy of this transform node. transform_affine(points) Performs only the affine part of this transformation on the given array of values.1 You will generally not call this constructor directly but use the blended_transform_factory() function instead.Transform A composite transform formed by applying transform a then transform b.transform(self.inverted(). Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). b) Bases: matplotlib.transforms. get_matrix() Get the underlying transformation matrix as a numpy array. which can automatically choose the best kind of composite transform instance to create. matplotlib.0. An update to self does not cause a corresponding update to its inverted copy. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). 29. this is generally a no-op.transforms. This “generic” version can handle any two arbitrary transformations.blended_transform_factory(x_transform. Affine2DBase A composite transform formed by applying transform a then transform b.transforms. this is always a no-op. this transform may insert curves into the path that began as line segments. In affine transformations. Create a new composite transform that is the result of applying transform a then transform b. You will generally not call this constructor directly but use the composite_transform_factory() function instead. b) Create a new composite transform that is the result of applying transform a then transform b. which can automatically choose the best kind of composite transform instance to create. Both a and b must be instances of Affine2DBase. this is generally equivalent to transform(values).transforms. transformed only by the non-affine part of this transform. path: a Path instance. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path.0. transform_path(path) Returns a transformed copy of path. In non-affine transformations. transform_non_affine(points) Performs only the non-affine part of the transformation. path: a Path instance. path: a Path instance. get_matrix() Get the underlying transformation matrix as a numpy array. Release 1. b) Bases: matplotlib.1 Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). In some cases. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). transform_path_affine(path) Returns a copy of path. matplotlib. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). This version is an optimization that handles the case where both a and b are 2D affines. transformed only by the affine part of this transform. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values class matplotlib. or one or the other is the identity transform.Matplotlib. Shortcut versions of the blended transform are provided for the case where both child transforms are affine. Working with transformations .transforms. 268 Chapter 29.composite_transform_factory(a.CompositeAffine2D(a. This cached copy is automatically updated when the non-affine part of the transform changes. Create a new TransformedPath from the given Path and Transform. transform) Bases: matplotlib. scale_trans) Bases: matplotlib.1 Composite transforms may also be created using the ‘+’ operator.transforms. class matplotlib. boxout) Bases: matplotlib.Matplotlib.TransformNode A TransformedPath caches a non-affine transformed copy of the Path.transforms.Affine2DBase BboxTransformFrom linearly transforms points from a given Bbox to the unit bounding box. e.transforms. get_transformed_path_and_affine() Return a copy of the child path.transforms.BboxTransform(boxin. class matplotlib.transforms.transforms. get_matrix() Get the underlying transformation matrix as a numpy array. class matplotlib. get_matrix() Get the underlying transformation matrix as a numpy array.ScaledTranslation(xt. get_matrix() Get the underlying transformation matrix as a numpy array. Release 1.Affine2DBase BboxTransformTo is a transformation that linearly transforms points from the unit bounding box to a given Bbox.0.transforms. class matplotlib. Create a new BboxTransformTo that linearly transforms points from the unit bounding box to boxout.BboxTransformTo(boxout) Bases: matplotlib.BboxTransformFrom(boxin) Bases: matplotlib. Create a new BboxTransform that linearly transforms points from boxin to boxout.TransformedPath(path.transforms.1.g. matplotlib.Affine2DBase BboxTransform linearly transforms points from one Bbox to another Bbox. after xt and yt have been transformad by the given transform scale_trans.Affine2DBase A transformation that translates by xt and yt. 29. get_fully_transformed_path() Return a fully-transformed copy of the child path.transforms. along with the affine part of the path necessary to complete the transformation.: c = a + b class matplotlib. get_matrix() Get the underlying transformation matrix as a numpy array. yt.transforms. with the non-affine part of the transform already applied.transforms 269 . If ‘increasing’ is True and vmin > vmax. If they are too close. vmax. increasing=True) Ensure the endpoints of a range are finite and not too close together. each will be moved by the ‘expander’. return . regardless of whether they are too close.expander. 270 Chapter 29.Matplotlib.transforms. Unlike get_transformed_path_and_affine().nonsingular(vmin. Release 1.0.001. expander.0000000000000001e-15. Working with transformations . If either is inf or -inf or nan. no interpolation will be performed. tiny=1.1 get_transformed_points_and_affine() Return a copy of the child path. they will be swapped. along with the affine part of the path necessary to complete the transformation. with the non-affine part of the transform already applied. expander=0. matplotlib. “too close” means the interval is smaller than ‘tiny’ times the maximum absolute value. • Locators (major and minor) that determine where to place ticks in the plot. are called “projections”. the range setting here is only used when automatically setting the range of the plot. 271 . and optionally. the scale of a plot can be set with set_xscale() and set_xscale(). • Formatters (major and minor) that specify how the tick labels should be drawn. y. The necessary code for scales and projections can be included anywhere: directly within a plot script. Unlike limit_range_for_scale(). Projections can be chosen using the projection keyword argument to the plot() or subplot() functions. From the user’s perspective. which is always enforced.ScaleBase. A log scale. that handle data in two or more dimensions at a time. There is an important distinction between two kinds of transformations. • An inverse of that transformation. how to adjust the limits of the plot to some “good” values. 30. Separable transformations.CHAPTER THIRTY ADDING NEW SCALES AND PROJECTIONS TO MATPLOTLIB Matplotlib supports the addition of custom procedures that transform the data before it is displayed. that includes the following elements: • A transformation from data coordinates into display coordinates. working on a single dimension. • A function to limit the range of the axis to acceptable values (limit_range_for_scale()).: plot(x. to convert mouse positions from screen space back into data space. e. or in the matplotlib source tree itself.scale. and non-separable transformations. would prevent the range from including values less than or equal to zero. projection="custom") This document is intended for developers and advanced users who need to create new scales and projections for matplotlib.1 Creating a new scale Adding a new scale consists of defining a subclass of matplotlib. for instance.g. in third-party code. for example. are called “scales”. This is used. LinearScale(axis.py. • Defining custom locators and formatters for the projection. it may be more convenient to display the grid in degrees. A full-fledged and heavily annotated example is in examples/api/custom_projection_example. it must be registered with matplotlib so that the user can select it.scale that may be used as starting points. This is used. Adding new scales and projections to matplotlib . since the defaults for a rectilinear axes may not be appropriate.axes.Axes. but there is an example of this for polar plots in matplotlib.3. **kwargs) Bases: matplotlib. • An inverse of that transformation.Matplotlib. and matplotlib has a facility to help with doing so.1 matplotlib. For example. that will be used to draw the background of the plot and for clipping any data elements.py. an elliptical axes.polar may also be of interest.0. Release 1. 30. Custom projections will often need to place these elements in special locations. ticks and ticklabels. There are also some classes in matplotlib. • Setting up default values (overriding cla()). 30.polar.scale.3 API documentation 30.scale.1 Once the class is defined.ScaleBase The default linear scale. This is left as an “advanced” feature left to the reader.2 Creating a new projection Adding a new projection consists of defining a subclass of matplotlib. get_transform() The transform for linear scaling is just the IdentityTransform. in a geographic projection. it must be registered with matplotlib so that the user can select it. even if the data is in radians. 272 Chapter 30. set_default_locators_and_formatters(axis) Set the locators and formatters to reasonable defaults for linear scaling. Once the class is defined.projections.scale class matplotlib. for example.projections. • Set up interactive panning and zooming. The polar plot functionality in matplotlib. • Any additional methods for additional convenience or features. to convert mouse positions from screen space back into data space. A full-fledged and heavily annotated example is in examples/api/custom_scale_example. • Defining the shape of the axes. for example. that includes the following elements: • A transformation from data coordinates into display coordinates. • Transformations for the gridlines. 2. class matplotlib. Any subclasses will want to override: •name •get_transform() And optionally: • set_default_locators_and_formatters() • limit_range_for_scale() get_transform() Return the Transform object associated with this scale. 30. 1.0. **kwargs) Bases: matplotlib. Care is taken so non-positive values are not plotted.scale. Scales are separable transformations. Should be a sequence of integers. 6. Release 1. 9] will place 10 logarithmically spaced minor ticks between each major tick. working on a single dimension. API documentation 273 . this scale provides different transforms depending on the base of the logarithm: •base 10 (Log10Transform) •base 2 (Log2Transform) •base e (NaturalLogTransform) •arbitrary base (LogTransform) basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. get_transform() Return a Transform instance appropriate for the given logarithm base.Matplotlib. For example.3.ScaleBase A standard logarithmic scale. in a log10 scale: [0.ScaleBase Bases: object The base class for all scales.scale. vmax. 7. 4. For computational efficiency (to push as much as possible to Numpy C code in the common cases). 8.LogScale(axis. 5. limit_range_for_scale(vmin.1 class matplotlib. 3.scale. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick. set_default_locators_and_formatters(axis) Set the locators and formatters to specialized versions for log scaling. minpos) Limit the domain to positive values. subsx/subsy: Where to place the subticks between each major tick. 2.projections. 274 Chapter 30. This is used by log scales to determine a minimum value.scale.SymmetricalLogScale(axis. minpos should be the minimum positive value in the data. 5. matplotlib. 7. 4. get_projection_class(name) Get a projection class from its name.1 limit_range_for_scale(vmin.ScaleBase The symmetrical logarithmic scale is logarithmic in both the positive and negative directions from the origin. basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. 9] will place 10 logarithmically spaced minor ticks between each major tick. **kwargs) Bases: matplotlib.scale. in a log10 scale: [0. minpos) Returns the range vmin. vmax. matplotlib. The parameter linthresh allows the user to specify the size of this range (-linthresh.projections class matplotlib. possibly limited to the domain supported by this scale. ACCEPTS: [ linear | log | symlog ] 30.get_scale_docs() Helper function for generating docstrings related to scales. scale_class must be a subclass of ScaleBase.register_scale(scale_class) Register a new kind of scale. 3. set_default_locators_and_formatters(axis) Set the locators and formatters to specialized versions for symmetrical log scaling. there is a need to have a range around zero that is linear.3. axis. get_transform() Return a SymmetricalLogTransform instance.scale. **kwargs) Return a scale class by name. set_default_locators_and_formatters(axis) Set the Locator and Formatter objects on the given axis to match this scale.scale.0. Release 1.scale_factory(scale. 1. 8. Adding new scales and projections to matplotlib . Since the values close to zero tend toward infinity. vmax. For example. linthresh). matplotlib. class matplotlib.Matplotlib. x) within which the plot is linear (to avoid having the plot go to infinity around zero).ProjectionRegistry Bases: object Manages the set of projections available to the system.scale. Should be a sequence of integers. 6.2 matplotlib. matplotlib.projections. where the input dimensions are theta. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). projection is a projection name. mapping Cartesian coordinate space x and y back to theta and r.Affine2DBase 30.get_projection_names() Get a list of acceptable projection names.0. API documentation 275 . r. inverted() Return the corresponding inverse transformation.PolarAffine(scale_transform. Any other kwargs are passed along to the specific projection constructor being used.Transform The inverse of the polar transform. matplotlib.transform(x)) transform(xy) Performs the transformation on the given array of values.projections. x === self. rect. An update to self does not cause a corresponding update to its inverted copy. figure is a figure to add the axes to.projections.transforms. class InvertedPolarTransform(axis=None) Bases: matplotlib. class PolarAxes. limits) Bases: matplotlib.get_projection_class(projection=None) Get a projection class from its name. rect is a Bbox object specifying the location of the axes within the figure.3. **kwargs) Get a new projection instance.polar.transform(self.Matplotlib.1 get_projection_names() Get a list of the names of all projections currently registered. The return value of this method should be treated as temporary.inverted().PolarAxes(*args. matplotlib. figure. **kwargs) Bases: matplotlib.projections.projections.Axes A polar graph projection.axes. If projection is None. matplotlib. Release 1.transforms.projection_factory(projection. Theta starts pointing east and goes anti-clockwise. a standard rectilinear projection is returned.polar class matplotlib. register(*projections) Register a new set of projection(s). 2pi).inverted(). get_matrix() Get the underlying transformation matrix as a numpy array. Scales the output so that maximum radius rests on the edge of the axes circle. In affine transformations.transform(x)) transform(tr) Performs only the non-affine part of the transformation. path: a Path instance. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). transformed only by the non-affine part of this transform. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(va transform_path_non_affine(path) Returns a copy of path. limits is the view limit of the data. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). transform_non_affine(tr) Performs only the non-affine part of the transformation. but does not perform the ultimate affine transformation into the correct position. inverted() Return the corresponding inverse transformation.transform(self. In non-affine transformations. The return value of this method should be treated as temporary.Matplotlib. x === self. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(va 276 Chapter 30. An update to self does not cause a corresponding update to its inverted copy. The theta range is always fixed to (0.Transform The base polar transform.1 The affine part of the polar projection. The only part of its bounds that is used is ymax (for the radius maximum).transforms. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). this is generally equivalent to transform(values). Adding new scales and projections to matplotlib . transform_path(path) Returns a copy of path. this is always a no-op. This handles projection theta and r into Cartesian coordinate space x and y. Release 1. path: a Path instance.PolarTransform(axis=None) Bases: matplotlib. In non-affine transformations. transformed only by the non-affine part of this transform. this is always a no-op.0. In affine transformations. this is generally equivalent to transform(values). class PolarAxes. r) Return a format string formatting the coordinate using Unicode characters. it delegates to the base Locator (which may be different depending on the scale of the r-axis.set_rgrids(radii.Matplotlib.format_coord(theta. labels. angle=None. is a len(radii) list of strings of the labels to use at each radius. Release 1.ThetaFormatter Bases: matplotlib. kwargs are optional text properties for the labels: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name Description unknown float (0.0 transparent through 1. where line is Line2D instances and the label is Text instances. PolarAxes.RadialLocator(base) Bases: matplotlib.transforms.get_data_ratio() Return the aspect ratio of the data itself.Formatter Used to format the theta tick labels. The labels will appear at radial distances radii at the given angle in degrees.Locator Used to locate radius ticks.3. API documentation 277 . rpad is a fraction of the max of radii which will pad each of the radial labels in the radial direction. this should always be 1. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] 30. fmt=None. PolarAxes. Return value is a list of tuples (line. labels=None. For all other tasks.0 PolarAxes. **kwargs) Set the radial locations and labels of the r grids. rpad=None.can_zoom() Return True if this axes support the zoom box PolarAxes. Converts the native unit of radians into degrees and adds a degree symbol.1 class PolarAxes.ticker. the built-in formatter will be used. label).Bbox instance [True | False] [ (Path. if not None.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. Ensures that all ticks are strictly positive.0. class PolarAxes. If labels is None.ticker. For a polar plot. Matplotlib.font_manager. Adding new scales and projections to matplotlib .y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. depending on the scale: ‘linear’ ‘log’ basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid.0. **kwargs) call signature: set_yscale(value) Set the scaling of the y-axis: ‘linear’ | ‘log’ | ‘symlog’ ACCEPTS: [’linear’ | ‘log’ | ‘symlog’] Different kwargs are accepted.1 Table 30. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: sequence of floats PolarAxes. or clipped to a very small positive number 278 Chapter 30. Release 1.set_rscale(value.Figure instance a matplotlib.figure.1 – continued from figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder a matplotlib. minor=False) Set the y ticks with list of ticks ACCEPTS: sequence of floats Keyword arguments: minor: [ False | True ] Sets the minor ticks if True PolarAxes. 6. 5. 6. subsx/subsy: Where to place the subticks between each major tick. is a len(angles) list of strings of the labels to use at each angle. 8.set_rticks(ticks. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x.0. 9] will place 10 logarithmically spaced minor ticks between each major tick. 4. angles is in degrees. Eg.0 transparent through 1.95 is inside the axes. For example.3.1 subsx/subsy: Where to place the subticks between each major tick.set_thetagrids(angles. **kwargs) Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). Return value is a list of tuples (line.transforms. 7. 7. in a log10 scale: [0. API documentation 279 .Matplotlib. PolarAxes. 1. the labels will be fmt % angle frac is the fraction of the polar axes radius at which to place the label (1 is the edge). in a log10 scale: [0. 2. label). 2. x) within which the plot is linear (to avoid having the plot go to infinity around zero).0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. Should be a sequence of integers.Bbox instance [True | False] [ (Path. frac=None. If labels is None.05 is outside the axes and 0. kwargs are optional text properties for the labels: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color Description unknown float (0. 5. Transform) | Patch | None ] any matplotlib color 30. 8. where line is Line2D instances and the label is Text instances. fmt=None. 3. 1. Release 1. labels. Should be a sequence of integers. if not None. 1. 3. 9] will place 10 logarithmically spaced minor ticks between each major tick. For example. 4. labels=None. FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.2 – continued from contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.1 Table 30.0.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. Adding new scales and projections to matplotlib . Release 1.font_manager.figure.Matplotlib.Figure instance a matplotlib. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: sequence of floats 280 Chapter 30. gtk Author Eric Eric Eric Manuel ? ? ? ? John John ? Eric ? ? John ? Michael Darren John Michael ? John Darren Charlie ? Charlie ? Darren John John John ? ? ? Status Reviewer has author Perry ? Darren has author ? has author ? no author Erik Tollerud ? no author ? no author Darren no author ? has author ? has author Darren no author ? has author ? no author ? no author ? has author ? no author ? accepted John accepted John submitted ? no author Darren submitted Eric submitted ? no author Darren no author ? has author ? submitted ? submitted ? submitted ? no author ? no author ? no author ? Continued on next page 281 . The “unit” doesn’t have to be a full chapter (though in some cases it will be). and who reviews them.annotations fonts et al pyplot tut configuration win32 install os x install linux install artist api event handling navigation interactive usage widgets ui .CHAPTER THIRTYONE DOCS OUTLINE Proposed chapters for the docs.usetex text . it may be a chapter or a section in a chapter.mathtext text . who has responsibility for them. User’s guide unit plotting 2-D arrays colormapping quiver plots histograms bar / errorbar x-y plots time series plots date plots working with data custom ticking masked data patches legends animation collections text . Matplotlib. we can figure out how best to organize the API Reference and continue from there.ps Darren has author ? backend . much less fleshed out Developer’s guide unit the renderer the canvas the artist transforms documenting mpl coding guide and_much_more Author John John John Michael Darren John ? Status has author has author has author submitted submitted complete ? Reviewer Michael ? ? ? John John. Module backend_agg backend_cairo backend_cocoa backend_emf backend_fltkagg backend_gdk backend_gtk backend_gtkagg backend_gtkcairo backend_mixed backend_pdf backend_ps backend_qt backend_qtagg backend_qt4 backend_qt4agg backend_svg backend_template backend_tkagg backend_wx Author Status needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion needs conversion Continued on next page Chapter 31. Release 1. Once docstring conversion is complete and all the modules are available in the docs. Mike? Eric ? We also have some work to do converting docstrings to ReST for the API Reference. Once it is converted.1 Table 31.0. Docs outline Darren Darren Darren Darren Darren 282 . Eric.qt Darren has author ? backend .svg ? no author ? backend .tk ? no author ? ui . please include the module in the API documentation and update the status in the table to “converted”.1 – continued from previous page ui .wx ? no author ? ui .pdf Jouni ? no author ? backend .cairo ? no author ? Here is the ouline for the dev guide. Please be sure to follow the few guidelines described in Formatting.agg ? no author ? backend . 0.1 Table 31. Release 1.2 – continued from previous page backend_wxagg needs conversion backends/tkagg needs conversion config/checkdep Darren needs conversion config/cutils Darren needs conversion config/mplconfig Darren needs conversion config/mpltraits Darren needs conversion config/rcparams Darren needs conversion config/rcsetup Darren needs conversion config/tconfig Darren needs conversion config/verbose Darren needs conversion projections/__init__ Mike converted projections/geo Mike converted (not included–experimental) projections/polar Mike converted afm converted artist converted axes converted axis converted backend_bases converted cbook converted cm converted collections converted colorbar converted colors converted contour needs conversion dates Darren needs conversion dviread Darren needs conversion figure Darren needs conversion finance Darren needs conversion font_manager Mike converted fontconfig_pattern Mike converted image needs conversion legend needs conversion lines Mike & ??? converted mathtext Mike converted mlab John/Mike converted mpl N/A patches Mike converted path Mike converted pylab N/A pyplot converted quiver needs conversion rcsetup needs conversion scale Mike converted table needs conversion texmanager Darren needs conversion text Mike converted Continued on next page 283 .Matplotlib. If mathtext. Docs outline . The backend chapters should cover backend specific configuration (eg PS only options). The reviewer should read your chapter. The main thing to wrap this up is getting the mathtext module ported over to rest and included in the API so the links from the user’s guide tutorial work. Admittedly.py were to be documented.. if you have an author pester the author for a submission every so often.. that would be useful to people just doing plots). You do not need to be an expert in the subject you are editing – you should know something about it and be willing to read. etc. but that may also be overkill..0. Please feel free to add units.1. I would put it in the developer’s docs.1 mathtext user’s guide– reviewed by JDH This looks good (see Writing mathematical expressions) – there are a few minor things to close the book on this chapter: 1.e. Maybe I should just take the link in the user’s guide out.2 – continued from previous page John converted Mike converted needs conversion needs conversion needs conversion And we might want to do a similar table for the FAQ. config. installation.1 ticker transforms type1font units widgets Table 31.1 Reviewer notes If you want to make notes for the authorwhen you have reviewed a submission.Matplotlib. and then pester them! Your only two responsibilities are getting your author to produce and checking their work.. This section might also benefit from a little more detail on the customizations that are possible (eg an example fleshing out the rc options a little bit). Once you have signed up to be an editor. The more the better. You are free to lift and convert as much material from the web site or the existing latex user’s guide as you see fit. If you agree to author a unit... Release 1. • There’s nothing in the mathtext module that I really consider a “public” API (i. test. what features are missing. such as version. etc. so don’t be shy. If you don’t have an author. they should be removed. remove the question mark by your name (or add your name if there is no candidate). As the author cleans them up or addresses them. etc. give feedback and pester! 31. you can put them here. It is probably easiest to be an editor. you can change the status to “submitted” and try to find a reviewer if you don’t have one. Once you have completed draft and checked it in.. but it might be helpful to a newbie. The UI chapters should give an example or two of using mpl with your GUI and any relevant info. this is pretty clear from readin ghte rc file. 284 Chapter 31. find one. volunteer to review or author a chapter.MGD 2. . test it for correctness (eg try your examples) and change the status to “complete” when done. 31.. and change the status to “has author”. 0. .MGD 3. The others only apply when mathtext. It’s pretty extensive. Reviewer notes 285 .1 • The only rcParam that is currently useful is mathtext. It’s really hard to get a good set of math fonts working that way. though it might be useful in a bind when someone has to use a specific wacky font for mathtext and only needs basics. There is still a TODO in the file to include a complete list of symbols • Done. which is documented here.MGD 31. Release 1.Matplotlib. like sub/superscripts. . which I’d like to declare “unsupported”..fontset..fontset == ‘custom’.1. thanks to STIX. 1 286 Chapter 31. Release 1.0.Matplotlib. Docs outline . Part IV The Matplotlib API 287 . . 32. it is a dictionary of kwargs to be passed to the errorbar function. A new auto kwarg is available to control this behavior.set_xlim().locator_params() allows one to adjust axes locator parameters such as nbins.dataLim.Axes. tick location.x • The default behavior of matplotlib. matplotlib.Axes.ScalarFormatter that is used by default with linear axes. • The matplotlib. and applies it.Axes. and tick label formatting.axes.Axes. and bottom and top instead of ymin and ymax.Axes. – matplotlib.Axes. has been changed: when view limits are set explicitly with one of these methods. visibility.margins() sets margins used to autoscale matplotlib.ticker. this list may help describe what changes may be necessary in your code. and their corresponding pyplot functions.tick_params() controls direction.axes.collections.bar() method accepts a error_kw kwarg.axes.Axes. size.EllipseCollection’ has been changed in two ways: 289 .axis(). • The :class:’~matplotlib. autoscaling is turned off for the matching axis.CHAPTER THIRTYTWO API CHANGES This chapter is a log of changes to matplotlib that affect the outward-facing API. • The matplotlib. – matplotlib.Axes.axes. If updating matplotlib breaks your scripts.Axes.autoscale() turns autoscaling on or off.axes. and the general appearance of ticks and tick labels: – matplotlib.hist() color kwarg now accepts a sequence of color specs to match a sequence of datasets. the – matplotlib.viewLim based on the matplotlib. The old names may still be used.axes. – matplotlib.Axes.axes.1 Changes beyond 0.99.Axes.axes.axes.Axes. however. and matplotlib.ticklabel_format() is a convenience method for controlling the matplotlib. and color of ticks and their labels.axes.axes. • There are five new Axes methods with corresponding pyplot functions to facilitate autoscaling.set_ylim().axes. The limit kwargs have been renamed to left and right instead of xmin and xmax. Ellipse‘ scaling. and to better match their names.color_cycle.Figure. offsets. API Changes . offsetTrans. offsets. gc. im.Axes. linewidths. coordinates. antialiaseds. antialiased.traits packages. showedges) # is now draw_quad_mesh(self. gc. even on collections and images. offsetTrans.figure. all clipping rectangles and paths are now passed in using GraphicsContext objects. clippath_trans. facecolors. ‘xy’. previously they specified the halfheight and half-width. antialiaseds. antialiased.Matplotlib. master_transform. bbox. meshWidth.backend_pdf. • The new rc parameter savefig. meshWidth. meshHeight. that scales the ellipse with the data units. – The height and width kwargs have been changed to specify the height and width. edgecolors. y. paths. • There is a new rc parameter axes. meshHeight.PdfPages for more information. offsets. • Removed configobj and enthought. offsetTrans. Release 1.0. matplotlib. clippath. • You can now print several figures to one pdf file and modify the document information dictionary of a pdf file. and the color cycle is now independent of the rc parameter lines. master_transform. See the docstrings of the class matplotlib. master_transform. clippath_trans=None) # is now draw_image(self. offsetTrans. which are only required by the experimental traited config and are somewhat out of date. master_transform. clippath=None.patches. • In an effort to simplify the backend API. offsets.color. cliprect. facecolors. install them independently. urls) # is now draw_path_collection(self. y. urls) draw_quad_mesh(self. linewidths. linestyles. linestyles.extension sets the filename extension that is used by matplotlib. Therefore: draw_path_collection(self.savefig() if its fname argument lacks an extension.set_default_color_cycle() is deprecated. facecolors. This matches the :class:’~matplotlib. showedges) draw_image(self. im) • There are four new Axes methods with corresponding pyplot functions that deal with unstructured 290 Chapter 32. clippath. all_transforms. If needed. again for consistency with Ellipse. facecolors. all_transforms. x. cliprect. edgecolors.1 – There is a new units option.backends. clippath_trans. coordinates. gc. x. paths. tricontour() draws contour lines on a triangular grid. The default is still to mask out non-positive values.99 291 .fignum_exists() and matplotlib.axes.axes. they merely expose information that had been hidden in matplotlib.2 Changes in 0. but the kwargs accept ‘clip’.Axes methods that set log scale parameters. Colormaps can be made the default and applied to the current image using matplotlib. these artists are Line2D instances.axes.Axes.savetxt for text files.triplot() draws a triangular grid as lines and/or markers. 32. • Polar plots no longer accept a resolution kwarg.pyplot. maxlags=10 and normed=True since these are the best defaults 32.3 Changes for 0. These are available in matplotlib.Axes. For normal (rectilinear) axes.image. Release 1. csd(). • Remove support for pyExcelerator in exceltools – use xlwt instead • Changed the defaults of acorr and xcorr to use usevlines=True.mlab.Axes. • Added new matplotlib.g. Instead.load for binary numpy arrays. This is unlikely to be a user-visible change – if interpolation of data is required. • changed use_mrecords default to False in mlab. nonposy to matplotlib. • Added new matplotlib. Changes in 0.pyplot interface.98.2. or you can use numpy.x • psd().0.get_cmap().pyplot. use the new “spines” attribute.save and np. Spines is a dictionary where the keys are the names of the spines (e. ‘left’. • Added new keyword parameters nonposx.Matplotlib. each Path must specify its own number of interpolation steps. these artists may be Patch instances.set_cmap().axes.cm.Axes. and cohere() will now automatically wrap negative frequency components to the beginning of the returned arrays. or np.99 • pylab no longer provides a load and save function.tricontourf() draws filled contours on a triangular grid.1 triangular grids: – matplotlib. which causes non-positive values to be replaced with a very small positive value. – matplotlib. • User-generated colormaps can now be added to the set recognized by matplotlib.loadtxt and numpy. that should be done before passing it to matplotlib.tripcolor() draws a pseudocolor plot on a triangular grid.imsave() and exposed it to the matplotlib.get_fignums(). – matplotlib. For other axes (such as polar axes). Instead.’right’ and so on) and the values are the artists that draw the spines. This is much more sensible behavior and makes them consistent with specgram().axes. – matplotlib.csv2rec since this is partially broken • Axes instances no longer have a “frame” attribute._pylab_helpers. • Deprecated numerix package.pyplot. 32. The previous behavior was more of an oversight than a design decision. 1 • Following keyword parameters for matplotlib.Axes methods and matplotlib.Axes.set_xlim().Collection.mlab.Figure.set_offsets() added to Collection base class. • Methods matplotlib.get_fullname() and matplotlib.clabel() function) so that they all have a form like . • Deprecated (raise NotImplementedError) all the mlab2 functions from matplotlib. matplotlib.cl.mlab out of concern that some of them were not clean room implementations. matplotlib. optionally scale the densities by the sampling frequency.ContourLabeler attributes (matplotlib. Deprecated pad labelsep handlelen handlestextsep axespad New borderpad labelspacing handlelength handletextpad borderaxespad • Removed the configobj and experimental traits rc support • Modified matplotlib.Axes.pyplot.patch.axes.axes.mlab.Matplotlib. fancybox and columnspacing are added as keyword parameters. • Font lookup now uses a nearest-neighbor approach rather than an exact match. Some fonts may be different in plots. Release 1.pyplot functions were updated as well.collections.EllipseCollection added. and matplotlib.axes. The corresponding matplotlib.cohere(). matplotlib.frame. • Added angles kwarg to matplotlib.figure.Figure. Also. • Changed precision kwarg in matplotlib. The new parameters are given as a fraction of the font-size. default is 0.contour.collections.figurePatch renamed matplotlib.get_frame().mlab.axes.psd().AFM.Axes.mlab.get_offsets() and matplotlib. and the string value ‘present’ is used for sparse arrays only to show filled locations. • matplotlib. • matplotlib.axes.Axes.Axes.axesFrame renamed matplotlib.labelAttribute.pyplot. scatteryoffsets.axes.axes.set_ylim() now return a copy of the viewlim array to avoid modify-in-place surprises. .specgram() to scale one-sided densities by a factor of 2. • matplotlib.afm. .collections. which gives true values of densities that can be integrated by the returned frequency values. matplotlib.Collection. but returns a guess based on the required FontName attribute.axes. The three attributes that are most likely to be used by end users.cl_cvalues 292 Chapter 32.afm. Also.Label are now deprecated and new set of parameters are introduced.patch.AFM.get_familyname() no longer raise an exception if the AFM file does not specify these optional attributes.axesPatch renamed matplotlib.label.axes.spy(). • matplotlib.csd(). which returns matplotlib. API Changes . matplotlib. • Changes in the matplotlib.Axes. matplotlib.cl_xy and .Axes. is deprecated.figure.patch.Axes.pyplot.0. but should be closer to what was requested. This also gives better MATLAB compatibility.quiver() for more flexible specification of the arrow angles. Any users of matplotlib.CallbackRegistry rather than custom callback handling.imread() now no longer always returns RGBA data—if the image is luminance or RGB.0.cm.1 293 . It makes something like a pcolor() of a 2-D histogram. bins are specified by the left edges only. symmetric. it will return a MxN or MxNx3 array if possible.ScalarMappable.numerical_methods because they were unrelated to the initial purpose of mlab or cbook and appeared more coherent elsewhere.hist() now uses future Numpy 1.4 Changes for 0.axes. Changes for 0. so matplotlib. The axes method matplotlib.91.toolkits) 32.Axes. • New axes method and pyplot function. reversed() or izip() compatibility functions.4.set_color_cycle(). • Moved several functions in matplotlib. the last value gives the upper-right edge now.1 Notes about the transforms refactoring A major new feature of the 0.axes3d support and replaced it with a non-implemented error pointing to 0.cm.Matplotlib. 32. but uses hexagonal bins.axes.0. enumerate().mlab and matplotlib.5 Changes for 0. • Toolkits must now be imported from mpl_toolkits (not matplotlib. This also means that the last bin doesn’t contain upper outliers any more by default.x 32.add_observer() of the ScalarMappable should use the matplotlib.0. • New axes function and Axes method provide control over the color cycle: matplotlib.Axes. Release 1. in matplotlib.ScalarMappable.3 semantics for histograms.1 have been maintained for the moment (in addition to their renamed versions).98.cbook will no longer provide set.ticker. • In Numpy 1. plot and • matplotlib now requires Python 2.cbook into a separate module matplotlib. is an alternative to scatter() for large datasets.axes. 32.98. Also uint8 is no longer always forced to float. • New kwarg. which was implicitly set to +infinity in Numpy 1.5.ScalarMappable callback infrastructure to use matplotlib.cm.1 • Removed broken matplotlib. Providing binedges.set_default_color_cycle() matplotlib.callbacks CallbackRegistry instead.cbook.98 series is a more flexible and extensible transformation infrastructure. written in Python/Numpy rather than a custom C extension. • Rewrote the matplotlib.0 • matplotlib.4. hexbin().MaxNLocator allows one require an axis to be centered around zero.98.image. but they are deprecated and will eventually be removed. axes. This means that if you hold on to a reference to them.0.axis. The following lists many of the simple changes necessary to update code from the old transformation framework to the new one.1 The primary goal of this refactoring was to make it easier to extend matplotlib to support new kinds of projections.g. not in the locator instances as well. 294 Chapter 32. which in turn looks up its limits from the Axes.Matplotlib.Locator. See matplotlib. In particular. (e. This means locators must get their limits from their matplotlib. For efficiency.transforms for a description of the design of the new transformation framework. The functionality of Pbox has been merged with Bbox.Axis.create_dummy_axis() to do so. their contents may change. Release 1. Call matplotlib. Its methods now all return copies rather than modifying in place. API Changes . If a locator is used temporarily and not assigned to an Axis or Axes. whereas methods that alter an object in place are named with a verb in the present tense. If you want to store a snapshot of their current values. many of these functions return views into Numpy arrays.ticker.Axes instance. and the possible user-visible changes it allows are yet to come. This is mostly an internal improvement.contour). in matplotlib. use the Numpy array method copy(). methods that return a copy are named with a verb in the past tense. The view intervals are now stored only in one place – in the matplotlib. a dummy axis must be created to store its bounds. xmin 1 Bbox.width Bbox.intervaly().height Bbox.get_bounds() transforms. y0) to (x1.intervalx().IdentityTransform tity_transform() blend_xy_sep_transform(xtrans.ymin 1 Bbox.transform(points) form.Bbox. h) [transforms.Bbox.Bbox. boxout) or BboxTransformFrom(boxin) or boxout) BboxTransformTo(boxout) TransTransform.contains_open(v) Interval. v) val.height() transforms.Bbox. y1) and there is no defined order to these points.] lbwh_to_bbox(l.count_overlaps(bboxes) bbox_all(bboxes) Bbox. y0. Affine2D().set_bounds() [Bbox.y0 or transforms.intervalx Bbox. ytrans) ytrans) scale_transform(xs.union(bboxes) [transforms.contains(v) interval_contains(tuple.Bbox. v) idenmatplotlib. Bbox. h) staticmethod.x1 or transforms.Bbox.0 295 . Release 1. blended_transform_factory(xtrans.Matplotlib. 1 32.get_bounds() transforms.x0 or transforms.] Bbox.Bbox.intervaly(). ys]) ys) get_bbox_transform(boxin.Bbox.y1 or transforms.xmax() transforms. x0 is not necessarily the left edge of the box. w.transforms Old method New method Bbox.ymax() transforms.from_bounds() is a w.1 matplotlib.transform(points) form. b.Bbox.get_bounds() transforms.inverse_xy_tup(points) The Bbox is bound by the points (x0.intervalx().xmin() transforms.0. use the read-only property xmin.intervaly Bbox.scale(xs[.Bbox.width() transforms.seq_xy_tup(points) TransTransform.98.Bbox. that is.intervalx is now a property.] Bbox. BboxTransform(boxin.union() is a staticmethod.intervaly is now a property.Bbox.from_bounds(x0. To get the left edge of the Bbox.inverse_transformed(trans) verse_transform_bbox(trans.overlaps(bboxes)Bbox.bounds Bbox.xmax 1 Bbox.] inBbox.5.set_bounds() [Bbox. Changes for 0.ymin() transforms.ymax 1 Bbox.inverted().Bbox.Bbox. bbox) Interinterval_contains_open(tuple.transforms.Bbox. get_position() matplotlib.projections. 3 matplotlib.get_paths‘() [Returns a list of matplotlib. Axes.Path instances.axes Old method New method Axes.set_position() 3 Axes.Axes.set_position() now accepts either four scalars or a matplotlib. matplotlib.polar.set_clip_path(path.set_clip_path() now accepts a matplotlib.transforms.transforms.e.path.axes. it no longer makes sense to have a toggle.Axes. now it returns a matplotlib.toggle_log_lineary() matplotlib.1 matplotlib.Path instance and a matplotlib.colors Old method New method ColorConverColorConvertor.Matplotlib.Bbox instance.ColorConvertor.transforms.artist Old method New method Artist. The Polar class has moved to matplotlib.Axes. API Changes .toggle_log_lineary() has been removed.set_position() matplotlib. transform) 5 matplotlib.axes.to_rgba_array() returns an Nx4 Numpy array of RGBA color quadruples.Axes. a single value or multiple values may be provided.set_yscale() 4 Subplot class removed. i.Transform that will be applied to the path immediately before clipping.collections Old method linestyle New method linestyles 6 matplotlib.] matplotlib.axes.axes.colors.to_rgba_array(c) tor.contour. 6 Linestyles are now treated like all other collection attributes.0.axes.get_position() 2 Axes.contour Old method Contour.Artist.set_clip_path(path) Artist. 296 Chapter 32.path._segments 2 New method matplotlib. 4 Since the recfactoring allows for more than two scale types (‘log’ or ‘linear’).Axes.Contour.] matplotlib.Bbox instance.artist. 5 matplotlib.get_position() used to return a list of points. Release 1.to_rgba_list(c) [matplotlib. Matplotlib, Release 1.0.1 matplotlib.figure Old method Figure.dpi.get() / Figure.dpi.set() matplotlib.patches Old method New method Patch.get_verts() matplotlib.patches.Patch.get_path() [Returns a matplotlib.path.Path instance] matplotlib.backend_bases Old method New method GraphicsConGraphicsContext.set_clip_rectangle(bbox) text.set_clip_rectangle(tuple) GraphicsConGraphicsContext.get_clip_path() 7 text.get_clip_path() GraphicsConGraphicsContext.set_clip_path() 8 text.set_clip_path() New method matplotlib.figure.Figure.dpi (a property) RendererBase New methods: • draw_path(self, gc, path, transform, rgbFace) • draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace) <matplotlib.backend_bases.RendererBase.draw_markers() • draw_path_collection(self, master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds) [optional] Changed methods: • draw_image(self, x, y, im, bbox) is now draw_image(self, x, y, im, bbox, clippath, clippath_trans) Removed methods: • draw_arc • draw_line_collection 7 matplotlib.backend_bases.GraphicsContext.get_clip_path() returns a tuple of the form (path, affine_transform), where path is a matplotlib.path.Path instance and affine_transform is a matplotlib.transforms.Affine2D instance. 8 matplotlib.backend_bases.GraphicsContext.set_clip_path() now only accepts a matplotlib.transforms.TransformedPath instance. 32.5. Changes for 0.98.0 297 Matplotlib, Release 1.0.1 • draw_line • draw_lines • draw_point • draw_quad_mesh • draw_poly_collection • draw_polygon • draw_rectangle • draw_regpoly_collection 32.6 Changes for 0.91.2 • For csv2rec(), checkrows=0 is the new default indicating all rows will be checked for type inference • A warning is issued when an image is drawn on log-scaled axes, since it will not log-scale the image data. • Moved rec2gtk() to matplotlib.toolkits.gtktools • Moved rec2excel() to matplotlib.toolkits.exceltools • Removed, dead/experimental matplotlib.__init__ ExampleInfo, Namespace and Importer code from 32.7 Changes for 0.91.1 32.8 Changes for 0.91.0 • Changed cbook.is_file_like() to cbook.is_writable_file_like() and corrected behavior. • Added ax kwarg to pyplot.colorbar() and Figure.colorbar() so that one can specify the axes object from which space for the colorbar is to be taken, if one does not want to make the colorbar axes manually. • Changed cbook.reversed() so it yields a tuple rather than a (index, tuple). This agrees with the python reversed builtin, and cbook only defines reversed if python doesnt provide the builtin. • Made skiprows=1 the default on csv2rec() • The gd and paint backends have been deleted. • The errorbar method and function now accept additional kwargs so that upper and lower limits can be indicated by capping the bar with a caret instead of a straight line segment. • The matplotlib.dviread file now has a parser for files like psfonts.map and pdftex.map, to map TeX font names to external files. 298 Chapter 32. API Changes Matplotlib, Release 1.0.1 • The file matplotlib.type1font contains a new class for Type 1 fonts. Currently it simply reads pfa and pfb format files and stores the data in a way that is suitable for embedding in pdf files. In the future the class might actually parse the font to allow e.g. subsetting. • matplotlib.FT2Font now supports FT_Attach_File(). In practice this can be used to read an afm file in addition to a pfa/pfb file, to get metrics and kerning information for a Type 1 font. • The AFM class now supports querying CapHeight and stem widths. The get_name_char method now has an isord kwarg like get_width_char. • Changed pcolor() default to shading=’flat’; but as noted now in the docstring, it is preferable to simply use the edgecolor kwarg. • The mathtext font commands (\cal, \rm, \it, \tt) now behave as TeX does: they are in effect until the next font change command or the end of the grouping. Therefore uses of $\cal{R}$ should be changed to ${\cal R}$. Alternatively, you may use the new LaTeX-style font commands (\mathcal, \mathrm, \mathit, \mathtt) which do affect the following group, eg. $\mathcal{R}$. • Text creation commands have a new default linespacing and a new linespacing kwarg, which is a multiple of the maximum vertical extent of a line of ordinary text. The default is 1.2; linespacing=2 would be like ordinary double spacing, for example. • Changed default kwarg in matplotlib.colors.Normalize.__init__‘() to clip=False; clipping silently defeats the purpose of the special over, under, and bad values in the colormap, thereby leading to unexpected behavior. The new default should reduce such surprises. • Made the emit property of set_xlim() and set_ylim() True by default; removed the Axes custom callback handling into a ‘callbacks’ attribute which is a CallbackRegistry instance. This now supports the ‘xlim_changed’ and ‘ylim_changed’ Axes events. 32.9 Changes for 0.90.1 The file dviread.py has a (very limited and fragile) dvi reader for usetex support. The API might change in the future so don’t depend on it yet. Removed deprecated support for a float value as a gray-scale; now it must be a string, like ’0.5’. Added alpha kwarg to ColorConverter.to_rgba_list. New method set_bounds(vmin, vmax) for formatters, locators sets the viewInterval and dataInterval from floats. Removed deprecated colorbar_classic. Line2D.get_xdata and get_ydata valid_only=False kwarg is replaced by orig=True. When True, it returns the original data, otherwise the processed data (masked, converted) Some modifications to the units interface. units.ConversionInterface.tickers renamed to 32.9. Changes for 0.90.1 299 Matplotlib, Release 1.0.1 units.ConversionInterface.axisinfo and it now returns a units.AxisInfo object rather than a tuple. This will make it easier to add axis info functionality (eg I added a default label on this iteration) w/o having to change the tuple length and hence the API of the client code everytime new functionality is added. Also, units.ConversionInterface.convert_to_value is now simply named units.ConversionInterface.convert. Axes.errorbar uses Axes.vlines and Axes.hlines to draw its error limits int he vertical and horizontal direction. As you’ll see in the changes below, these funcs now return a LineCollection rather than a list of lines. The new return signature for errorbar is ylins, caplines, errorcollections where errorcollections is a xerrcollection, yerrcollection Axes.vlines and Axes.hlines now create and returns a LineCollection, not a list of lines. This is much faster. The kwarg signature has changed, so consult the docs MaxNLocator accepts a new Boolean kwarg (’integer’) to force ticks to integer locations. Commands that pass an argument to the Text constructor or to Text.set_text() now accept any object that can be converted with ’%s’. This affects xlabel(), title(), etc. Barh now takes a **kwargs dict instead of most of the old arguments. This helps ensure that bar and barh are kept in sync, but as a side effect you can no longer pass e.g. color as a positional argument. ft2font.get_charmap() now returns a dict that maps character codes to glyph indices (until now it was reversed) Moved data files into lib/matplotlib so that setuptools’ develop mode works. Re-organized the mpl-data layout so that this source structure is maintained in the installation. (I.e. the ’fonts’ and ’images’ sub-directories are maintained in site-packages.). Suggest removing site-packages/matplotlib/mpl-data and ~/.matplotlib/ttffont.cache before installing 32.10 Changes for 0.90.0 All artists now implement a "pick" method which users should not call. Rather, set the "picker" property of any artist you want to pick on (the epsilon distance in points for a hit test) and register with the "pick_event" callback. See examples/pick_event_demo.py for details Bar, barh, and hist have "log" binary kwarg: log=True sets the ordinate to a log scale. 300 Chapter 32. API Changes Matplotlib, Release 1.0.1 Boxplot can handle a list of vectors instead of just an array, so vectors can have different lengths. Plot can handle 2-D x and/or y; it plots the columns. Added linewidth kwarg to bar and barh. Made the default Artist._transform None (rather than invoking identity_transform for each artist only to have it overridden later). Use artist.get_transform() rather than artist._transform, even in derived classes, so that the default transform will be created lazily as needed New LogNorm subclass of Normalize added to colors.py. All Normalize subclasses have new inverse() method, and the __call__() method has a new clip kwarg. Changed class names in colors.py to match convention: normalize -> Normalize, no_norm -> NoNorm. Old names are still available for now. Removed obsolete pcolor_classic command and method. Removed lineprops and markerprops from the Annotation code and replaced them with an arrow configurable with kwarg arrowprops. See examples/annotation_demo.py - JDH 32.11 Changes for 0.87.7 Completely reworked the annotations API because I found the old API cumbersome. The new design is much more legible and easy to read. See matplotlib.text.Annotation and examples/annotation_demo.py markeredgecolor and markerfacecolor cannot be configured in matplotlibrc any more. Instead, markers are generally colored automatically based on the color of the line, unless marker colors are explicitely set as kwargs - NN Changed default comment character for load to ’#’ - JDH math_parse_s_ft2font_svg from mathtext.py & mathtext2.py now returns width, height, svg_elements. svg_elements is an instance of Bunch ( cmbook.py) and has the attributes svg_glyphs and svg_lines, which are both lists. Renderer.draw_arc now takes an additional parameter, rotation. It specifies to draw the artist rotated in degrees anticlockwise. It was added for rotated ellipses. 32.11. Changes for 0.87.7 301 Matplotlib, Release 1.0.1 Renamed Figure.set_figsize_inches to Figure.set_size_inches to better match the get method, Figure.get_size_inches. Removed the copy_bbox_transform from transforms.py; added shallowcopy methods to all transforms. All transforms already had deepcopy methods. FigureManager.resize(width, height): resize the window specified in pixels barh: x and y args have been renamed to width and bottom respectively, and their order has been swapped to maintain a (position, value) order. bar and barh: now accept kwarg ’edgecolor’. bar and barh: The left, height, width and bottom args can now all be scalars or sequences; see docstring. barh: now defaults to edge aligned instead of center aligned bars bar, barh and hist: Added a keyword arg ’align’ that controls between edge or center bar alignment. Collections: PolyCollection and LineCollection now accept vertices or segments either in the original form [(x,y), (x,y), ...] or as a 2D numerix array, with X as the first column and Y as the second. Contour and quiver output the numerix form. The transforms methods Bbox.update() and Transformation.seq_xy_tups() now accept either form. Collections: LineCollection is now a ScalarMappable like PolyCollection, etc. Specifying a grayscale color as a float is deprecated; use a string instead, e.g., 0.75 -> ’0.75’. Collections: initializers now accept any mpl color arg, or sequence of such args; previously only a sequence of rgba tuples was accepted. Colorbar: completely new version and api; see docstring. The original version is still accessible as colorbar_classic, but is deprecated. Contourf: "extend" kwarg replaces "clip_ends"; see docstring. Masked array support added to pcolormesh. Modified aspect-ratio handling: Removed aspect kwarg from imshow Axes methods: set_aspect(self, aspect, adjustable=None, anchor=None) 302 Chapter 32. API Changes Matplotlib, Release 1.0.1 set_adjustable(self, adjustable) set_anchor(self, anchor) Pylab interface: axis(’image’) Backend developers: ft2font’s load_char now takes a flags argument, which you can OR together from the LOAD_XXX constants. 32.12 Changes for 0.86 Matplotlib data is installed into the matplotlib module. This is similar to package_data. This should get rid of having to check for many possibilities in _get_data_path(). The MATPLOTLIBDATA env key is still checked first to allow for flexibility. 1) Separated the color table data from cm.py out into a new file, _cm.py, to make it easier to find the actual code in cm.py and to add new colormaps. Everything from _cm.py is imported by cm.py, so the split should be transparent. 2) Enabled automatic generation of a colormap from a list of colors in contour; see modified examples/contour_demo.py. 3) Support for imshow of a masked array, with the ability to specify colors (or no color at all) for masked regions, and for regions that are above or below the normally mapped region. See examples/image_masked.py. 4) In support of the above, added two new classes, ListedColormap, and no_norm, to colors.py, and modified the Colormap class to include common functionality. Added a clip kwarg to the normalize class. 32.13 Changes for 0.85 Made xtick and ytick separate props in rc made pos=None the default for tick formatters rather than 0 to indicate "not supplied" Removed "feature" of minor ticks which prevents them from overlapping major ticks. Often you want major and minor ticks at the same place, and can offset the major ticks with the pad. This could be made configurable Changed the internal structure of contour.py to a more OO style. 32.12. Changes for 0.86 303 Matplotlib, Release 1.0.1 Calls to contour or contourf in axes.py or pylab.py now return a ContourSet object which contains references to the LineCollections or PolyCollections created by the call, as well as the configuration variables that were used. The ContourSet object is a "mappable" if a colormap was used. Added a clip_ends kwarg to contourf. From the docstring: * clip_ends = True If False, the limits for color scaling are set to the minimum and maximum contour levels. True (default) clips the scaling limits. Example: if the contour boundaries are V = [-100, 2, 1, 0, 1, 2, 100], then the scaling limits will be [-100, 100] if clip_ends is False, and [-3, 3] if clip_ends is True. Added kwargs linewidths, antialiased, and nchunk to contourf. These are experimental; see the docstring. Changed Figure.colorbar(): kw argument order changed; if mappable arg is a non-filled ContourSet, colorbar() shows lines instead hof polygons. if mappable arg is a filled ContourSet with clip_ends=True, the endpoints are not labelled, so as to give the correct impression of open-endedness. Changed LineCollection.get_linewidths to get_linewidth, for consistency. 32.14 Changes for 0.84 Unified argument handling between hlines and vlines. Both now take optionally a fmt argument (as in plot) and a keyword args that can be passed onto Line2D. Removed all references to "data clipping" in rc and lines.py since these were not used and not optimized. I’m sure they’ll be resurrected later with a better implementation when needed. ’set’ removed - no more deprecation warnings. Use ’setp’ instead. Backend developers: Added flipud method to image and removed it from to_str. Removed origin kwarg from backend.draw_image. origin is handled entirely by the frontend now. 32.15 Changes for 0.83 - Made HOME/.matplotlib the new config dir where the matplotlibrc file, the ttf.cache, and the tex.cache live. The new default 304 Chapter 32. API Changes Matplotlib, Release 1.0.1 filenames in .matplotlib have no leading dot and are not hidden. Eg, the new names are matplotlibrc, tex.cache, and ttffont.cache. This is how ipython does it so it must be right. If old files are found, a warning is issued and they are moved to the new location. - backends/__init__.py no longer imports new_figure_manager, draw_if_interactive and show from the default backend, but puts these imports into a call to pylab_setup. Also, the Toolbar is no longer imported from WX/WXAgg. New usage: from backends import pylab_setup new_figure_manager, draw_if_interactive, show = pylab_setup() - Moved Figure.get_width_height() to FigureCanvasBase. It now returns int instead of float. 32.16 Changes for 0.82 - toolbar import change in GTKAgg, GTKCairo and WXAgg - Added subplot config tool to GTK* backends -- note you must now import the NavigationToolbar2 from your backend of choice rather than from backend_gtk because it needs to know about the backend specific canvas -- see examples/embedding_in_gtk2.py. Ditto for wx backend -- see examples/embedding_in_wxagg.py - hist bin change Sean Richards notes there was a problem in the way we created the binning for histogram, which made the last bin underrepresented. From his post: I see that hist uses the linspace function to create the bins and then uses searchsorted to put the values in their correct bin. Thats all good but I am confused over the use of linspace for the bin creation. I wouldn’t have thought that it does what is needed, to quote the docstring it creates a "Linear spaced array from min to max". For it to work correctly shouldn’t the values in the bins array be the same bound for each bin? (i.e. each value should be the lower bound of a bin). To provide the correct bins for hist would it not be something like def bins(xmin, xmax, N): if N==1: return xmax dx = (xmax-xmin)/N # instead of N-1 return xmin + dx*arange(N) 32.16. Changes for 0.82 305 Matplotlib, Release 1.0.1 This suggestion is implemented in 0.81. My test script with these changes does not reveal any bias in the binning from matplotlib.numerix.mlab import randn, rand, zeros, Float from matplotlib.mlab import hist, mean Nbins = 50 Ntests = 200 results = zeros((Ntests,Nbins), typecode=Float) for i in range(Ntests): print ’computing’, i x = rand(10000) n, bins = hist(x, Nbins) results[i] = n print mean(results) 32.17 Changes for 0.81 - pylab and artist "set" functions renamed to setp to avoid clash with python2.4 built-in set. Current version will issue a deprecation warning which will be removed in future versions - imshow interpolation arguments changes for advanced interpolation schemes. See help imshow, particularly the interpolation, filternorm and filterrad kwargs - Support for masked arrays has been added to the plot command and to the Line2D object. Only the valid points are plotted. A "valid_only" kwarg was added to the get_xdata() and get_ydata() methods of Line2D; by default it is False, so that the original data arrays are returned. Setting it to True returns the plottable points. - contour changes: Masked arrays: contour and contourf now accept masked arrays as the variable to be contoured. Masking works correctly for contour, but a bug remains to be fixed before it will work for contourf. The "badmask" kwarg has been removed from both functions. Level argument changes: Old version: a list of levels as one of the positional arguments specified the lower bound of each filled region; the upper bound of the last region was taken as a very large number. Hence, it was not possible to specify that z values between 0 and 1, for example, be filled, and that values outside that range remain unfilled. 306 Chapter 32. API Changes Matplotlib, Release 1.0.1 New version: a list of N levels is taken as specifying the boundaries of N-1 z ranges. Now the user has more control over what is colored and what is not. Repeated calls to contourf (with different colormaps or color specifications, for example) can be used to color different ranges of z. Values of z outside an expected range are left uncolored. Example: Old: contourf(z, [0, 1, 2]) would yield 3 regions: 0-1, 1-2, and >2. New: it would yield 2 regions: 0-1, 1-2. If the same 3 regions were desired, the equivalent list of levels would be [0, 1, 2, 1e38]. 32.18 Changes for 0.80 - xlim/ylim/axis always return the new limits regardless of arguments. They now take kwargs which allow you to selectively change the upper or lower limits while leaving unnamed limits unchanged. See help(xlim) for example 32.19 Changes for 0.73 - Removed deprecated ColormapJet and friends - Removed all error handling from the verbose object - figure num of zero is now allowed 32.20 Changes for 0.72 - Line2D, Text, and Patch copy_properties renamed update_from and moved into artist base class - LineCollecitons.color renamed to LineCollections.set_color for consistency with set/get introspection mechanism, - pylab figure now defaults to num=None, which creates a new figure with a guaranteed unique number - contour method syntax changed - now it is MATLAB compatible unchanged: contour(Z) old: contour(Z, x=Y, y=Y) new: contour(X, Y, Z) see http://matplotlib.sf.net/matplotlib.pylab.html#-contour 32.18. Changes for 0.80 307 Matplotlib, Release 1.0.1 - Increased the default resolution for save command. - Renamed the base attribute of the ticker classes to _base to avoid conflict with the base method. Sitt for subs - subs=none now does autosubbing in the tick locator. - New subplots that overlap old will delete the old axes. If you do not want this behavior, use fig.add_subplot or the axes command 32.21 Changes for 0.71 Significant numerix namespace changes, introduced to resolve namespace clashes between python built-ins and mlab names. Refactored numerix to maintain separate modules, rather than folding all these names into a single namespace. See the following mailing list threads for more information and background http://sourceforge.net/mailarchive/forum.php?thread_id=6398890&forum_id=36187 http://sourceforge.net/mailarchive/forum.php?thread_id=6323208&forum_id=36187 OLD usage from matplotlib.numerix import array, mean, fft NEW usage from matplotlib.numerix import array from matplotlib.numerix.mlab import mean from matplotlib.numerix.fft import fft numerix dir structure mirrors numarray (though it is an incomplete implementation) numerix numerix/mlab numerix/linear_algebra numerix/fft numerix/random_array but of course you can use ’numerix : Numeric’ and still get the symbols. pylab still imports most of the symbols from Numerix, MLab, fft, etc, but is more cautious. For names that clash with python names (min, max, sum), pylab keeps the builtins and provides the numeric versions with an a* prefix, eg (amin, amax, asum) 308 Chapter 32. API Changes Matplotlib, Release 1.0.1 32.22 Changes for 0.70 MplEvent factored into a base class Event and derived classes MouseEvent and KeyEvent Removed definct set_measurement in wx toolbar 32.23 Changes for 0.65.1 removed add_axes and add_subplot from backend_bases. Use figure.add_axes and add_subplot instead. The figure now manages the current axes with gca and sca for get and set current axe. If you have code you are porting which called, eg, figmanager.add_axes, you can now simply do figmanager.canvas.figure.add_axes. 32.24 Changes for 0.65 mpl_connect and mpl_disconnect in the MATLAB interface renamed to connect and disconnect Did away with the text methods for angle since they were ambiguous. fontangle could mean fontstyle (obligue, etc) or the rotation of the text. Use style and rotation instead. 32.25 Changes for 0.63 Dates are now represented internally as float days since 0001-01-01, UTC. All date tickers and formatters are now in matplotlib.dates, rather than matplotlib.tickers converters have been abolished from all functions and classes. num2date and date2num are now the converter functions for all date plots Most of the date tick locators have a different meaning in their constructors. In the prior implementation, the first argument was a base and multiples of the base were ticked. Eg HourLocator(5) # old: tick every 5 minutes In the new implementation, the explicit points you want to tick are provided as a number or sequence 32.22. Changes for 0.70 309 Matplotlib, Release 1.0.1 HourLocator(range(0,5,61)) # new: tick every 5 minutes This gives much greater flexibility. I have tried to make the default constructors (no args) behave similarly, where possible. Note that YearLocator still works under the base/multiple scheme. The difference between the YearLocator and the other locators is that years are not recurrent. Financial functions: matplotlib.finance.quotes_historical_yahoo(ticker, date1, date2) date1, date2 are now datetime instances. Return value is a list of quotes where the quote time is a float - days since gregorian start, as returned by date2num See examples/finance_demo.py for example usage of new API 32.26 Changes for 0.61 canvas.connect is now deprecated for event handling. use mpl_connect and mpl_disconnect instead. The callback signature is func(event) rather than func(widget, evet) 32.27 Changes for 0.60 ColormapJet and Grayscale are deprecated. For backwards compatibility, they can be obtained either by doing from matplotlib.cm import ColormapJet or from matplotlib.matlab import * They are replaced by cm.jet and cm.grey 32.28 Changes for 0.54.3 removed the set_default_font / get_default_font scheme from the font_manager to unify customization of font defaults with the rest of the rc scheme. See examples/font_properties_demo.py and help(rc) in matplotlib.matlab. 310 Chapter 32. API Changes Matplotlib, Release 1.0.1 32.29 Changes for 0.54 32.29.1 MATLAB interface dpi Several of the backends used a PIXELS_PER_INCH hack that I added to try and make images render consistently across backends. This just complicated matters. So you may find that some font sizes and line widths appear different than before. Apologies for the inconvenience. You should set the dpi to an accurate value for your screen to get true sizes. pcolor and scatter There are two changes to the MATLAB interface API, both involving the patch drawing commands. For efficiency, pcolor and scatter have been rewritten to use polygon collections, which are a new set of objects from matplotlib.collections designed to enable efficient handling of large collections of objects. These new collections make it possible to build large scatter plots or pcolor plots with no loops at the python level, and are significantly faster than their predecessors. The original pcolor and scatter functions are retained as pcolor_classic and scatter_classic. The return value from pcolor is a PolyCollection. Most of the propertes that are available on rectangles or other patches are also available on PolyCollections, eg you can say: c = scatter(blah, blah) c.set_linewidth(1.0) c.set_facecolor(’r’) c.set_alpha(0.5) or: c = scatter(blah, blah) set(c, ’linewidth’, 1.0, ’facecolor’, ’r’, ’alpha’, 0.5) Because the collection is a single object, you no longer need to loop over the return value of scatter or pcolor to set properties for the entire list. If you want the different elements of a collection to vary on a property, eg to have different line widths, see matplotlib.collections for a discussion on how to set the properties as a sequence. For scatter, the size argument is now in points^2 (the area of the symbol in points) as in MATLAB and is not in data coords as before. Using sizes in data coords caused several problems. So you will need to adjust your size arguments accordingly or use scatter_classic. mathtext spacing For reasons not clear to me (and which I’ll eventually fix) spacing no longer works in font groups. However, I added three new spacing commands which compensate for this ‘’ (regular space), ‘/’ (small space) and ‘hspace{frac}’ where frac is a fraction of fontsize in points. You will need to quote spaces in font strings, is: 32.29. Changes for 0.54 311 Matplotlib, Release 1.0.1 title(r’$\rm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$’) 32.29.2 Object interface - Application programmers Autoscaling The x and y axis instances no longer have autoscale view. axes.autoscale_view Axes creation These are handled by You should not instantiate your own Axes any more using the OO API. Rather, create a Figure as before and in place of: f = Figure(figsize=(5,4), dpi=100) a = Subplot(f, 111) f.add_axis(a) use: f = Figure(figsize=(5,4), dpi=100) a = f.add_subplot(111) That is, add_axis no longer exists and is replaced by: add_axes(rect, axisbg=defaultcolor, frameon=True) add_subplot(num, axisbg=defaultcolor, frameon=True) Artist methods If you define your own Artists, you need to rename the _draw method to draw Bounding boxes matplotlib.transforms.Bound2D is replaced by matplotlib.transforms.Bbox. If you want to construct a bbox from left, bottom, width, height (the signature for Bound2D), use matplotlib.transforms.lbwh_to_bbox, as in bbox = clickBBox = lbwh_to_bbox(left, bottom, width, height) The Bbox has a different API than the Bound2D. Eg, if you want to get the width and height of the bbox OLD:: width = fig.bbox.x.interval() height = fig.bbox.y.interval() New:: width = fig.bbox.width() height = fig.bbox.height() 312 Chapter 32. API Changes Matplotlib, Release 1.0.1 Object constructors You no longer pass the bbox, dpi, or transforms to the various Artist constructors. The old way or creating lines and rectangles was cumbersome because you had to pass so many attributes to the Line2D and Rectangle classes not related directly to the gemoetry and properties of the object. Now default values are added to the object when you call axes.add_line or axes.add_patch, so they are hidden from the user. If you want to define a custom transformation on these objects, call o.set_transform(trans) where trans is a Transformation instance. In prior versions of you wanted to add a custom line in data coords, you would have to do l = Line2D(dpi, bbox, x, y, color = color, transx = transx, transy = transy, ) now all you need is l = Line2D(x, y, color=color) and the axes will set the transformation for you (unless you have set your own already, in which case it will eave it unchanged) Transformations The entire transformation architecture has been rewritten. Previously the x and y transformations where stored in the xaxis and yaxis insstances. The problem with this approach is it only allows for separable transforms (where the x and y transformations don’t depend on one another). But for cases like polar, they do. Now transformations operate on x,y together. There is a new base class matplotlib.transforms.Transformation and two concrete implemetations, matplotlib.transforms.SeparableTransformation and matplotlib.transforms.Affine. The SeparableTransformation is constructed with the bounding box of the input (this determines the rectangular coordinate system of the input, ie the x and y view limits), the bounding box of the display, and possibily nonlinear transformations of x and y. The 2 most frequently used transformations, data cordinates -> display and axes coordinates -> display are available as ax.transData and ax.transAxes. See alignment_demo.py which uses axes coords. Also, the transformations should be much faster now, for two reasons • they are written entirely in extension code • because they operate on x and y together, they can do the entire transformation in one loop. Earlier I did something along the lines of: xt = sx*func(x) + tx yt = sy*func(y) + ty Although this was done in numerix, it still involves 6 length(x) for-loops (the multiply, add, and function evaluation each for x and y). Now all of that is done in a single pass. If you are using transformations and bounding boxes to get the cursor position in data coordinates, the method calls are a little different now. See the updated examples/coords_demo.py which shows you how to do this. 32.29. Changes for 0.54 313 Matplotlib, Release 1.0.1 Likewise, if you are using the artist bounding boxes to pick items on the canvas with the GUI, the bbox methods are somewhat different. You will need to see the updated examples/object_picker.py. See unit/transforms_unit.py for many examples using the new transformations. 32.30 Changes for 0.50 * refactored Figure class so it is no longer backend dependent. FigureCanvasBackend takes over the backend specific duties of the Figure. matplotlib.backend_bases.FigureBase moved to matplotlib.figure.Figure. * backends must implement FigureCanvasBackend (the thing that controls the figure and handles the events if any) and FigureManagerBackend (wraps the canvas and the window for MATLAB interface). FigureCanvasBase implements a backend switching mechanism * Figure is now an Artist (like everything else in the figure) and is totally backend independent * GDFONTPATH renamed to TTFPATH * backend faceColor argument changed to rgbFace * colormap stuff moved to colors.py * arg_to_rgb in backend_bases moved to class ColorConverter in colors.py * GD users must upgrade to gd-2.0.22 and gdmodule-0.52 since new gd features (clipping, antialiased lines) are now used. * Renderer must implement points_to_pixels Migrating code: MATLAB interface: The only API change for those using the MATLAB interface is in how you call figure redraws for dynamically updating figures. In the old API, you did fig.draw() In the new API, you do manager = get_current_fig_manager() manager.canvas.draw() See the examples system_monitor.py, dynamic_demo.py, and anim.py 314 Chapter 32. API Changes Now the Figure class is independent of the backend.42 * Refactoring AxisText to be backend independent. All prior calls to figure. not a Figure.draw() and canvas. In order to include figures into your apps.print_figure(args) should now be canvas. FigureGTK subclassed gtk. and FigureCanvas takes over the functionality formerly handled by Figure. 32. Figure instances used subclass GUI widgets that enabled them to be placed directly into figures. Release 1.DrawingArea.31.py all reflect the new API so use these as a guide.1 API There is one important API change for application developers. dpi=100) canvas = FigureCanvasGTK(fig) # a gtk. * backend_bases. so I hope the inconvenience is worth it. and mpl_with_glade. you now need to do. This refactorization brings significant more freedom in developing matplotlib and should bring better plotting capabilities. Ditto with state change. eg by caching a font or layout instance in a dict with the prop tup as a key -. Changes for 0. embedding_in_gtk2. The examples embedding_in_gtk. 32.31 Changes for 0.draw() and figure. this in now intialized with a FigureCanvas.DrawingArea canvas. Text drawing and get_window_extent functionality will be moved to the Renderer.pack_start(canvas) If you use the NavigationToolbar.see RendererGTK.0.get_pango_layout in backend_gtk for an example.42 315 . for example # gtk example fig = Figure(figsize=(5.not needed with double buffered drawing.Text module * All the erase and reset functionality removed frmo AxisText .show() vbox.py.Matplotlib.py. Text instances have a get_prop_tup method that returns a hashable tuple of text properties which you can use to see if text props have changed.AxisTextBase is now text.print_figure(args) Apologies for the inconvenience. Eg.4). Axis.40 .AxisTextBase * Initialized with a transx. API Changes .axis * moved process_text_args to matplotlib.Patches * Initialized with a transx.axes into matplotlib.min is left.Matplotlib._get_xy_display renamed Text. for example. transy which are Transform instances ..FigureBase attributes dpi is a DPI intance rather than scalar and new attribute bbox is a Bound2D in display coords.Artist * __init__ takes a DPI instance and a Bound2D instance which is the bounding box of the artist in display coords * get_window_extent returns a Bound2D instance * set_size is removed.text * After getting Text handled in a backend independent fashion. the import process is much cleaner since there are no longer cyclic dependencies * matplotlib.legend * Moved Tick.0.matlab. eg figManager. bbox. transy which are Transform instances . etc.GcfBase attribute pagesize renamed to figsize 316 Chapter 32. . transy * Initialized with a transx.. etc.frame for wx 32.axes to matplotlib.window for GTK and figManager. gc clip to bbox.x.y. Release 1.get_current_fig_manager to allow user access to the GUI window attribute. height. width. attributes. YTick.Line2D Patches now take transx.. YAxis from matplotlib.get_xy_display * Artist set_renderer and wash_brushes methods removed * Moved Legend class from matplotlib..max is top.1 * Text. bbox.matlab. XAxis. transy which are Transform instances * set_drawing_area removed * get_left_right and get_top_bottom are replaced by get_window_extent . Artists now clip themselves with their box * added _clipOn boolean attribute. bbox._get_current_fig_manager renamed to matplotlib. and I got rid of the left. replaced by bbox and dpi * the clip_gc method is removed. .x. These are now accessible as. XTick.interval() is width. If True.32 Changes for 0. Renderer methods for patches now take gcEdge and gcFace instances. Changes for 0. Bound2D and Transform instances and more .get_all_fig_managers Jeremy: Make sure to self. This was 32._set_font.32.GcfBase is renamed by Gcf.1 . * FigureManagerBase moved to backend_bases * Gcf. gcFace=None takes the place of filled=False .True and False symbols provided by cbook in a python2.Subplot * added fig instance to __init__ . Instead. they provide a factory function new_figure_manager(num. The destroy method of the GcfDerived from the backends is moved to the derived FigureManager.40 317 .Changes to the MATLAB helpers API * _matlab_helpers. Release 1.Matplotlib.Axes * removed figbg attribute * added fig instance to __init__ * resizing is handled by figure call to resize. . Backends no longer need to derive from this class.get_all_figwins renamed to Gcf.new module transforms supplies Bound1D. dpi). something missing in my backend code.0. figsize.3 compatible way ._reset = False in AxisTextWX. Matplotlib.1 318 Chapter 32. Release 1. API Changes .0. 1 matplotlib This is an object-orient plotting library.g: from matplotlib.lines defines the Line2D class for drawing lines and markers matplotlib.collections classes for efficient drawing of groups of lines or polygons matplotlib.text defines the Text.artist defines the Artist base class for all classes that draw things. The exceptions are the pyplot commands figure(). subplots(). use: from pylab import * or using ipython: ipython -pylab For the most part. e. direct use of the object-oriented library is encouraged when programming. A procedural interface is provided by the companion pyplot module. matplotlib. TextWithDash.pyplot import * To include numpy functions too. The axes module is the highest level of OO access to the library. and savefig().CHAPTER THIRTYTHREE MATPLOTLIB CONFIGURATION 33. Most pylab commands are wrappers for Axes methods.patches defines classes for drawing polygons matplotlib. which may be imported directly. pyplot is primarily for working interactively.figure defines the Figure class. which can greatly simplify scripting. Modules include: matplotlib. and Annotate classes matplotlib.image defines the AxesImage and FigureImage classes matplotlib. show(). matplotlib.colors classes for interpreting color specifications and for making colormaps 319 . subplot().axes defines the Axes class. matplotlib. 0. matplotlib. eg.cm colormaps and the ScalarMappable mixin class for providing color mapping functionality to other classes matplotlib. linewidth=2.com) and is now developed and maintained by a host of others. you can customize the font rc as follows: 320 Chapter 33. the group is axes. lw=2. ytick). c=’r’) Note you can use python’s kwargs dictionary facility to store dictionaries of default parameters. color=’r’) sets the current rc params and is equivalent to: rcParams[’lines. eg. (xtick. Group is the grouping for the rc.facecolor. **kwargs) Set the current rc params. In particular. Occasionally the internal documentation (python docstrings) will refer to MATLAB®.ticker classes for calculating tick mark locations and for formatting tick labels matplotlib.linewidth’] = 2 rcParams[’lines. It is initialized by code which may be overridded by a matplotlibrc file. a registered trademark of The MathWorks. kwargs is a dictionary attribute name/value pairs. and so on. If used. Release 1.Matplotlib. this function must be called immediately after importing matplotlib for the first time.linewidth the group is lines. Hunter (jdh2358 at gmail.backends a subpackage with modules for various gui libraries and output formats The base matplotlib namespace includes: rcParams a global dictionary of default configuration settings. matplotlib configuration .1 matplotlib. rc() a function for setting groups of rcParams values use() a function for setting the matplotlib backend. matplotlib was initially written by John D.rc(group.color’] = ’r’ The following aliases are available to save typing for interactive users: Alias ‘lw’ ‘ls’ ‘c’ ‘fc’ ‘ec’ ‘mew’ ‘aa’ Property ‘linewidth’ ‘linestyle’ ‘color’ ‘facecolor’ ‘edgecolor’ ‘markeredgewidth’ ‘antialiased’ Thus you could abbreviate the above rc command as: rc(’lines’. it must be called before importing pylab (if pylab is imported). for axes. for lines. Group may also be a list or tuple of group names. Inc. eg: rc(’lines’.. Eg. it must be called before importing matplotlib. the argument can have an extension to indicate the type of output. Note: this function must be called before importing pylab for the first time. See rc_file_defaults for reloading the default params from the rc file matplotlib. For the Cairo backend. but mpl’s internal params. a warning is issued if you try and callthis after pylab or pyplot have been loaded. Example: use(‘cairo.1.0. ’weight’ : ’bold’.use(arg. In certain black magic use cases. matplotlib 321 . eg pyplot. If warn is True.pdf’) will specify a default of pdf output generated by Cairo. we are doing the reloading necessary to make the backend switch work (in some cases. warn=True) Set the matplotlib backend to one of the known backends.switch_backends. ’size’ : ’larger’} rc(’font’.1 font = {’family’ : ’monospace’. The argument is case-insensitive. eg pure image backends) so one can set warn=False to supporess the warnings 33.backends. **font) # pass in the font dict as kwargs This enables you to easily switch between several configurations. Use rcdefaults() to restore the default rc params after changes.rcdefaults() Restore the default rc params .Matplotlib. matplotlib. or. if you are not using pylab.these are not the params loaded by the rc file. Release 1. matplotlib configuration .0.Matplotlib. Release 1.1 322 Chapter 33. CHAPTER THIRTYFOUR MATPLOTLIB AFM 34.string_width_height(’What the heck?’) (6220. Hunter <jdh2358@gmail. Although a number of other python implementations exist (and may be more complete than mine) I decided not to go with them because either they were either 1. -9.0 >>> afm. isord=False) 323 .1 matplotlib.com> class matplotlib. 676] >>> afm.get_fontname() ’Times-Roman’ >>> afm.afm.afm This is a python interface to Adobe Font Metrics Files. ’f’) 0 >>> afm. copyrighted or used a non-BSD compatible license 2. 238. 1000.afm’) >>> afm = AFM(fh) >>> afm.get_bbox_font() [-168. Did more than I needed and it was easier to write my own than figure out how to just get what I needed from theirs It is pretty easy to use.AFM(fh) Parse the AFM file in file object fh get_angle() Return the fontangle as float get_bbox_char(c. -218. 898] AUTHOR: John D. and requires only built-in python libs: >>> from afm import AFM >>> fh = file(’ptmr8a.get_bbox_char(’!’) [130. 683) >>> afm. ’y’) -92.get_kern_dist(’A’.0. had too many dependencies and I wanted a free standing lib 3.get_kern_dist(’A’. matplotlib. isord=False) Get the height of character c from the bounding box. eg. Return value is a (dhead. ‘Times-Roman’ get_fullname() Return the font full name.afm. ‘Bold’ or ‘Roman’ get_width_char(c. or None if not specified in AFM file. isord=False) Get the name of the character. eg. dcomposite) tuple where dhead is a _parse_header() dict. dcmetrics. Release 1.1 get_capheight() Return the cap height as float get_familyname() Return the font family name. h) tuple. matplotlib afm . or None if not specified in AFM file. eg. ‘. dcmetrics is a 324 Chapter 34.Matplotlib. This is the ink height (space is 0) get_horizontal_stem_width() Return the standard horizontal stem width as float. get_kern_dist(c1. ‘Times’ get_fontname() Return the font name. ‘Times-Roman’ get_height_char(c.parse_afm(fh) Parse the Adobe Font Metics file in file handle fh. ie.’ is ‘semicolon’ get_str_bbox(s) Return the string bounding box get_str_bbox_and_descent(s) Return the string bounding box get_underline_thickness() Return the underline thickness as float get_vertical_stem_width() Return the standard vertical stem width as float.0. c2) Return the kerning pair distance (possibly 0) for chars c1 and c2 get_kern_dist_from_name(name1. dkernpairs. get_weight() Return the font weight. name2) Return the kerning pair distance (possibly 0) for chars name1 and name2 get_name_char(c. eg. isord=False) Get the width of the character from the character metric WX field get_width_from_char_name(name) Get the width of the character from a type1 character name get_xheight() Return the xheight as float string_width_height(s) Return the string width (including kerning) and string height as a (w. 1.afm 325 .Matplotlib.0. and dcomposite is a _parse_composites() dict (possibly {}) 34. dkernpairs is a _parse_kern_pairs() dict (possibly {}). Release 1. matplotlib.1 _parse_composites() dict. matplotlib afm .Matplotlib.1 326 Chapter 34.0. Release 1. VertexSelector patches.Circle patches.Annotation 35.YAArrow text.artist.Line2D patches.Arc patches.ArrowStyle patches.ConnectionPatch artist.Artist Bases: object Abstract base class for someone who renders into a FigureCanvas.Arrow patches.W edge patches.Artist lines.Polygon patches.Rectangle patches.1 matplotlib.T extWithDash text.RegularPolygon lines.ConnectionStyle patches.CHAPTER THIRTYFIVE MATPLOTLIB ARTISTS patches.FancyArrow patches.CirclePolygon patches.Ellipse text._AnnotationBase text.BoxStyle patches.FancyArrowPatch patches.PathPatch patches. 327 .Patch patches.artist class matplotlib.Shadow patches.T ext text.FancyBboxPatch patches.OffsetFrom patches._Style patches. such as which points are contained in the pick radius. Only return artists of class type get_agg_filter() return filter function to be used for agg filter get_alpha() Return the alpha value used for blending . **kwargs) Derived classes drawing method findobj(match=None) pyplot signature: findobj(o=gcf(). convert x using xaxis unit type convert_yunits(y) For artists in an axes. match=None) Recursively find all :class:matplotlib. or None get_children() Return a list of the child Artist‘s this :class:‘Artist contains. matplotlib artists .artist. convert y using yaxis unit type draw(renderer.1 add_callback(func) Adds a callback function that will be called whenever one of the Artist‘s properties changes. See individual artists for details. match can be •None: return all objects contained in artist (including artist) •function with signature boolean = match(artist) used to filter matches •class instance: eg Line2D. Returns the truth value and a dictionary of artist specific details of selection. if the yaxis has units support.Matplotlib. convert_xunits(x) For artists in an axes. contains(mouseevent) Test whether the artist contains the mouse event. Release 1. Returns an id that is useful for removing the callback with remove_callback() later. if the xaxis has units support. get_clip_box() Return artist clipbox get_clip_on() Return whether artist uses clipping get_clip_path() Return artist clip path 328 Chapter 35. *args.0.Artist instances contained in self.not supported on all backends get_animated() Return the artist’s animated state get_axes() Return the Axes instance the artist resides in. get_gid() Returns the group id get_label() Get the label used for this artist in the legend.0 Message length ---> Minimum Message Length Model length Data length Total message length 0. get_picker() Return the picker object used by this artist get_rasterized() return True if the artist is to be rasterized get_snap() Returns the snap setting which may be: •True: snap vertices to the nearest pixel center •False: leave vertices as-is •None: (auto) If the path contains only rectilinear line segments. Release 1.1.1 20 15 10 5 0 0. matplotlib.0 Model complexity ---> 2. round to the nearest pixel center 35.5 1.artist 329 .5 1.0 get_contains() Return the _contains test used by the artist.0 2. get_figure() Return the Figure instance the artist belongs to.Matplotlib.5 3. or None for default.0. have_units() Return True if units are set on the x or y axes hitlist(event) List the children of the artist which contain the mouse event event. properties() return a dictionary mapping property name -> value for all Artist props remove() Remove the artist from the figure if possible. Call matplotlib. is_figure_set() Returns True if the artist is assigned to a Figure.draw_idle().Axes.. is_transform_set() Returns True if Artist has a transform explicitly set. Note: relim() will not see collections even if the collection was added to axes with autolim = True. calling all of the registered callbacks. The effect will not be visible until the figure is redrawn.Axes.0.axes.Matplotlib.relim() to update the axes limits if desired. get_transform() Return the Transform instance used by this artist.1 Only supported by the Agg and MacOSX backends.axes.g. Note: there is no support for removing the artist’s legend entry. Release 1. pick(mouseevent) call signature: pick(mouseevent) each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set pickable() Return True if Artist is pickable. matplotlib artists . with matplotlib. pchanged() Fire an event when property changed. and the remaining affine part of its transformation. 330 Chapter 35. get_url() Returns the url get_visible() Return the artist’s visiblity get_zorder() Return the Artist‘s zorder. get_transformed_clip_path_and_affine() Return the clip path with the non-affine part of its transformation applied. e. 0 opaque) set_animated(b) Set the artist’s animation state. in which case an optional Transform instance may be provided. set_alpha(alpha) Set the alpha value used for blending .1 remove_callback(oid) Remove a callback based on its id. if any. ACCEPTS: float (0. See Also: add_callback() For adding callbacks set(**kwargs) A tkstyle set command.1. this method will set the clipping box to the corresponding rectangle and set the clipping path to None. Release 1. transform=None) Set the artist’s clip path. ACCEPTS: [True | False] set_axes(axes) Set the Axes instance in which the artist resides. ACCEPTS: [ (Path. pass kwargs to set properties set_agg_filter(filter_func) set agg_filter fuction.Matplotlib. if the path happens to be an axis-aligned rectangle.0 transparent through 1. matplotlib. ACCEPTS: an Axes instance set_clip_box(clipbox) Set the artist’s clip Bbox.transforms. Transform) | Patch | None ] set_contains(picker) Replace the contains test used by this artist. which may be: •a Patch (or subclass) instance •a Path instance. ACCEPTS: [True | False] set_clip_path(path. The new picker should be a callable function which determines whether the artist is hit by the mouse event: 35. which will be applied to the path before using it for clipping. •None.artist 331 . ACCEPTS: a matplotlib.not supported on all backends.0. to remove the clipping path For efficiency.Bbox instance set_clip_on(b) Set whether artist uses clipping. g. the indices of the data within epsilon of the pick event •A function: if picker is callable. 332 Chapter 35. matplotlib artists . e. return hit=True and props is a dictionary of properties you want added to the PickEvent attributes. it is a user supplied function which determines whether the artist is hit by the mouse event: hit. the artists may examine things like the pixel width of the axes and draw a subset of their contents accordingly ACCEPTS: [True | False] set_picker(picker) Set the epsilon for picking used by this artist picker can be one of the following: •None: picking is disabled for this artist (default) •A boolean: if True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist •A float: if picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if it’s data is within epsilon of the mouse event. mouseevent) to determine the hit test. props = picker(artist.figure. return hit = True and props is a dictionary of properties you want returned with the contains test. props = picker(artist.Matplotlib.Figure instance set_gid(gid) Sets the (group) id for the artist ACCEPTS: an id string set_label(s) Set the label to s for auto legend. mouseevent) If the mouse event is over the artist. For some artists like lines and patch collections. if the mouse event is over the artist. If on. ACCEPTS: any string set_lod(on) Set Level of Detail on or off. ACCEPTS: a matplotlib.1 hit. Release 1. ACCEPTS: a callable function set_figure(fig) Set the Figure instance the artist belongs to.0. the artist may provide additional data to the pick event that is generated. ACCEPTS: [None|float|boolean|callable] set_rasterized(rasterized) Force rasterized (bitmap) drawing in vector backend output. matplotlib. return ‘markerfacecolor or mfc’ and for the transform property. Artists with lower zorder values are drawn first. aliased_name(s) return ‘PROPNAME or alias’ if s has an alias. Release 1. which implies the backend’s default behavior ACCEPTS: [True | False | None] set_snap(snap) Sets the snap setting which may be: •True: snap vertices to the nearest pixel center •False: leave vertices as-is •None: (auto) If the path contains only rectilinear line segments. E. return ‘transform’ aliased_name_rest(s. ACCEPTS: Transform instance set_url(url) Sets the url for the artist ACCEPTS: a url string set_visible(b) Set the artist’s visiblity.artist 333 . class matplotlib.artist. Initialize the artist inspector with an Artist or sequence of Artists. ACCEPTS: [True | False] set_zorder(level) Set the zorder for the artist. round to the nearest pixel center Only supported by the Agg and MacOSX backends. target) return ‘PROPNAME or alias’ if s has an alias.0. which does not.1 Defaults to None. which has an alias. set_transform(t) Set the Transform instance used by this artist. else return PROPNAME. If a sequence is used. update_from(other) Copy properties from other to self. for the line markerfacecolor property. we assume it is a homogeneous sequence (all Artists are of the same type) and it is your responsibility to make sure this is so.g.Matplotlib. else return PROPNAME formatted for ReST 35. ACCEPTS: any number update(props) Update the properties of this Artist from the dictionary prop.ArtistInspector(o) A helper class to inspect an Artist and return information about it’s settable properties and their current values.1. Format the output for ReST If prop is not None. for lines: {’markerfacecolor’: ’mfc’.. matplotlib artists . } get_setters() Get the attribute strings with setters for object. properties() return a dictionary mapping property name -> value 334 Chapter 35. If prop is not None.Artist instances contained in self.]. Eg. return [’markerfacecolor’..1 E. Release 1.. Eg. ’linewidth’. return a list of strings of all settable properies and their valid values. get_aliases() Get a dict mapping fullname -> alias for each alias in the ArtistInspector.. for a line linestyle. which has an alias. . for the line markerfacecolor property. leadingspace=2) If prop is None. return ‘transform’ findobj(match=None) Recursively find all matplotlib. it can be •function with signature boolean = match(artist) •class instance: eg Line2D used to filter matches. it is a valid property name and that property will be returned as a string of property : valid values. This is done by querying the docstring of the function set_attr for a line that begins with ACCEPTS: Eg. leadingspace=2) If prop is None. pprint_getters() Return the getters and actual values as list of strings.g..artist. ’linewidth’ : ’lw’. which does not. return “[ ’-’ | ’--’ | ’-. return ‘markerfacecolor or mfc’ and for the transform property. get_valid_values(attr) Get the legal arguments for the setter associated with attr.Matplotlib. return a list of strings of all settable properies and their valid values. pprint_setters_rest(prop=None.. it is a valid property name and that property will be returned as a string of property : valid values.0.’ | ’:’ | ’steps’ | ’None’ ]” is_alias(o) Return True if method object o is an alias for another function. pprint_setters(prop=None. for a line. If match is not None. g. If the property is ‘somename’. ’linestyle’) # get the linestyle property obj is a Artist instance. such as starting and flushing a mixed-mode renderer.g.get_somename() getp() can be used to query all the gettable properties with getp(obj). **kwargs) matplotlib supports the use of setp() (“set property”) and getp() to set and get object properties.artist. eg Line2D or an instance of a Axes or matplotlib. The before and after functions are useful for changing artist-dependant renderer attributes or making other setup function calls.Matplotlib. In the output. property=None) Return the value of object’s property. aliases and full property names will be listed as: property or alias = value e.Text. this function returns obj.allow_rasterization(draw) Decorator for Artist.0.g.1 matplotlib. as well as to do introspection on the object.g.text.artist.Text. If the property is ‘somename’. In the output.text.: linewidth or lw = 2 matplotlib. Provides routines that run before and after the draw call. Release 1. For example. eg Line2D or an instance of a Axes or matplotlib. aliases and full property names will be listed as: property or alias = value e. *args. ‘lw’ is an alias for ‘linewidth’. this function returns obj. property=None) Return the value of object’s property. property is an optional string for the property you want to return Example usage: getp(obj) # get all the object properties getp(obj. Many properties have aliases for shorter typing.artist.get(obj.get_somename() getp() can be used to query all the gettable properties with getp(obj).1.artist 335 . e. to set the linestyle of a line to be dashed.setp(obj.artist.: linewidth or lw = 2 matplotlib. matplotlib.draw method.kwdoc(a) matplotlib. e. you can do: 35. ’linestyle’) # get the linestyle property obj is a Artist instance. matplotlib. ‘lw’ is an alias for ‘linewidth’. Many properties have aliases for shorter typing. property is an optional string for the property you want to return Example usage: getp(obj) # get all the object properties getp(obj.artist.getp(obj. you can provide the name of the property you want to set without a value: >>> setp(line. ’color’.0.’ | ’:’ | ’steps’ | ’None’ ] If you want to see all the properties that can be set.2 matplotlib.. and their possible values. the following are equivalent: >>> setp(lines. ‘right’ : 5. the following will make both lines thicker and red: >>> >>> >>> >>> >>> x = arange(0. Release 1. only the first instance in the sequence is used.legend.2. E. x. ‘center’ : 10. color=’r’) # MATLAB style # python style 35.Matplotlib. For example.1 >>> line. matplotlib artists .DraggableOffsetBox artist_picker(legend. use_blit=False) Bases: matplotlib. y2) setp(lines. linestyle=’--’) If you want to know the valid types of arguments. ‘center left’ : 6.g. y1. color=’r’) setp() works with the MATLAB style string/value pairs or with python kwargs. linewidth=2. evt) finalize_offset() 336 Chapter 35. suppose you have a list of two lines. linewidth=2. line instances that make up the legend class matplotlib..1.offsetbox. ‘center right’ : 7. Return value is a sequence of text. ‘lower center’ : 8. 2. you can do: >>> setp(line) . (only implemented for axis legends) ‘upper right’ : 1. If you are in query mode introspecting the possible values. ’linewidth’. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location The location codes are ‘best’ : 0. r’) >>> setp(lines.01) y1 = sin(2*pi*x) y2 = sin(4*pi*x) lines = plot(x. ‘upper center’ : 9. all the instances will be set.3]) >>> setp(line. When actually setting values.DraggableLegend(legend. = plot([1. long output listing omitted setp() operates on a single instance or a list of instances. ‘lower right’ : 4.0. ‘lower left’ : 3. ’linestyle’) linestyle: [ ’-’ | ’--’ | ’-.legend Place a legend on the axes at location loc.0.. ‘upper left’ : 2. 2.Artist Place a legend on the axes at location loc. handles. line instances that make up the legend •parent : the artist that contains the legend •handles : a list of artists (lines. 8. frameon=True) Bases: matplotlib. mode=None.legend 337 . scatterpoints=3. Release 1. patches) to add to the legend •labels : a list of strings to label the legend Optional keyword arguments: 35. bbox_transform=None. ncol=1. 2. prop=None. loc can be a tuple of the noramilzed coordinate values with respect its parent. matplotlib. labelspacing=None.Legend(parent. loc=None. 7. handlelength=None. 10.artist. 6. shadow=None. (only implemented for axis legends) 1.Matplotlib. handlelen=None. 3.1 class matplotlib. handletextpad=None. numpoints=None. borderaxespad=None. labels. bbox_to_anchor=None. 9. scatteryoffsets=None. axespad=None. markerscale=None. borderpad=None. 4. labelsep=None. 5.0. handletextsep=None. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location The location codes are: ’best’ ’upper right’ ’upper left’ ’lower left’ ’lower right’ ’right’ ’center left’ ’center right’ ’lower center’ ’upper center’ ’center’ : : : : : : : : : : : 0.legend. title=None. Return value is a sequence of text. pad=None. columnspacing=None. fancybox=None. 0. *args. See set_bbox_to_anchor() for more detail. draw(artist. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. The legend location can be specified by setting loc with a tuple of 2 floats.. the transform for the bbox. draw a frame with a round fancybox. Release 1. Users can specify any arbitrary location for the legend using the bbox_to_anchor keyword argument.g. you can drag the legend on the canvas with the mouse. Values from rcParams will be used if None. **kwargs) Draw everything that belongs to the legend draw_frame(b) b is a boolean. E. renderer. transAxes if None. If None. draggable(state=None. matplotlib artists . draw a shadow behind legend number of columns the fractional whitespace inside the legend border the vertical space between the legend entries the length of the legend handles the pad between the legend handle and text the pad between the axes and legend border the spacing between columns the legend title the bbox that the legend will be anchored. The pad and spacing parameters are measure in font-size units. original the number of points in the legend for line the number of points in the legend for scatter plot a list of yoffsets for scatter symbols in legend if True. The DraggableLegend helper instance is returned if draggable is on. which is interpreted as the lower-left corner of the legend in the normalized axes coordinate. a fontsize of 10 points and a handlelength=5 implies a handlelength of 50 points.1 Keyword loc prop markerscale numpoints scatterpoints scatteryoffsets frameon fancybox shadow ncol borderpad labelspacing handlelength handletextpad borderaxespad columnspacing title bbox_to_anchor bbox_transform Description a location code the font property the relative size of legend markers vs. use_blit=False) Set the draggable state – if state is •None : toggle the current state •True : turn draggable on •False : turn draggable off If draggable is on. Set draw frame to b get_bbox_to_anchor() return the bbox that the legend will be anchored get_children() return a list of child artists 338 Chapter 35.Matplotlib. use rc if True. draw a frame (default is True) if True. the drawing of the solid line is influenced by the drawstyle.artist. dash_capstyle=None. a tuple of [left. set_frame_on(b) Set whether the legend box patch is drawn ACCEPTS: [ True | False ] set_title(title) set the legend title 35. markeredgecolor=None. marker=None.the line can have both a solid linestyle connecting all the vertices.Artist A line .lines This module contains all the 2D line class which can draw with a variety of line styles.Line2D(xdata. linewidth=None. eg one can create “stepped” lines in various styles. width.lines.lines 339 .Line2D instances in the legend get_patches() return a list of patch instances in the legend get_texts() return a list of text. transform=None) set the bbox that the legend will be anchored.Matplotlib. Release 1. antialiased=None. matplotlib. solid_capstyle=None. **kwargs) Bases: matplotlib. solid_joinstyle=None.3 matplotlib. markevery=None. or a tuple of [left. drawstyle=None. markersize=None. pickradius=5. markers and colors. fillstyle=’full’. height] in the given transform (normalized axes coordinate if None). ydata. linestyle=None.Text instance in the legend get_title() return Text instance for the legend title get_window_extent() return a extent of the the legend set_bbox_to_anchor(bbox. and a marker at each vertex. bottom. markerfacecolor=None. markeredgewidth=None. class matplotlib. dash_joinstyle=None.0. color=None. bbox can be a BboxBase instance. markerfacecoloralt=’none’. Additionally. bottom] where the width and height will be assumed to be zero.1 get_frame() return the Rectangle instance used to frame the legend get_frame_on() Get whether the legend box patch is drawn get_lines() return a list of lines. 35.3. Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. The kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder Description unknown float (0. Release 1.transforms. stride) float distance in points or callable pick function fn(artist. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.1 Create a Line2D instance with x and y data in sequences xdata.Bbox instance [True | False] [ (Path.figure. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.Matplotlib.’ | ’. ydata.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. matplotlib artists .0 transparent through 1.0. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Transform instance a url string [True | False] 1D array 1D array any number 340 Chapter 35.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.transforms. Matplotlib. TODO: sort returned indices by distance draw(artist.0. ydata. The pick radius determines the precision of the location test (usually within five points of the value). return the original data get_drawstyle() get_fillstyle() return the marker fillstyle get_linestyle() get_linewidth() get_ls() alias for get_linestyle get_lw() alias for get_linewidth get_marker() get_markeredgecolor() get_markeredgewidth() get_markerfacecolor() pointlist}. Returns True if any values are within the radius along with {’ind’: pointlist is the set of points within the radius. If orig is True. renderer. and set_drawstyle() for a description of the draw styles.1 See set_linestyle() for a decription of the line styles. **kwargs) get_aa() alias for get_antialiased get_antialiased() get_c() alias for get_color get_color() get_dash_capstyle() Get the cap style for dashed linestyles get_dash_joinstyle() Get the join style for dashed linestyles get_data(orig=True) Return the xdata.lines 341 . Release 1.3. set_marker() for a description of the markers. contains(mouseevent) Test whether the mouse event occurred on the line. *args. where 35. matplotlib. Use get_pickradius() or set_pickradius() to view or modify it. return the original data. matplotlib artists . else the processed data. get_ydata(orig=True) Return the ydata. else the processed data.Matplotlib. get_pickradius() return the pick radius used for containment tests get_solid_capstyle() Get the cap style for solid linestyles get_solid_joinstyle() Get the join style for solid linestyles get_window_extent(renderer) get_xdata(orig=True) Return the xdata.1 get_markerfacecoloralt() get_markersize() get_markevery() return the markevery setting get_mec() alias for get_markeredgecolor get_mew() alias for get_markeredgewidth get_mfc() alias for get_markerfacecolor get_mfcalt(alt=False) alias for get_markerfacecoloralt get_ms() alias for get_markersize get_path() Return the Path object associated with this line. return the original data.0. Release 1. If orig is True. get_xydata() Return the xy data as a Nx2 numpy array. If orig is True. is_dashed() return True if line is dashstyle recache(always=False) recache_always() set_aa(val) alias for set_antialiased 342 Chapter 35. ‘steps’ is equivalent to ‘steps-pre’ and is maintained for backward-compatibility. y) or two 1D arrays set_drawstyle(drawstyle) Set the drawstyle of the plot ‘default’ connects the points with lines. Release 1.0. If seq is empty or if seq = (None. sequence of dashes with on off ink in points. ACCEPTS: an Axes instance set_c(val) alias for set_color set_color(color) Set the color of the line ACCEPTS: any matplotlib color set_dash_capstyle(s) Set the cap style for dashed linestyles ACCEPTS: [’butt’ | ‘round’ | ‘projecting’] set_dash_joinstyle(s) Set the join style for dashed linestyles ACCEPTS: [’miter’ | ‘round’ | ‘bevel’] set_dashes(seq) Set the dash sequence. None). ACCEPTS: sequence of on/off ink in points set_data(*args) Set the x and y data ACCEPTS: 2D array (rows are x. The other options are for half filled markers ACCEPTS: [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] set_linestyle(linestyle) Set the linestyle of the line (also accepts drawstyles) 35.3.lines 343 . ‘full’ means fill the whole marker. matplotlib. ACCEPTS: [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] set_fillstyle(fs) Set the marker fill style. if any.Matplotlib.1 set_antialiased(b) True if line should be drawin with antialiased rendering ACCEPTS: [True | False] set_axes(ax) Set the Axes instance in which the artist resides. the linestyle will be set to solid. The steps variants produce step-plots. ’ ’:’ ’None’ ’ ’ ” description solid dashed dash_dot dotted draw nothing draw nothing draw nothing ‘steps’ is equivalent to ‘steps-pre’ and is maintained for backward-compatibility. e. ’steps--’.0.’ ’o’ ’v’ ’^’ ’<’ ’>’ ’1’ ’2’ ’3’ ’4’ ’s’ ’p’ ’*’ ’h’ ’H’ ’+’ ’x’ description point pixel circle triangle_down triangle_up triangle_left triangle_right tri_down tri_up tri_left tri_right square pentagon star hexagon1 hexagon2 plus x Continued on next page Chapter 35. ACCEPTS: [ ’-’ | ’--’ | ’-. matplotlib artists 344 . See Also: set_drawstyle() To set the drawing style (stepping) of the plot. Release 1.g.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a linestyle. set_linewidth(w) Set the line width in points ACCEPTS: float value in points set_ls(val) alias for set_linestyle set_lw(val) alias for set_linewidth set_marker(marker) Set the line marker marker ’.Matplotlib.’ ’.1 linestyle ’-’ ’--’ ’-. 1 Table 35.$’] set_markeredgecolor(ec) Set the marker edge color ACCEPTS: any matplotlib color set_markeredgewidth(ew) Set the marker edge width in points ACCEPTS: float value in points set_markerfacecolor(fc) Set the marker face color.3. ACCEPTS: any matplotlib color set_markerfacecoloralt(fc) Set the alternate marker face color.0.’ | ’.. Release 1. ACCEPTS: any matplotlib color set_markersize(sz) Set the marker size in points ACCEPTS: float 35.$’ render the string using mathtext ACCEPTS: [ ’+’ | ’*’ | ’.’ ’1’ | ’2’ | ’3’ | ’4’ ’<’ | ’>’ | ’D’ | ’H’ ’^’ | ’_’ | ’d’ | ’h’ ’o’ | ’p’ | ’s’ | ’v’ ’x’ | ’|’ TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT CARETUP | CARETDOWN | CARETLEFT | CARETRIGHT ’None’ | ’ ’ | ” | ’$..Matplotlib..lines 345 .2 – continued from previous page ’D’ diamond ’d’ thin_diamond ’|’ vline ’_’ hline TICKLEFT tickleft TICKRIGHT tickright TICKUP tickup TICKDOWN tickdown CARETLEFT caretleft CARETRIGHT caretright CARETUP caretup CARETDOWN caretdown ’None’ nothing ’ ’ nothing ” nothing ‘$. matplotlib.. Eg if markevery=5.Transform instance set_xdata(x) Set the data np.array for x ACCEPTS: 1D array set_ydata(y) Set the data np. every 5-th marker will be plotted.Matplotlib. event) set_pickradius(d) Sets the pick radius used for containment tests ACCEPTS: float distance in points set_solid_capstyle(s) Set the cap style for solid linestyles ACCEPTS: [’butt’ | ‘round’ | ‘projecting’] set_solid_joinstyle(s) Set the join style for solid linestyles ACCEPTS: [’miter’ | ‘round’ | ‘bevel’] set_transform(t) set the Transformation instance used by this artist ACCEPTS: a matplotlib. Release 1. stride) set_mec(val) alias for set_markeredgecolor set_mew(val) alias for set_markeredgewidth set_mfc(val) alias for set_markerfacecolor set_mfcalt(val) alias for set_markerfacecoloralt set_ms(val) alias for set_markersize set_picker(p) Sets the event picker details for the line. matplotlib artists . ACCEPTS: float distance in points or callable pick function fn(artist. every can be None Every point will be plotted an integer N Every N-th marker will be plotted starting with marker 0 A length-2 tuple of integers every=(start.array for y ACCEPTS: 1D array 346 Chapter 35.1 set_markevery(every) Set the markevery property to subsample the plot when using markers.transforms.0. N) will start at point start and plot every N-th marker ACCEPTS: None | integer | (startind. ys) self.patches.VertexSelector.random.patches class matplotlib. xs and ys are the coordinates of the selected vertices.markers. **kwargs): lines.Line2D instance.Axes instance and should have the picker property set.set_data(xs.Matplotlib.segment_hits(cx. Because it performs various optimizations. Release 1. 30) line.plot([].figure() ax = fig.lines.0. theta2=360. 35.0.__init__(self. = self. []. theta1=0. height. **kwargs) def process_selected(self.canvas. picker=5) selector = HighlightSelected(line) plt. fmt=’ro’. y = np. onpick(event) When the line is picked.plot(x. radius) Determine if any line segments are within radius of a point.0. line) self. = ax. ind.4. ys): self. An elliptical arc. Derived classes should override process_selected() to do something with the picks. it can not be filled. **kwargs) Bases: matplotlib.VertexSelector): def __init__(self. cy.1 update_from(other) copy properties from other to self class matplotlib.4 matplotlib. y.add_subplot(111) x.rand(2.VertexSelector(line) Manage the callbacks to maintain a list of selected vertices for matplotlib. process_selected(ind.patches 347 .Arc(xy. ys) Default “do nothing” implementation of the process_selected() method. line.markers.lines.lines as lines class HighlightSelected(lines. matplotlib. Here is an example which highlights the selected verts with red circles: import numpy as np import matplotlib. matplotlib.Ellipse angle=0.axes. ’bs-’. 35.lines.show() Initialize the class with a matplotlib. xs.patches.pyplot as plt import matplotlib. width. xs.axes.lines.draw() fig = plt. Returns the list of line segments that are within that radius. ind are the indices of the selected vertices. x. The line should already be added to some matplotlib. fmt.Line2D. y.0. update the set of selected indicies. or None for default. or ‘none’ for no color mpl color spec.transforms. The following args are supported: xy center of ellipse width length of horizontal axis height length of vertical axis angle rotation in degrees (anti-clockwise) theta1 starting angle of the arc in degrees theta2 ending angle of the arc in degrees If theta1 and theta2 are not provided. the arc will form a complete ellipse. or ‘none’ for no color a matplotlib.1 The arc must be used in an Axes instance—it can not be added directly to a Figure—because it is optimized to only render the segments that are inside the axes bounding box with high resolution. Release 1.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. *args.0.figure. or None for default. Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. The 348 Chapter 35.Matplotlib.Bbox instance [True | False] [ (Path. renderer. matplotlib artists . **kwargs) Ellipses are normally drawn using an approximation that uses eight cubic bezier splines.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number draw(artist. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. according to this unverified source: Lancaster. in the case where either radius of the ellipse is large enough that the error of the spline approximation will be visible (greater than one pixel offset from the ideal).arc(). http://www. In that case. with each visible arc using a fixed number of spline segments (8). Draws an arrow.Proceeding counterclockwise starting in the positive x-direction.tinaja. London: Springer-Verlag.Path. This uses the “line intersecting a circle” algorithm from: Vince.4. Release 1. Examples & Proofs.patches.The angles of each of the intersection points are calculated. Don. Geometry for Computer Graphics: Formulae. y).Arrow(x. 2005. dy. starting at (x.patches. The algorithm proceeds as follows: 1.0. direction and length given by (dx. dy) the width of the arrow is scaled by width. a different technique is used. John.0. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines.com/glib/ellipse4. dx.pdf There is a use case where very large ellipses must be drawn with very high accuracy. Therefore. width=1. matplotlib. y. (This is done be performing an inverse transformation on the axes bbox such that it is relative to the unit circle – this makes the intersection calculation much easier than doing rotated ellipse intersection directly). 2.89818e-6. only the visible parts of the ellipse are drawn. 3. class matplotlib. and it is too expensive to render the entire ellipse with enough segments (either splines or line segments).Matplotlib. each of the visible arcsegments between the pairs of vertices are drawn using the bezier arc approximation technique implemented in matplotlib.The points where the ellipse intersects the axes bounding box are located.1 error of this approximation is 1. Valid kwargs are: 35.path. **kwargs) Bases: matplotlib.Patch An arrow patch.patches 349 . 4.Matplotlib. or ‘none’ for no color mpl color spec._Style ArrowStyle is a container class which defines several arrowstyle classes. matplotlib artists .4.4") 350 Chapter 35.0.figure. head_length=. or None for default.4.patches.patches.transforms.4. head_width=. tail_width=. or ‘none’ for no color a matplotlib.4. tail_width=.ArrowStyle Bases: matplotlib. Release 1. head_width=.Fancy(head_length=. These are mainly used with FancyArrowPatch.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder get_patch_transform() get_path() Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.4.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. tail_width=. A arrowstyle object can be either created as: ArrowStyle.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib. or None for default.4) or: ArrowStyle("Fancy. head_length=.Bbox instance [True | False] [ (Path. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.4) or: ArrowStyle("Fancy". head_width=. which is used to create an arrow path along a given path. head_width=0. widthA width of the bracket lengthA length of the bracket 35.lengthB=0.2 ]]-[ fancy simple wedge |-| widthA=1.patches 351 . This is meant to be used to correct the location of the head so that it does not overshoot the destination point. but not all classes support it. Release 1.Matplotlib.0.patches.lengthB=0.patches.4.4.head_width=0.0._Bracket An arrow with a bracket(]) at both ends.head_width=0.angleB=None An instance of any arrow style class is an callable object.2 tail_width=0.4.lengthA=0.lengthA=0.angleB=None head_length=0.) and it returns a tuple of a Path instance and a boolean value.0.BracketA(widthA=1.4.5. linewidth.0.4. linewidth is a line width to be stroked. path.2 head_length=0. angleA=None. widthB=1.4.5.angleA=None widthA=1.2.widthB=1. angleA=None) Bases: matplotlib.3.angleA=None.2.2 head_length=0.angleB=None head_length=0.4 head_length=0. aspect_ratio=1.head_width=0.angleA=None. mutation_size.20000000000000001.tail_width=0.0. angleB=None) Bases: matplotlib. path is a Path instance along witch the arrow will be drawn.head_width=0. mutation_size and aspect_ratio has a same meaning as in BoxStyle.4.1 The following classes are defined Class Curve CurveB BracketB CurveFilledB CurveA CurveAB CurveFilledA CurveFilledAB BracketA BracketAB Fancy Simple Wedge BarAB Name -> -[ -|> <<-> <|Attrs None head_length=0.0. matplotlib.head_width=0.0.widthB=1.4. class BarAB(widthA=1.tail_width=0.0.0.2 widthB=1.2 head_length=0.5 widthA=1.2 <|-|> head_length=0. whose call signature is: __call__(self.head_width=0. widthA width of the bracket lengthA length of the bracket angleA angle between the bracket and the line widthB width of the bracket lengthB length of the bracket angleB angle between the bracket and the line class ArrowStyle.2. lengthA=0.head_width=0.2.shrink_factor=0._Bracket An arrow with a bracket(]) at its end.4.0. 0.> <|- <|-| > ]]-[ fancy simple wedge |-| 352 Chapter 35. matplotlib artists .Matplotlib. Release 1.1 -> -[ -| > <<. lengthA=0.40000000000000002.patches. head_width=0.CurveB(head_length=0. angleB=None) Bases: matplotlib.patches 353 .1 angleA angle between the bracket and the line class ArrowStyle. head_width=0.0. 35.4.CurveA(head_length=0.0. angleA=None._Bracket An arrow with a bracket([) at its end.CurveAB(head_length=0.40000000000000002._Curve An arrow with a head at its end point.0.BracketAB(widthA=1._Curve An arrow with heads both at the begin and the end point.0.patches. lengthB=0.patches.20000000000000001. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.20000000000000001.20000000000000001) Bases: matplotlib.patches. matplotlib.40000000000000002.BracketB(widthB=1. head_length length of the arrow head head_width width of the arrow head class ArrowStyle. widthA width of the bracket lengthA length of the bracket angleA angle between the bracket and the line widthB width of the bracket lengthB length of the bracket angleB angle between the bracket and the line class ArrowStyle.patches. class ArrowStyle._Curve An arrow with a head at its begin point.20000000000000001.patches. head_width=0._Bracket An arrow with a bracket(]) at both ends._Curve A simple curve without any arrow head.20000000000000001) Bases: matplotlib.Curve Bases: matplotlib. widthB=1.20000000000000001) Bases: matplotlib. lengthB=0. Release 1.Matplotlib. angleB=None) Bases: matplotlib. widthB width of the bracket lengthB length of the bracket angleB angle between the bracket and the line class ArrowStyle. 40000000000000002.patches. Only works with a quadratic bezier curve._Curve An arrow with filled triangle head at the end. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.Simple(head_length=0. head_width=0._Curve An arrow with filled triangle heads both at the begin and the end point.40000000000000002) Bases: matplotlib. linewidth) class ArrowStyle.1 head_length length of the arrow head head_width width of the arrow head class ArrowStyle.40000000000000002. tail_width=0. head_length length of the arrow head head_width width of the arrow head class ArrowStyle._Base A simple arrow.20000000000000001) Bases: matplotlib.20000000000000001) Bases: matplotlib.patches.5. head_width=0. tail_width=0. matplotlib artists .CurveFilledAB(head_length=0.patches.Matplotlib.patches.CurveFilledB(head_length=0._Curve An arrow with filled triangle head at the begin.40000000000000002. head_length length of the arrow head head_with width of the arrow head tail_width width of the arrow tail head_width=0.40000000000000002.0. Only works with a quadratic bezier curve. mutation_size.CurveFilledA(head_length=0.Fancy(head_length=0.patches.20000000000000001) Bases: matplotlib.40000000000000002. Release 1. head_length length of the arrow head head_with width of the arrow head tail_width width of the arrow tail transmute(path._Base A fancy arrow. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.5. 354 Chapter 35.20000000000000001) Bases: matplotlib. head_width=0. head_width=0. A style object can be created as: BoxStyle. linewidth) class matplotlib.0. pad=0. which are used for FancyBoxPatch.29999999999999999) Bases: matplotlib. width.4.patches. mutation_aspect determines the aspect-ratio of the mutation.3 pad=0. The begin point has a width of the tail_width and the end point has a width of 0.2") Following boxstyle classes are defined.Matplotlib.Wedge(tail_width=0.3 An instance of any boxstyle class is an callable object.3. y0.3.2) or: BoxStyle("Round". mutation_size.2) or: BoxStyle("Round.patches.BoxStyle Bases: matplotlib. x0.29999999999999999. tail_width width of the tail shrink_factor fraction of the arrow width at the middle point transmute(path.3. aspect_ratio=1. the width is shrink_factor*tail_width. Release 1. shrink_factor=0. matplotlib._Base 35.1 transmute(path. height. pad=0. mutation_size.patches.rounding_size=None pad=0.3.patches 355 .patches. mutation_size. whose call signature is: __call__(self. mutation_scale determines the overall size of the mutation (by which I mean the transformation of the rectangle to the fancy box).Round(pad=0. class LArrow(pad=0. Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0. y0. linewidth) class ArrowStyle.3 pad=0.5) Bases: matplotlib._Style BoxStyle is a container class which defines several boxstyle classes.rounding_size=None pad=0. width and height specify the location and size of the box to be drawn. Only wokrs with a quadratic bezier curve._Base Wedge(?) shape.tooth_size=None pad=0.) and returns a Path instance.tooth_size=None pad=0. x0. At the middle. Release 1.1 square sawtooth roundtooth rarrow larrow round4 round 356 Chapter 35.Matplotlib. matplotlib artists .0. rounding_size=None) Bases: matplotlib.Round4(pad=0. width. y0. y0.1 (left) Arrow Box transmute(x0.patches 357 .29999999999999999.patches.patches.29999999999999999) Bases: matplotlib.29999999999999999.patches._Base Another box with round edges. y0.Square(pad=0. mutation_size) class BoxStyle. pad if None transmute(x0.29999999999999999.LArrow (right) Arrow Box transmute(x0.Sawtooth(pad=0. height. pad amount of padding tooth_size size of the sawtooth. y0. tooth_size=None) Bases: matplotlib.patches. width.0.RArrow(pad=0.Roundtooth(pad=0. pad amount of padding rounding_size rounding size of edges. mutation_size) class BoxStyle. width. y0. height. mutation_size) class BoxStyle._Base A box with round corners. mutation_size) class BoxStyle.4. width.Matplotlib. width.patches. mutation_size) class BoxStyle.29999999999999999. mutation_size) class BoxStyle._Base A simple square box.Round(pad=0. y0.patches. pad amount of padding 35. tooth_size=None) Bases: matplotlib. pad if None transmute(x0._Base A sawtooth box. pad* if None transmute(x0. height. height. Release 1. matplotlib. rounding_size=None) Bases: matplotlib. pad amount of padding tooth_size size of the sawtooth.Sawtooth A roundtooth(?) box. pad amount of padding rounding_size rounding radius of corners.29999999999999999) Bases: matplotlib. height. width. height. pad* if None transmute(x0. Ellipse A circle patch.Bbox instance [True | False] [ (Path. y0. or None for default.0. y) with given radius. mutation_size) class matplotlib.figure. Unlike CirclePolygon which is a polygonal approximation.patches. **kwargs) Bases: matplotlib. radius=5. this uses Bézier splines and is much closer to a scale-free circle.Circle(xy. Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. Create true circle at center xy = (x. Release 1.Matplotlib. height.patches.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. matplotlib artists .1 transmute(x0.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number get_radius() return the radius of the circle radius return the radius of the circle set_radius(radius) Set the radius of the circle ACCEPTS: float 358 Chapter 35. or ‘none’ for no color a matplotlib.transforms. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. width. or ‘none’ for no color mpl color spec. or None for default. Create a circle at xy = (x. 35. arrowstyle=’-‘. xyB. Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. arrow_transmuter=None. clip_on=False.0. radius=5.0. coordsB=None.1 class matplotlib. y) with given radius.patches. coordsA.Matplotlib. or None for default. dpi_cor=1. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. patchB=None. see Circle. axesB=None.FancyArrowPatch A ConnectionPatch class is to make connecting lines between two points (possibly in different axes). Release 1. shrinkA=0. This circle is approximated by a regular polygon with resolution sides.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib.patches. connectionstyle=’arc3’. mutation_scale=10. For a smoother circle drawn with splines. connector=None.patches 359 .0. **kwargs) Bases: matplotlib. axesA=None. resolution=20.patches. shrinkB=0.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. mutation_aspect=None.ConnectionPatch(xyA.CirclePolygon(xy. matplotlib. or ‘none’ for no color mpl color spec.0. **kwargs) Bases: matplotlib. or ‘none’ for no color a matplotlib.4. patchA=None. or None for default.transforms.patches.figure.0.Bbox instance [True | False] [ (Path.RegularPolygon A polygon-approximation of a circle patch. matplotlib artists . you do not need to specify polar for the coordinate system since that is the native “data” coordinate system. get_path_in_displaycoord() Return the mutated path of the arrow in the display coord 360 Chapter 35.PathPatch coordsA and coordsB are strings that indicate the coordinates of xyA and xyB. Release 1. 0. draw(renderer) Draw.1 is upper right use the coordinate system of the object being annotated (default) Specify an offset (in points) from the xy value you can specify theta. any key for matplotlib. See set_annotation_clip() for the meaning of return values. r for the annotation. Property ‘figure points’ ‘figure pixels’ ‘figure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘offset points’ ‘polar’ Description points from the lower left corner of the figure pixels from the lower left corner of the figure 0.Matplotlib.patches. even in cartesian plots. get_annotation_clip() Return annotation_clip attribute.1 Connect point xyA in coordsA with point xyB in coordsB Valid keys are Key arrowstyle connectionstyle relpos patchA patchB shrinkA shrinkB mutation_scale mutation_aspect ? Description the arrow style the connection style default is (0. Note that if you are using a polar axes.0. right points from lower left corner of axes pixels from lower left corner of axes 0.1 is upper.5) default is bounding box of the text default is None default is 2 points default is 2 points default is text size (in points) default is 1.0 is lower left of figure and 1.5.1 is lower left of axes and 1. y coordinates of the two points to be connected. shrinkB=2.) and it returns a Path instance.xy is inside the axes. •False : the annotation will always be drawn regardless of its position. •True : the annotation will only be drawn when self.0. class Angle(angleA=90. shrinkA=2. the returned path is clipped so that it start (or end) from the boundary of the patch.0 angleA=90.rad=0. patchA=None. patchA (or patchB) is given.1 set_annotation_clip(b) set annotation_clip attribute. patchB=None. The connecting edges are rounded with rad. A connectionstyle object can be either created as: ConnectionStyle.0 rad=0. Release 1. posB.armB=None. posA.patches.Arc3(rad=0.armB=0. which is used to create a path between two points.4.angleB=0.2) or: ConnectionStyle("Arc3".angleB=0 angleA=0.0 armA=0.0. rad=0. •None : the self.Matplotlib.fraction=0. rad=0.ConnectionStyle Bases: matplotlib. rad=0.0.xy will be checked only if xycoords is “data” class matplotlib. matplotlib._Style ConnectionStyle is a container class which defines several connectionstyle classes. posA and posB are tuples of x. whose call signature is: __call__(self.2") The following classes are defined Class Angle Angle3 Arc Arc3 Bar Name angle angle3 arc arc3 bar Attrs angleA=90.patches.angleB=0..rad=0. angleA starting angle of the path angleB ending angle of the path rad rounding radius of the edge 35.angle=None An instance of any connection style class is an callable object. The path is further shrunk by shrinkA (or shrinkB) which is given in points._Base Creates a picewise continuous quadratic bezier path between two points.2) or: ConnectionStyle("Arc3. These are mainly used with FancyArrowPatch. The path has a one passing-through point placed at the intersecting point of two lines which crosses the start (or end) point and has a angle of angleA (or angleB).patches 361 . angleB=0.patches.3.armA=None.0) Bases: matplotlib. Arc(angleA=0.29999999999999999. The length of armA is determined by (armA + fraction x AB distance). Release 1.0) Bases: matplotlib. angleB=0) Bases: matplotlib. posB) class ConnectionStyle. rad=0. The path can have two passing-through points. posB) class ConnectionStyle.Angle3(angleA=90.patches.patches.0) Bases: matplotlib. angleA starting angle of the path angleB ending angle of the path connect(posA.patches. angleA : starting angle of the path angleB : ending angle of the path armA : length of the starting arm armB : length of the ending arm rad : rounding radius of the edges connect(posA.Bar(armA=0.Arc3(rad=0. matplotlib artists . armB=0. posB) class ConnectionStyle._Base Creates a simple quadratic bezier curve between two points. a point placed at the distance of armA and angle of angleA from point A. One of the arm is extend so that they are connected in a right angle. angle : anlge of the connecting line (if None. parallel to A and B) connect(posA. Same for armB. armA : minimum length of armA armB : minimum length of armB fraction : a fraction of the distance between two points that will be added to armA and armB. posB) 362 Chapter 35.patches.0. angleB=0._Base Creates a simple quadratic bezier curve between two points. rad curvature of the curve. posB) class ConnectionStyle. armA=None._Base Creates a picewise continuous quadratic bezier path between two points. armB=None. connect(posA.0. fraction=0.1 connect(posA. another point with respect to point B.0. angle=None) Bases: matplotlib._Base A line with angle between A and B with armA and armB. The edges are rounded with rad. The curve is created so that the middle contol points (C1) is located at the same distance from the start (C0) and end points(C2) and the distance of the C1 to the line connecting C0-C2 is rad times the distance of C0-C2.Matplotlib. The middle control points is placed at the intersecting point of two lines which crosses the start (or end) point and has a angle of angleA (or angleB). Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. xy center of ellipse width total length (diameter) of horizontal axis height total length (diameter) of vertical axis angle rotation in degrees (anti-clockwise) Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder contains(ev) get_patch_transform() get_path() Return the vertices of the rectangle Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.figure. or ‘none’ for no color a matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 35. matplotlib.Patch A scale-free ellipse.1 class matplotlib.Bbox instance [True | False] [ (Path. Release 1. width.0.Matplotlib.0.patches 363 . or None for default.patches.4.patches. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. **kwargs) Bases: matplotlib. or ‘none’ for no color mpl color spec. or None for default. angle=0.Ellipse(xy. height.transforms. dy. shape=’full’.FancyArrow(x. head_width=None. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. head_starts_at_zero=False.001.Bbox instance [True | False] [ (Path. overhang=0. but lets you set head width and head height independently. or ‘none’ for no color mpl color spec. matplotlib artists . ‘left’.Matplotlib. the head starts being drawn at coordinate 0 instead of ending at coordinate 0. shape: [’full’. y.1 class matplotlib. Constructor arguments length_includes_head: True if head is counted in calculating the length. head_length=None.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. or None for default. or ‘none’ for no color a matplotlib.patches. Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. ‘right’] overhang: distance that the arrow is swept back (0 overhang means triangular shape).’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 364 Chapter 35. dx.transforms. Release 1. **kwargs) Bases: matplotlib.patches.Polygon Like Arrow. head_starts_at_zero: If True.figure. length_includes_head=False.0. or None for default. width=0. The connectionstyle describes how posA and posB are connected.patches 365 . mutation_aspect=None.5.tail_width=0.Patch A fancy arrow patch. arrowstyle=’simple’.2.2 head_length=0.5.head_width=0.3.rad=0.4.4 head_length=0.angleB=0 angleA=0. Release 1.patches.tail_width=0.4.0.head_width=0.angleA=None.lengthA=0.head_width=0.0. The following connection styles are available.0.angle=None The arrowstyle describes how the fancy arrow will be drawn.4.fraction=0. path=None.armA=None.5 widthA=1.angleB=0..armB=None.0 armA=0. mutation_scale=1. Class Angle Angle3 Arc Arc3 Bar Name angle angle3 arc arc3 bar Attrs angleA=90. shrinkA.2 ]]-[ fancy simple wedge |-| widthA=1. It can be an instance of the ConnectionStyle class (matplotlib.angleB=None head_length=0. or one of the ArrowStyle instance.2 head_length=0. dpi_cor=1.2.3. with optional comma-separated attributes.0.Matplotlib.angleB=None mutation_scale [a value with which attributes of arrowstyle] (e. a path connecting two point are created according to the connectionstyle.head_width=0. connector=None.ConnectionStlye) or a string of the connectionstyle name. arrow_transmuter=None.0.head_width=0.0.head_width=0. de35.lengthB=0.lengthA=0.head_width=0.2 head_length=0.lengthB=0.armB=0.0 angleA=90.angleB=None head_length=0.4. an arrow is drawn along this path and patchA.0. and shrinkB are ignored.0.0 rad=0.angleA=None. It can be string of the available arrowstyle names.widthB=1. head_length) will be scaled. connectionstyle=’arc3’. It draws an arrow using the :class:ArrowStyle.4. shrinkA=2.2 tail_width=0. If posA and posB is given. patchA=None.patches.2 <|-|> head_length=0. posB=None. patchB. Class Curve CurveB BracketB CurveFilledB CurveA CurveAB CurveFilledA CurveFilledAB BracketA BracketAB Fancy Simple Wedge BarAB Name -> -[ -|> <<-> <|Attrs None head_length=0. **kwargs) Bases: matplotlib. patchB=None.4.2 widthB=1.4. The path will be clipped with patchA and patchB and further shirnked by shrinkA and shrinkB.0. The optional attributes are meant to be scaled with the mutation_scale.FancyArrowPatch(posA=None.0.widthB=1.patches.0. matplotlib.1 class matplotlib. If path provided.2. An arrow is drawn along this resulting path using the arrowstyle parameter.4.4. with optional comma-separated attributes.shrink_factor=0.0.head_width=0. shrinkB=2.0.rad=0.angleA=None widthA=1.angleB=0.2.g. The following arrow styles are available. Mutation scale is not affected by this.1 fault=1.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number .transforms. or ‘none’ for no color mpl color spec. Release 1. or ‘none’ for no color a matplotlib. Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder draw(renderer) get_arrowstyle() Return the arrowstyle object get_connectionstyle() Return the ConnectionStyle instance get_dpi_cor() dpi_cor is currently used for linewidth-related things and shink factor. 366 Chapter 35.0. mutation_aspect [The height of the rectangle will be] squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. or None for default. matplotlib artists Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Matplotlib.figure. get_mutation_aspect() Return the aspect ratio of the bbox mutation.Bbox instance [True | False] [ (Path. or None for default. return available styles as a list of strings. ACCEPTS: float set_patchA(patchA) set the begin patch. **kw) Set the arrow style. posB) set the begin end end positions of the connecting path.2) Old attrs simply are forgotten. set_arrowstyle(“Fancy. Alternatively. get_path() return the path of the arrow in the data coordinate.rad=10”) gleA=0. matplotlib.rad=10) Old attrs simply are forgotten. Mutation scale is not affected by this. the attrs can be probided as keywords. Without argument (or with arrowstyle=None).0. ACCEPTS: float set_mutation_scale(scale) Set the mutation scale. set_mutation_aspect(aspect) Set the aspect ratio of the bbox mutation. set_connectionstyle(“arc”. Alternatively. Use get_path_in_displaycoord() method to retrieve the arrow path in the disaply coord. Use current vlaue if None. an- 35. arrowstyle can be a string with arrowstyle name with optional comma-separated attributes. get_path_in_displaycoord() Return the mutated path of the arrow in the display coord set_arrowstyle(arrowstyle=None.armA=30. the attrs can be provided as keywords.angleA=0. head_length=0. set_connectionstyle(“arc.head_length=0. set_patchB(patchB) set the begin patch set_positions(posA.2”) set_arrowstyle(“fancy”. set_dpi_cor(dpi_cor) dpi_cor is currently used for linewidth-related things and shink factor.patches 367 .4. Without argument (or with connectionstyle=None).1 get_mutation_scale() Return the mutation scale.Matplotlib.armA=30. connectionstyle can be a string with connectionstyle name with optional comma-separated attributes. **kw) Set the connection style. Release 1. return available box styles as a list of strings. set_connectionstyle(connectionstyle. Matplotlib.3 pad=0. default=1. bbox_transmuter=None. **kwargs) Bases: matplotlib.rounding_size=None pad=0.3.rounding_size=None pad=0. The transformation of the rectangle box to the fancy box is delegated to the BoxTransmuterBase and its derived classes. It can be a string of the style name with a comma separated attribute. width..FancyBboxPatch(xy.0.patches. default=None. xy = lower left corner width.Patch Draw a fancy box around a rectangle with lower left at xy*=(*x.tooth_size=None pad=0.3 pad=0. or an instance of BoxStyle.3. mutation_scale=1.g.3. y) with specified width and height. Following box styles are available.tooth_size=None pad=0.3. boxstyle=’round’. height.patches. height boxstyle determines what kind of fancy box will be drawn. Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0.3 mutation_scale : a value with which attributes of boxstyle (e.0.1 class matplotlib. pad) will be scaled. Valid kwargs are: 368 Chapter 35. mutation_aspect : The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. Release 1. mutation_aspect=None. FancyBboxPatch class is similar to Rectangle class. matplotlib artists . but it draws a fancy box around the rectangle. or ‘none’ for no color a matplotlib. get_mutation_scale() Return the mutation scale. or None for default.4. matplotlib.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder get_bbox() Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. get_path() Return the mutated path of the rectangle get_width() Return the width of the rectangle get_x() Return the left coord of the rectangle 35. or None for default.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number get_boxstyle() Return the boxstyle object get_height() Return the height of the rectangle get_mutation_aspect() Return the aspect ratio of the bbox mutation.Bbox instance [True | False] [ (Path.transforms. Release 1.0.figure.patches 369 . or ‘none’ for no color mpl color spec. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.Matplotlib. 3 pad=0. ACCEPTS: float set_mutation_scale(scale) Set the mutation scale. Alternatively. matplotlib artists . the attrs can be provided as keywords: set_boxstyle("round.h ACCEPTS: (left.3.rounding_size=None pad=0.b. it returns available box styles. Release 1. bottom.tooth_size=None pad=0. pad=0. **kw) Set the box style. width. height) set_boxstyle(boxstyle=None.w.rounding_size=None pad=0. Without argument (or with boxstyle = None).2") set_boxstyle("round". ACCEPTS: float set_width(w) Set the width rectangle ACCEPTS: float set_x(x) Set the left coord of the rectangle Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0.pad=0.3 370 Chapter 35.3 pad=0.1 get_y() Return the bottom coord of the rectangle set_bounds(*args) Set the bounds of the rectangle: l. ACCEPTS: [ Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square ] set_height(h) Set the width rectangle ACCEPTS: float set_mutation_aspect(aspect) Set the aspect ratio of the bbox mutation.Matplotlib.tooth_size=None pad=0.3.2) Old attrs simply are forgotten.3.0.3. boxstyle can be a string with boxstyle name with optional comma-separated attributes. ’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number contains(mouseevent) Test whether the mouse event occurred in the patch.Artist A patch is a 2D thingy with a face color and an edge color. linewidth.4.0.1 ACCEPTS: float set_y(y) Set the bottom coord of the rectangle ACCEPTS: float class matplotlib.Matplotlib.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. **kwargs) Bases: matplotlib.patches. or None for default.patches 371 . facecolor. 35. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. The following kwarg properties are supported Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.artist. or antialiased are None. or None for default. If any of edgecolor. fill=True. path_effects=None. facecolor=None.Bbox instance [True | False] [ (Path. antialiased=None. linestyle=None.Patch(edgecolor=None.transforms. color=None.figure. Release 1. or ‘none’ for no color mpl color spec. matplotlib. linewidth=None. or ‘none’ for no color a matplotlib. they default to their rc params setting. hatch=None. get_fill() return whether fill is set get_hatch() Return the current hatching pattern get_linestyle() Return the linestyle. get_patch_transform() get_path() Return the path of this patch get_path_effects() 372 Chapter 35. get_fc() Return the face color of the Patch. get_edgecolor() Return the edge color of the Patch. Release 1.0. Will be one of [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] get_lw() Return the line width in points. get_facecolor() Return the face color of the Patch. {} contains_point(point) Returns True if the given point is inside the path (transformed with its transform attribute). *args. get_antialiased() Returns True if the Patch is to be drawn with antialiasing. get_data_transform() get_ec() Return the edge color of the Patch.Matplotlib. get_ls() Return the linestyle. matplotlib artists . draw(artist. **kwargs) Draw the Patch to the given renderer. renderer.1 Returns T/F. get_extents() Return a Bbox object defining the axis-aligned extents of the Patch. fill return whether fill is set get_aa() Returns True if the Patch is to be drawn with antialiasing. Will be one of [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] get_linewidth() Return the line width in points. or None for default. To access the curves as curves.patches 373 . get_verts() Return a copy of the vertices used in this patch If the patch contains Bezier curves. use get_path(). ACCEPTS: float or None set_antialiased(aa) Set whether to use antialiased rendering ACCEPTS: [True | False] or None for default set_color(c) Set both the edgecolor and the facecolor.1 get_transform() Return the Transform applied to the Patch. the curves will be interpolated by line segments. set_edgecolor() For setting the edge or face color individually.4. get_window_extent(renderer=None) set_aa(aa) alias for set_antialiased set_alpha(alpha) Set the alpha tranparency of the patch.0. or ‘none’ for no color set_facecolor(color) Set the patch face color ACCEPTS: mpl color spec. ACCEPTS: matplotlib color spec See Also: set_facecolor().Matplotlib. matplotlib. Release 1. set_ec(color) alias for set_edgecolor set_edgecolor(color) Set the patch edge color ACCEPTS: mpl color spec. or ‘none’ for no color set_fc(color) alias for set_facecolor set_fill(b) Set whether to fill the patch ACCEPTS: [True | False] set_hatch(hatch) Set the hatching pattern hatch can be one of: 35. or None for default. SVG and Agg backends only. Release 1.Path object. update_from(other) Updates this Patch from the properties of other._Base class or its derivatives. **kwargs) Bases: matplotlib.Patch A general polycurve path patch. in which case all the specified hatchings are done.Matplotlib. Valid kwargs are: 374 Chapter 35.1 / \ | + x o O .path.patches. PDF.PathPatch(path.0.’ | ‘*’ ] set_linestyle(ls) Set the patch linestyle ACCEPTS: [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] set_linewidth(w) Set the patch linewidth in points ACCEPTS: float or None for default set_ls(ls) alias for set_linestyle set_lw(lw) alias for set_linewidth set_path_effects(path_effects) set path_effects. If same letter repeats.patheffect. * - diagonal hatching back diagonal vertical horizontal crossed crossed diagonal small circle large circle dots stars Letters can be combined. it increases the density of hatching of that pattern. Hatching is supported in the PostScript.patches. matplotlib artists . ACCEPTS: [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. class matplotlib. which should be a list of instances of matplotlib. path is a matplotlib. Bbox instance [True | False] [ (Path. **kwargs) Bases: matplotlib.patches 375 .0. Valid kwargs are: 35. closed=True.patches.Polygon(xy. or None for default.patches. If closed is True.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder See Also: Patch For additional kwargs get_path() Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. the polygon will be closed so the starting and ending points are the same.Patch A general polygon patch.transforms. or ‘none’ for no color mpl color spec.Matplotlib. or None for default. xy is a numpy array with shape Nx2. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.4. matplotlib.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.figure. Release 1.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib. or ‘none’ for no color a matplotlib. Rectangle(xy. 376 Chapter 35.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder See Also: Patch For additional kwargs get_closed() get_path() get_xy() set_closed(closed) set_xy(vertices) xy Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. height.Patch Draw a rectangle with lower left at xy = (x. width.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.0.patches. y) with specified width and height.transforms.patches. This property is provided for backward compatibility with matplotlib 0.Matplotlib.figure. New code should use get_xy() and set_xy() instead. **kwargs) Bases: matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Set/get the vertices of the polygon. or ‘none’ for no color a matplotlib.Bbox instance [True | False] [ (Path. or None for default. or None for default. Release 1. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.91. or ‘none’ for no color mpl color spec. matplotlib artists . class matplotlib.x only. Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.1 fill is a boolean indicating whether to fill the rectangle Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. or None for default. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Bbox instance [True | False] [ (Path. or None for default.figure.Matplotlib.transforms.0. or ‘none’ for no color mpl color spec. Release 1.4. or ‘none’ for no color a matplotlib.patches 377 . matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number contains(mouseevent) get_bbox() get_height() Return the height of the rectangle get_patch_transform() get_path() Return the vertices of the rectangle get_width() Return the width of the rectangle get_x() Return the left coord of the rectangle 35. patches. 378 Chapter 35. numVertices the number of vertices. numVertices.Matplotlib. orientation=0. bottom.patches. **kwargs) Bases: matplotlib. Release 1.h ACCEPTS: (left. matplotlib artists . height) set_height(h) Set the width rectangle ACCEPTS: float set_width(w) Set the width rectangle ACCEPTS: float set_x(x) Set the left coord of the rectangle ACCEPTS: float set_xy(xy) Set the left and bottom coords of the rectangle ACCEPTS: 2-item sequence set_y(y) Set the bottom coord of the rectangle ACCEPTS: float xy Return the left and bottom coords of the rectangle class matplotlib.Patch A regular polygon patch.0. y) of the center.1 get_xy() Return the left and bottom coords of the rectangle get_y() Return the bottom coord of the rectangle set_bounds(*args) Set the bounds of the rectangle: l.b.RegularPolygon(xy. orientation rotates the polygon (in radians). Valid kwargs are: radius=5. radius The distance from the center to each of the vertices. Constructor arguments: xy A length 2 tuple (x. width.w. **kwargs) Bases: matplotlib. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.patches.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. If None.patches 379 .1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder get_patch_transform() get_path() numvertices orientation radius xy Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. matplotlib. oy. Release 1.transforms. props. kwargs are 35. is a patch property update dictionary.Shadow(patch. ox. if not None. props=None. oy. the shadow will have have the same color as the face.Matplotlib. or ‘none’ for no color a matplotlib.figure. or ‘none’ for no color mpl color spec.patches.0.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib.Bbox instance [True | False] [ (Path. or None for default. or None for default.4.Patch Create a shadow of the given patch offset by ox. but darkened. Draw a wedge centered at x. then a partial wedge is drawn from inner radius r .Patch Wedge shaped patch. Valid kwargs are: 380 Chapter 35. or None for default. theta2.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.transforms.figure. y center with radius r that sweeps theta1 to theta2 (in degrees). or ‘none’ for no color a matplotlib. theta1.0. If width is given.patches. width=None.Bbox instance [True | False] [ (Path.patches. matplotlib artists . Release 1. r. or None for default. or ‘none’ for no color mpl color spec.Matplotlib. **kwargs) Bases: matplotlib. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder draw(renderer) get_patch_transform() get_path() Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.width to outer radius r.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib.Wedge(center. **kwargs) Bases: matplotlib.Matplotlib. matplotlib.patches. Constructor arguments: xytip (x.patches.4.transforms. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or None for default. y) location of arrow tip xybase (x.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib. or ‘none’ for no color mpl color spec. or ‘none’ for no color a matplotlib. frac=0.Bbox instance [True | False] [ (Path. width=4.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. Release 1. y) location the arrow base mid point figure The Figure instance (fig.0. xybase. This is an arrow that is defined in display space and has a tip at x1.YAArrow(figure.figure.patches 381 .Patch Yet another arrow class.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder get_path() Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. or None for default.10000000000000001. headwidth=12. y1 and a base at x2. xytip. y2.dpi) width The width of the arrow in points frac The fraction of the arrow length occupied by the head headwidth The width of the base of the arrow head in points 35. k) For line segment defined by (x1.Matplotlib.0.figure.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.bbox_artist(artist. y2) of the returned points is k. y1. y2. props=None. fill=True) This is a debug function to draw a rectangle around the bounding box returned by get_window_extent() of an artist. to test whether the artist is returning the correct bbox. or None for default. renderer. matplotlib.Bbox instance [True | False] [ (Path. y2) and the distance from (x2. or ‘none’ for no color a matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 382 Chapter 35. matplotlib artists .patches. props is a dict of rectangle props with the additional property ‘pad’ that sets the padding around the bbox in points. or ‘none’ for no color mpl color spec. renderer. color=’k’. y1) and (x2. x2. Release 1. to test whether the artist is returning the correct bbox.transforms. Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.patches.draw_bbox(bbox. matplotlib.1 Valid kwargs are: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder get_patch_transform() get_path() getpoints(x1. y2) return the points on the line that is perpendicular to the line and intersects (x2. trans=None) This is a debug function to draw a rectangle around the bounding box returned by get_window_extent() of an artist. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or None for default. arrowprops. **kwargs) Bases: matplotlib. and if textcoords = None. xy. annotation_clip=None.5. 0.Matplotlib. etc. class matplotlib.text Classes for including text in a figure. ie.PathPatch xycoords and textcoords are strings that indicate the coordinates of xy and xytext. shrink will shorten the arrow so the tip and base are shink percent of the distance d away from the endpoints.patches. shrink=0. (If xytext = None.polygon ? Valid keys for FancyArrowPatch are Key arrowstyle connectionstyle relpos patchA patchB shrinkA shrinkB mutation_scale mutation_aspect ? Description the arrow style the connection style default is (0. If d is the distance between the text and annotated point.0. y point xy with text s at x.text. xycoords=’data’. Valid keys for YAArow are Key width frac headwidth shrink Description the width of the arrow in points the fraction of the arrow length occupied by the head the width of the base of the arrow head in points oftentimes it is convenient to have the arrowtip and base a bit away from the text and point being annotated.05 is 5% any key for matplotlib. Rectangle.patches. is a dictionary of line properties (see matplotlib.. 35. defaults to xy.1 35. matplotlib.lines. easier. a YAArow patch instance is created and drawn. xytext=None._AnnotationBase A Text class to make annotating things in the figure. Release 1. any key for matplotlib.5.Annotation(s.Text. matplotlib. If the dictionary has a key arrowstyle. defaults to xycoords). Otherwise. if not None. Axes. textcoords=None. arrowprops=None.5) default is bounding box of the text default is None default is 2 points default is 2 points default is text size (in points) default is 1.5 matplotlib.text. y location xytext.Line2D) for the arrow that connects annotation to the point.text.text 383 . a FancyArrowPatch instance is created with the given dictionary and is drawn. Annotate the x. such as Figure. the annotation will always be drawn regardless of its position.Bbox instance [True | False] [ (Path. The default is None. Transform) | Patch | None ] 384 Chapter 35. the annotation will only be drawn when the xy is inside the axes. If a ‘points’ or ‘pixels’ option is specified.0 transparent through 1. Eg: # 10 points to the right of the left border of the axes and # 5 points below the top border xy=(10. Additional kwargs are Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path Description unknown float (0.transforms.1 is upper right use the coordinate system of the object being annotated (default) Specify an offset (in points) from the xy value you can specify theta. See Annotating Axes for more details. which behave as True only if xycoords is”data”. If False. values will be added to the bottom-left and if negative.0 is lower left of figure and 1. r for the annotation. Release 1. values will be subtracted from the top-right.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.-5). even in cartesian plots. right points from lower left corner of axes pixels from lower left corner of axes 0.1 Property ‘figure points’ ‘figure pixels’ ‘figure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘offset points’ ‘polar’ Description points from the lower left corner of the figure pixels from the lower left corner of the figure 0. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system.Matplotlib.1 is lower left of axes and 1.0. The annotation_clip attribute contols the visibility of the annotation when it goes outside the axes area. matplotlib artists . If True. Note that if you are using a polar axes.1 is upper. xycoords=’axes points’ You may use an instance of Transform or Artist. This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox. 35.Figure instance a matplotlib. renderer. matplotlib.0. update_positions(renderer) Update the pixel positions of the annotated point and the text. *args.font_manager.text 385 .Matplotlib.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.3 – continued from color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.1 Table 35. **kwargs) Draw the Annotation object to the given renderer. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number contains(event) draw(artist. set_figure(fig) update_bbox_position_size(renderer) Update the location and the size of the bbox. Release 1.5.figure. y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown 386 Chapter 35.OffsetFrom(artist.Matplotlib. multialignment=None. horizontalalignment=’left’.font_manager.0 transparent through 1. path_effects=None.FT2Font() FT2Font class matplotlib. linespacing=None.Figure instance a matplotlib. **kwargs) Bases: matplotlib.1 matplotlib. fontproperties=None. Valid kwargs are Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap Description unknown float (0.figure. Release 1.Artist Handle storing and drawing of text in window or data coordinates. verticalalignment=’baseline’.transforms. text=’‘.text. ref_coord. y with string text.text. unit=’points’) Bases: object get_unit() set_unit(unit) class matplotlib.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. y=0.text. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.artist.0.Text(x=0. rotation=None. Create a Text instance at x. rotation_mode=None.Bbox instance [True | False] [ (Path. matplotlib artists .0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. color=None. get_bbox_patch() Return the bbox Patch object.Matplotlib. get_color() Return the color of the text get_family() Return the list of font families used for font lookup get_font_properties() alias for get_fontproperties get_fontfamily() alias for get_family get_fontname() alias for get_name get_fontproperties() Return the FontProperties object get_fontsize() alias for get_size get_fontstretch() alias for get_stretch 35. draw(artist. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number contains(mouseevent) Test whether the mouse event occurred in the patch. Returns True or False. Returns None if the the FancyBboxPatch is not made. renderer. In the case of text.text 387 . **kwargs) Draws the Text object to the given renderer. a hit is true anywhere in the axis-aligned bounding-box containing the text. *args.4 – continued from [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.1 stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder Table 35. matplotlib.5.0. Release 1. Not intended to be human readable.1 get_fontstyle() alias for get_style get_fontvariant() alias for get_variant get_fontweight() alias for get_weight get_ha() alias for get_horizontalalignment get_horizontalalignment() Return the horizontal alignment as string. get_rotation() return the text angle as float in degrees get_rotation_mode() get text rotation mode get_size() Return the font size as integer get_stretch() Get the font stretch as a string or number get_style() Return the font style as string get_text() Get the text as string get_va() alias for getverticalalignment() get_variant() Return the font variant as a string get_verticalalignment() Return the vertical alignment as string. ‘bottom’ or ‘baseline’. 388 Chapter 35. ‘center’. get_name() Return the font name as string get_path_effects() get_position() Return the position of the text as a tuple (x. y) get_prop_tup() Return a hashable tuple of properties.0. ‘center’ or ‘right’. matplotlib artists . Will be one of ‘top’. but useful for backends who want to cache derived information about text (eg layouts) and need to know if the text has changed. Will be one of ‘left’. Release 1.Matplotlib. so you must use this kwarg if you want to call get_window_extent() prior to the first draw(). ACCEPTS: [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] 35. If no mathtext is present. If the latter. dpi defaults to self. matplotlib. determined by counting unescaped dollar signs. t. set_backgroundcolor(color) Set the background color of the text by updating the bbox.5. eg facecolor=’red’. For getting web page regions.text 389 . then the value that was used must be specified as the dpi argument. ACCEPTS: any matplotlib color set_bbox(rectprops) Draw a bounding box around self.0. ACCEPTS: rectangle prop dict set_color(color) Set the foreground color of the text ACCEPTS: any matplotlib color set_family(fontname) Set the font family. it is simpler to call the method after saving the figure. Each string may be either a real font name or a generic font class name.set_bbox(dict(facecolor=’red’. static is_math_text(s) Returns a cleaned string and a boolean flag. alpha=0. the cleaned string has its dollar signs unescaped. For the web application.5. If usetex is on. if figure. Release 1.1 get_weight() Get the font weight as string or number get_window_extent(renderer=None. See Also: set_bbox() To change the position of the bounding box. rectprops are any settable properties for a rectangle. renderer defaults to the _renderer attribute of the text object. The mutation scale of the FancyBboxPath is set to the fontsize. The flag indicates if the given string s contains any mathtext.Matplotlib. the renderer dpi is irrelevant. in display units.dpi.dpi is not the value used when saving the figure. This is not assigned until the first execution of draw(). this is useful for specifying clickable regions in a png file on a web page. In addition to being used internally. May be either a single string.5)) If rectprops has “boxstyle” key. A FancyBboxPatch is initialized with rectprops and will be drawn. dpi=None) Return a Bbox object bounding the text. the flag always has the value “TeX”. or a list of strings in decreasing priority. alpha=0.figure. the specific font names will be looked up in the matplotlibrc file. font_manager. y) position of the text 390 Chapter 35. Default is 1. matplotlib artists .0. but the multiline text within that box can be ACCEPTS: [’left’ | ‘right’ | ‘center’ ] set_name(fontname) alias for set_family set_path_effects(path_effects) set_position(xy) Set the (x.FontProperties object. text. The layout of the bounding box of all the lines is determined bu the horizontalalignment and verticalalignment properties.font_manager.Matplotlib.2. Release 1. fp must be a ACCEPTS: a matplotlib.1 set_font_properties(fp) alias for set_fontproperties set_fontname(fontname) alias for set_family set_fontproperties(fp) Set the font properties that control the matplotlib.FontProperties instance set_fontsize(fontsize) alias for set_size set_fontstretch(stretch) alias for set_stretch set_fontstyle(fontstyle) alias for set_style set_fontvariant(variant) alias for set_variant set_fontweight(weight) alias for set_weight set_ha(align) alias for set_horizontalalignment set_horizontalalignment(align) Set the horizontal alignment to one of ACCEPTS: [ ‘center’ | ‘right’ | ‘left’ ] set_linespacing(spacing) Set the line spacing as a multiple of the font size. ACCEPTS: float (multiple of font size) set_ma(align) alias for set_verticalalignment set_multialignment(align) Set the alignment for multiple lines layout. either ‘normal’ or ‘small-caps’. ACCEPTS: [ ‘normal’ | ‘small-caps’ ] set_verticalalignment(align) Set the vertical alignment ACCEPTS: [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] set_weight(weight) Set the font weight. ACCEPTS: [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultraexpanded’ ] set_style(fontstyle) Set the font style.5.Matplotlib. the text will be rotated first then will be aligned. ACCEPTS: string or anything printable with ‘%s’ conversion.1 ACCEPTS: (x.0.y) set_rotation(s) Set the rotation of the text ACCEPTS: [ angle in degrees | ‘vertical’ | ‘horizontal’ ] set_rotation_mode(m) set text rotation mode. Release 1. ACCEPTS: [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ] set_stretch(stretch) Set the font stretch (horizontal condensation or expansion). ACCEPTS: [ ‘normal’ | ‘italic’ | ‘oblique’] set_text(s) Set the text string s It may contain newlines (\n) or math in LaTeX syntax. ACCEPTS: [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ] 35.text 391 . If None (default). or an absolute font size in points. set_va(align) alias for set_verticalalignment set_variant(variant) Set the font variant. May be either a size string. the un-rotated text will first aligned according to their ha and va. and then will be rotated with the alignement reference point as a origin. relative to the default font size. matplotlib. set_size(fontsize) Set the font size. If “anchor”. This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox. major deviations in the rotation cause what may be considered visually unappealing results. or whether that’s sufficient for providing the object bounding box. the text alignment arguments (horizontalalignment.0). Hence the quality of the “centering” of the label text with respect to the dash varies depending on the backend used. multialignment=None. and should behave identically to it when dashlength = 0. (default = 0. the dash takes its rotation from the text’s rotation).text. Because the text center is projected onto the dash. When a dash exists.text.0. (default = None) dashpad is a padding length to add (or subtract) space between the text and the dash.Matplotlib. (default = 3) dashpush “pushes” the dash and text away from the point specified by set_position() by the amount in canvas units. appears to depend on the font metrics as given by the rendering backend. It is intended to be a drop-in replacement for Text. 392 Chapter 35. dashrotation=None. (I. (default = 0) Note: The alignment of the two objects is based on the bounding box of the Text. dashpad=3.0.e. where 0 draws the dash after the text and 1 before. dashrotation specifies the rotation of the dash. color=None. Release 1. horizontalalignment=’center’. (default = 0). verticalalignment=’center’. dashlength is the length of the dash in canvas units. dashdirection is one of 0 or 1. and should generally stay None. linespacing=None. This. update_from(other) Copy properties from other to self class matplotlib.TextWithDash(x=0.. in turn. dashpush=0) Bases: matplotlib. as obtained by get_window_extent().1 set_x(x) Set the x position of the text ACCEPTS: float set_y(y) Set the y position of the text ACCEPTS: float update_bbox_position_size(renderer) Update the location and the size of the bbox. rotation=None. y=0. draw(renderer) Draw the TextWithDash object to the given renderer. dashlength=0. fontproperties=None. The dash always comes between the point specified by set_position() and the text.0. matplotlib artists . in canvas units. Note: I’m not sure that I got the get_window_extent() right. text=’‘. verticalalignment) are ignored. dashdirection=0.Text This is basically a Text with a dash (drawn with a Line2D) before/after it. In this case get_dashrotation() returns get_rotation(). get_window_extent(renderer=None) Return a Bbox object bounding the text.1 get_dashdirection() Get the direction dash. ACCEPTS: int (1 is before. this is useful for specifying clickable regions in a png file on a web page. Not intended to be human readable. y) get_prop_tup() Return a hashable tuple of properties. in display units. For getting web page regions. matplotlib. 1 is before the text and 0 is after. get_dashpush() Get the extra spacing between the dash and the specified text position. so you must use this kwarg if you want to call get_window_extent() prior to the first draw().5.0. ACCEPTS: float (canvas units) set_dashpad(dp) Set the “pad” of the TextWithDash. 1 is before the text and 0 is after. which is what you’d want for the typical case of ticks below and on the left of the figure.Matplotlib. it is simpler to call the method after saving the figure. get_dashlength() Get the length of the dash. which is the extra spacing between the dash and the text.text 393 . in canvas units. set_dashdirection(dd) Set the direction of the dash following the text. renderer defaults to the _renderer attribute of the text object. get_figure() return the figure instance the artist belongs to get_position() Return the position of the text as a tuple (x. get_dashpad() Get the extra spacing between the dash and the text. 0 is after) set_dashlength(dl) Set the length of the dash. This is not assigned until the first execution of draw(). but useful for backends who want to cache derived information about text (eg layouts) and need to know if the text has changed. in canvas units. In addition to being used internally. Release 1. get_dashrotation() Get the rotation of the dash in degrees. in canvas units. ACCEPTS: float (canvas units) 35. The default is 0. y) position of the TextWithDash.0. ACCEPTS: a matplotlib. Release 1. ACCEPTS: float (canvas units) set_dashrotation(dr) Set the rotation of the dash. ‘vertical’.text.transforms.transforms. y and the dashlength. ACCEPTS: float update_coords(renderer) Computes the actual x. 394 Chapter 35.Transform instance set_x(x) Set the x position of the TextWithDash. y) set_transform(t) Set the matplotlib.1 set_dashpush(dp) Set the “push” of the TextWithDash. rotation may be ‘horizontal’.Figure instance set_position(xy) Set the (x. matplotlib artists . y coordinates for text based on the input x. or a numeric value in degrees. matplotlib. ACCEPTS: float set_y(y) Set the y position of the TextWithDash.figure. ACCEPTS: a matplotlib. which is the extra spacing between the beginning of the dash and the specified position.Matplotlib. in degrees ACCEPTS: float (degrees) set_figure(fig) Set the figure instance the artist belong to.get_rotation(rotation) Return the text angle as float.Transform instance used by this artist. ACCEPTS: (x. Since the rotation is with respect to the actual canvas’s coordinates we need to map back and forth. **kwargs) Return value is a tuple (lags. normed=True. detrend=mlab. normalize the data by the autocorrelation at 0-th lag. x is detrended by the detrend callable (default no normalization). acorr(x. Tick. maxlags=10. Data are plotted as plot(lags.CHAPTER THIRTYSIX MATPLOTLIB AXES 36.Artist The Axes contains most of the figure elements: Axis.axes class matplotlib.axes. If normed = True. vlines() rather than plot() is used to draw vertical lines from the origin to the acorr.Axes(fig. **kwargs) Plot the autocorrelation of x. etc. **kwargs) Bases: matplotlib. Line2D. yscale=None. Polygon. If usevlines is True. the plot style is determined by the kwargs. **kwargs) call signature: acorr(x. sharey=None.artist. maxlags is a positive integer detailing the number of lags to show. xscale=None. The events you can connect to are ‘xlim_changed’ and ‘ylim_changed’ and the callback will be called with func(ax) where ax is the Axes instance.. which are Line2D properties. The Axes instance supports callbacks through a callbacks attribute which is a CallbackRegistry instance. though these can be overridden with keyword args. frameon=True. axisbg=None. The default value of None will return all 2imeslen(x) − 1 lags.detrend_none. line) where: •lags are a length 2*maxlags+1 lag vector •c is the 2*maxlags+1 auto correlation vector •line is a Line2D instance returned by plot() The default linestyle is None and the default marker is ’o’. Otherwise. rect. c.correlate() with mode = 2. usevlines=True. sharex=None. label=’‘. and sets the coordinate system.1 matplotlib. Text. 395 . The cross correlation is performed with numpy. c. add_collection(collection.15 0. Returns the collection.15 0. c.6 0. matplotlib axes .00 0.10 0.0. autolim=True) Add a Collection instance to the axes. Example: 0. Release 1. linecol.2 0.05 0.0 0.05 0. See Also: plot() or vlines() For documentation on valid kwargs.2060 1. Returns the artist.4 0.8 0.0 0. b) where •linecol is the LineCollection •b is the x-axis. 396 Chapter 36. Example: xcorr() above.Matplotlib.1 The return value is a tuple (lags.260 40 20 0 20 40 60 40 20 0 20 40 60 add_artist(a) Add any Artist to the axes.20 0. and acorr() below.10 0. a FancyArrowPatch instance is created with the given dictionary and is drawn. it will be set to transData. matplotlib. the clipbox will be set to the Axes clipping box.1 add_line(line) Add a Line2D to the list of plot lines Returns the line. defaults to xy.Matplotlib. arrowprops=None. xytext=None. and if textcoords = None. xy. defaults to xycoords).patches. Returns the patch. is a dictionary of line properties (see matplotlib. add_patch(p) Add a Patch p to the list of axes patches. add_table(tab) Add a Table instance to the list of axes tables Returns the table. Release 1. xycoords=’data’. ie. arrowprops. annotate(*args.polygon ? Valid keys for FancyArrowPatch are 36. **kwargs) Keyword arguments: Annotate the x. if not None. If d is the distance between the text and annotated point. textcoords=’data’. y point xy with text s at x. shrink will shorten the arrow so the tip and base are shink percent of the distance d away from the endpoints. If the transform is not set. Otherwise.lines.1.05 is 5% any key for matplotlib. Valid keys for YAArow are Key width frac headwidth shrink Description the width of the arrow in points the fraction of the arrow length occupied by the head the width of the base of the arrow head in points oftentimes it is convenient to have the arrowtip and base a bit away from the text and point being annotated. If the dictionary has a key arrowstyle.0. a YAArow patch instance is created and drawn. **kwargs) call signature: annotate(s.Line2D) for the arrow that connects annotation to the point. shrink=0.axes 397 . (If xytext = None. y location xytext. which behave as True only if xycoords is”data”. matplotlib axes .1 is lower left of axes and 1.5. Note that if you are using a polar axes. The default is None. If False.Matplotlib. The annotation_clip attribute contols the visibility of the annotation when it goes outside the axes area.1 is upper right use the coordinate system of the object being annotated (default) Specify an offset (in points) from the xy value you can specify theta. Property ‘figure points’ ‘figure pixels’ ‘figure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘offset points’ ‘polar’ Description points from the lower left corner of the figure pixels from the lower left corner of the figure 0. r for the annotation.0. the annotation will always be drawn regardless of its position. 398 Chapter 36.-5). values will be subtracted from the top-right. If a ‘points’ or ‘pixels’ option is specified. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system. If True.patches. 0. values will be added to the bottom-left and if negative. any key for matplotlib. See Annotating Axes for more details. right points from lower left corner of axes pixels from lower left corner of axes 0. Eg: # 10 points to the right of the left border of the axes and # 5 points below the top border xy=(10.1 Key arrowstyle connectionstyle relpos patchA patchB shrinkA shrinkB mutation_scale mutation_aspect ? Description the arrow style the connection style default is (0.PathPatch xycoords and textcoords are strings that indicate the coordinates of xy and xytext. Release 1. the annotation will only be drawn when the xy is inside the axes. xycoords=’axes points’ You may use an instance of Transform or Artist.5) default is bounding box of the text default is None default is 2 points default is 2 points default is text size (in points) default is 1.0 is lower left of figure and 1.1 is upper. even in cartesian plots. y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.Figure instance a matplotlib.0 transparent through 1.transforms.figure. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number apply_aspect(position=None) Use _aspect() and _adjustable() to modify the axes box or the view limits. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.Matplotlib. 36.1 Additional kwargs are Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder Description unknown float (0.axes 399 .Bbox instance [True | False] [ (Path. matplotlib.1.font_manager.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.0. Release 1. Matplotlib.1 3 2 1 0 1 2 3 41 0 1 2 3 4 5 arc3 arc angle3 arrowstyle arc angle angle angle angle 3 2 1 0 1 2 3 4 51> − 400 fancy simple wedge wedge wedge 0 1 2 3 4 5 Chapter 36.0. matplotlib axes . Release 1. False turns it off. matplotlib. dx.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 36. if autoscaling for either axis is on. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or ‘none’ for no color a matplotlib.axes 401 . axis: [’x’ | ‘y’ | ‘both’] which axis to operate on. y + dy). or ‘none’ for no color mpl color spec. dy.Matplotlib. dy. or None for default. y.transforms. and then.1 arrow(x. or None for default.0. **kwargs) call signature: arrow(x. Release 1.Bbox instance [True | False] [ (Path. dx. enable: [True | False | None] True (default) turns autoscaling on. None leaves the autoscaling state unchanged. tight=None) Convenience method for simple axis view autoscaling. y) to (x + dx. default is ‘both’ Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.figure. axis=’both’. autoscale(enable=True. It turns autoscaling on or off.1. y. Optional kwargs control the arrow properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Example: Exception occurred rendering plot. it performs the autoscaling on the specified axis or axes. **kwargs) Draws arrow on specified axis from (x. let the locator and margins expand the view limits.0. •draw a thick red hline at y = 0 that spans the xrange >>> axhline(linewidth=4. The tight setting is retained for future autoscaling until it is explicitly changed.5 that spans the the middle half of the xrange >>> axhline(y=. Returns None. xmin=0. Eg. 0. color=’r’) •draw a default hline at y = 1 that spans the xrange >>> axhline(y=1) •draw a default hline at y = . scalex=True.25. if None.5. scaley=True) Autoscale the view limits using the data limits. xmax=1. regardless of the xlim settings. eg. autoscale_view(tight=None.axes. with the set_xlim() command. In that case. and can be used to control the line properties.5=middle. use tight scaling if the only artist is an image. with the exception of ‘transform’: Property agg_filter alpha animated antialiased or aa axes Description unknown float (0. You can selectively autoscale only a single axis. use matplotlib. otherwise treat tight as False. the xaxis by setting scaley to False. **kwargs) call signature: axhline(y=0. this line will always span the horizontal extent of the axes. The autoscaling preserves any axis direction reversal that has already been done. even if you change them. Release 1. if False.. xmin=0.0 transparent through 1. **kwargs) Axis Horizontal Line Draw a horizontal line at y from xmin to xmax. the horizontal extent is in axes coords: 0=left. eg.0 opaque) [True | False] [True | False] an Axes instance 402 Chapter 36. kwargs are the same as kwargs to plot.0=right but the y location is in data coordinates.1 tight: [True | False | None] If True.relim() prior to calling autoscale_view. xmin=0. set view limits to data limits. xmax=1. xmax=0. The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. matplotlib axes . axhline(y=0. Return value is the Line2D instance. With the default values of xmin = 0 and xmax = 1. That is.Matplotlib.Axes. 1.75) Valid kwargs are Line2D properties. ’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. Release 1. **kwargs) call signature: 36.axes 403 .1 clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder a matplotlib.Bbox instance [True | False] [ (Path. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. ymax.transforms.transforms.1.0.Transform instance a url string [True | False] 1D array 1D array any number See Also: axhspan() for example plot and source code axhspan(ymin.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. matplotlib. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.figure. stride) float distance in points or callable pick function fn(artist. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.Matplotlib. xmin=0. xmax=1.’ | ’.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. 75 that spans the horizontal extent of the axes >>> axhspan(0.75.figure. ymax. eg. xmax=1. the horizontal extent is in axes coords: 0=left.1 axhspan(ymin. regardless of the xlim settings. Examples: •draw a gray rectangle from y = 0.Bbox instance [True | False] [ (Path. With the default values of xmin = 0 and xmax = 1.25-0. or ‘none’ for no color mpl color spec. Return value is a matplotlib. or ‘none’ for no color a matplotlib.transforms.patches.5) Valid kwargs are Polygon properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.Polygon instance. this always spans the xrange.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.5’. 0. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. xmin=0. facecolor=’0.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 404 Chapter 36.25. Release 1. 0. with the set_xlim() command. **kwargs) Axis Horizontal Span. y coords are in data units and x coords are in axes (relative 0-1) units. or None for default. matplotlib axes . Draw a horizontal span (rectangle) from ymin to ymax.Matplotlib.0.0=right but the y location is in data coordinates. or None for default. even if you change them. 1. alpha=0. That is.5=middle. Return value is the Line2D instance. ymax=1.5 0.5 1. this line will always span the vertical extent of the axes.0 0. the vertical extent is in axes coords: 0=bottom. matplotlib.5 0.5 1.axes 405 . That is. With the default values of ymin = 0 and ymax = 1.0 0. ymin=0. Eg.Matplotlib. with the set_ylim() command.0 1. •draw a thick red vline at x = 0 that spans the yrange >>> axvline(linewidth=4. **kwargs) call signature: axvline(x=0. regardless of the ylim settings. eg.5 2. 1.1. color=’r’) 36.0. Release 1. **kwargs) Convenience method for manipulating the x and y view limits and the aspect ratio of the plot. kwargs are the same as kwargs to plot. kwargs are passed on to set_xlim() and set_ylim() axvline(x=0. ymax=1. **kwargs) Axis Vertical Line Draw a vertical line at x from ymin to ymax.01.0 0..0 axis(*v. even if you change them.5=middle.0 0. ymin=0.5 1. and can be used to control the line properties.0 1.1 Example: 2.0=top but the x location is in data coordinates. 0. ymax=0. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.0 transparent through 1.figure.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.0.Matplotlib.’ | ’. stride) float distance in points or callable pick function fn(artist. ymin=0.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. with the exception of ‘transform’: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform Description unknown float (0. matplotlib axes .1 •draw a default vline at x = 1 that spans the yrange >>> axvline(x=1) •draw a default vline at x = . Release 1. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.5.75) Valid kwargs are Line2D properties.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.transforms.Transform instance 406 Chapter 36. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Bbox instance [True | False] [ (Path.25.transforms.5 that spans the the middle half of the yrange >>> axvline(x=. 1. matplotlib. alpha=0.Polygon instance. Release 1.1.Matplotlib. eg. even if you change them. xmax. With the default values of ymin = 0 and ymax = 1. Return value is the matplotlib. ymax=1.25 to 1. ymin=0. 1. Draw a vertical span (rectangle) from xmin to xmax. x coords are in data units and y coords are in axes (relative 0-1) units. **kwargs) Axis Vertical Span. **kwargs) call signature: axvspan(xmin. That is. this always spans the yrange.5) Valid kwargs are Polygon properties: 36. with the set_ylim() command.0=top but the y location is in data coordinates. Examples: •draw a vertical green translucent rectangle from x=1.patches. 0. ymax=1. regardless of the ylim settings. ymin=0.55 that spans the yrange of the axes >>> axvspan(1. xmax.25.axes 407 . facecolor=’g’.0. the vertical extent is in axes coords: 0=bottom.5=middle.1 url visible xdata ydata zorder a url string [True | False] 1D array 1D array any number See Also: axhspan() for example plot and source code axvspan(xmin.55. **kwargs) call signature: bar(left. bottom=0.Matplotlib. width. bottom + height (left.Bbox instance [True | False] [ (Path. matplotlib axes . height.0. width=0. height. right.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.80000000000000004. width=0. Required arguments: 408 Chapter 36.transforms. or None for default.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder See Also: Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. Release 1.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number axhspan() for example plot and source code bar(left. and bottom can be either scalars or sequences Return value is a list of matplotlib. or ‘none’ for no color a matplotlib.Rectangle instances. height. bottom and top edges) left. or None for default. **kwargs) Make a bar plot with rectangles bounded by: left. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.8. bottom=None.figure. bottom. or ‘none’ for no color mpl color spec. left + width.patches. will be used to generate errorbars on the bar chart ecolor specifies the color of any errorbar cap(default 3) determines the length in points of the error bar caps size erdictionary of kwargs to be passed to errorbar method. 0 means don’t draw edges. Release 1. xerr if not None.Matplotlib. xerr.axes 409 . align ‘edge’ (default) | ‘center’ orien. will be used to generate errorbars on the bar chart yerr if not None. Other optional kwargs: 36. matplotlib.0. This enables you to use bar as the basis for stacked bar charts.1 Argument left height Description the x coordinates of the left sides of the bars the heights of the bars Optional keyword arguments: KeyDescription word width the widths of the bars botthe y coordinates of the bottom edges of the bars tom color the colors of the bars edge. or candlestick plots. so they can also have shape 2xN for independent specification of lower and upper errors. while align = ‘center’ interprets these values as the y coordinates of the bar centers. and yerr can be either scalars or sequences of length equal to the number of bars. linewidth. ecolor and capsize ror_kw may be specified here rather than as independent kwargs. edgecolor. Detail: xerr and yerr are passed directly to errorbar(). For horizontal bars.the colors of the bar edges color linewidthwidth of bar edges. while align = ‘center’ interprets these values as the x coordinates of the bar centers. align = ‘edge’ aligns bars by their bottom edges in bottom. align = ‘edge’ aligns bars by their left edges in left.1. True sets it to log scale For vertical bars. None means use default linewidth. The optional arguments color.‘vertical’ | ‘horizontal’ tation log [False|True] False (default) leaves the orientation axis as-is. Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. V: give the x and y components of the barb shaft C: an optional array used to map colors to the barbs All arguments may be 1-D or 2-D arrays or sequences. barb(X. **kw) Plot a 2-D field of barbs. barb(U. V. Y. barbs(*args. V.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.Matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Example: A stacked bar chart. C. Y: The x and y coordinates of the barb locations (default is head of barb. barb(X. Y. or None for default. V. **kw) U.figure. or ‘none’ for no color a matplotlib. they will be 410 Chapter 36. If X and Y are absent. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. **kw) U. **kw) C. V.0. see pivot kwarg) U. call signatures: barb(U.transforms.Bbox instance [True | False] [ (Path. **kw) Arguments: X. or ‘none’ for no color mpl color spec. or None for default. Release 1. matplotlib axes . If C has been set. V. This parameter is analagous to the edgecolor parameter for polygons.axes 411 . matplotlib.1.Matplotlib.1 80 70 60 50 Scores 40 30 20 10 0 G1 Scores by group and gender Men Women G2 G3 G4 G5 generated as a uniform grid. flagcolor has no effect.0. flagcolor: [ color | color sequence ] Specifies the color of any flags on the barb. but masked X. This parameter is analagous to the facecolor parameter for polygons. C may be masked arrays. the arrow rotates about this point. sizes: A dictionary of coefficients specifying the ratio of a given feature to the length of the barb. However this parameter will override facecolor. Only those values one wishes to override need to be included. Release 1. Default is 9 pivot: [ ‘tip’ | ‘middle’ ] The part of the arrow that is at the grid point. which can be used instead. If U and V are 2-D arrays but X and Y are 1-D. U. However this parameter will override facecolor. Default is ‘tip’ barbcolor: [ color | color sequence ] Specifies the color all parts of the barb except any flags. Keyword arguments: length: Length of the barb in points. Y are not supported at present.meshgrid(). then X and Y will be expanded with numpy. the other parts of the barb are scaled against this. If this is not set (and C has not either) then flagcolor will be set to match barbcolor so that the barb has a uniform color. and if len(X) and len(Y) match the column and row dimensions of U. hence the name pivot. which can be used instead. These 36. the magnitude is rounded to the nearest multiple of the half-barb increment. ever at most 1 half line. matplotlib axes . of course. If they are not filled.half barbs (Default is 5) • ‘full’ . Normal behavior is for the barbs and lines to point right (comes from wind barbs having these features point towards low pressure in the Northern Hemisphere. they will be drawn such that no color is applied to the center. the half-line is offset from the end of the barb so that it can be easily distinguished from barbs with a single full line. 10. If True.1 features include: • ‘spacing’ . but can technically be used to plot any two dimensional vector quantity.) Default is False Barbs are traditionally used in meteorology as a way to plot the speed and direction of wind observations.flags (default is 50) flip_barb: Either a single boolean flag or an array of booleans.height (distance from shaft to top) of a flag or full barb • ‘width’ . The smallest increment is a half line. as show schematically below: : /\ \ : / \ \ : / \ \ \ : / \ \ \ : ------------------------------ The largest increment is given by a triangle (or “flag”). If the magnitude is small and only needs a single half-line and no full lines or triangles.space between features (flags. and 5. • ‘half’ . After those come full lines (barbs). Single boolean indicates whether the lines and flags should point opposite to normal for all barbs.full barbs (Default is 10) • ‘flag’ . which give vector magnitude by the length of the arrow. There is only. twice the width of a full barb • ‘emptybarb’ .width of a flag. Release 1.Matplotlib.0. Default is True barb_increments: A dictionary of increments specifying values to associate with different parts of the barb. the magnitude is simply truncated to the next lowest multiple. Default is False rounding: A flag to indicate whether the vector magnitude should be rounded when allocating barb components. Only those values one wishes to override need to be included. the barbs give more quantitative information about the vector magnitude by putting slanted lines or a triangle for various increments in magnitude. If False. 412 Chapter 36. full/half barbs) • ‘height’ .radius of the circle used for low magnitudes fill_empty: A flag on whether the empty barbs (circles) that are drawn should be filled with the flag color. The magnitude for the barb shown above would nominally be 65. An array (which should be the same size as the other data arrays) indicates whether to flip for each individual barb. As opposed to arrows. using the standard increments of 50. 80000000000000004. Release 1.figure. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib. height=0. width. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number Example: barh(bottom. **kwargs) Make a horizontal bar plot with rectangles bounded by: 36. left=None.transforms.Figure instance an id string any string [’solid’ | ‘dashed’.8.0. matplotlib. width.1 linewidths and edgecolors can be used to customize the barb. height=0.1. left=0.Matplotlib. **kwargs) call signature: barh(bottom. ‘dotted’ | (offset.axes 413 . Additional PolyCollection keyword arguments: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized snap transform url urls visible zorder Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.Bbox instance [True | False] [ (Path. ‘dashdot’. left + width.0 1. width.1 6 2.5 4 3 2 1 0 1 2 1.5 4 3 2 1 0 1 2 left.5 0 0. bottom and top edges) bottom.5 6 1.0 4 6 6 4 2 0 2 4 6 1. right.5 2 0 0.0 6 6 4 2 0 2 4 6 1. Required arguments: Argument bottom width Description the vertical positions of the bottom edges of the bars the lengths of the bars Optional keyword arguments: 414 Chapter 36.Matplotlib. Release 1.5 4 1.0 2 0.0 0. bottom.0 4 0. height.patches.5 4 1. matplotlib axes .0 2 0.5 2 1.Rectangle instances.0. and left can be either scalars or sequences Return value is a list of matplotlib. bottom + height (left. while align = ‘center’ interprets these values as the y coordinates of the bar centers. True sets it to log scale Setting align = ‘edge’ aligns bars by their bottom edges in bottom. 36.5 4 Keyword height left color edgecolor linewidth xerr yerr ecolor capsize align log 3 Description 2 1 0 1 2 the heights (thicknesses) of the bars the x coordinates of the left edges of the bars the colors of the bars the colors of the bar edges width of bar edges. if not None.0 0. edgecolor. 0 means don’t draw edges.5 1. will be used to generate errorbars on the bar chart if not None. linewidth.5 1.0 0. matplotlib.0 1.0. Release 1. The optional arguments color.1 2. xerr. None means use default linewidth. This enables you to use barh as the basis for stacked bar charts. and yerr can be either scalars or sequences of length equal to the number of bars.1.5 0.Matplotlib.axes 415 . or candlestick plots.0 1. will be used to generate errorbars on the bar chart specifies the color of any errorbar (default 3) determines the length in points of the error bar caps ‘edge’ (default) | ‘center’ [False|True] False (default) leaves the horizontal axis as-is. x is an array or a sequence of vectors. sym=’+’. 416 Chapter 36. or ‘none’ for no color a matplotlib. patch_artist=False. •notch = 0 (default) produces a rectangular box plot. or ‘none’ for no color mpl color spec. notch=0. The box extends from the lower to upper quartile values of the data. vert=1. positions=None. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Matplotlib. Release 1. sym=’b+’. •notch = 1 will produce a notched box plot sym (default ‘b+’) is the default symbol for flier points. matplotlib axes .Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.0. notch=0. or None for default.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number positions=None.5. widths=None. or None for default. with a line at the median. whis=1.Bbox instance [True | False] [ (Path. The whiskers extend from the box to show the range of the data. whis=1. bootstrap=None) call signature: boxplot(x. boxplot(x.1 other optional kwargs: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.5. Flier points are those past the end of the whiskers.transforms. widths=None. patch_artist=False) Make a box and whisker plot for each column of x or each vector in sequence x. vert=1.figure. Enter an empty string (‘’) if you don’t want to show fliers. bootstrap (default None) specifies whether to bootstrap the confidence intervals around the median for notched boxplots. Release 1...transforms.BrokenBarHCollection properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. or 0.collections. xwidth) sequence of (ymin. Tukey. widths is either a scalar or a vector and sets the width of each box. no bootstrapping is performed. xranges.1 •vert = 1 (default) makes the boxes vertical. whis (default 1.. matplotlib. The default is 0. This seems goofy.5.. R.n) sets the horizontal positions of the boxes.0.lines. Otherwise.15*(distance between extreme positions) if that is smaller. and Larsen. If bootstrap==None. **kwargs) A collection of horizontal bars spanning yrange with a sequence of xranges. •vert = 0 makes horizontal boxes. but that’s how MATLAB did it.2.W.Bbox instance [True | False] Continued on next page 417 36. The ticks and limits are automatically set to match the positions. yrange. ywidth) kwargs are matplotlib.1. They extend to the most extreme data point within ( whis*(75%-25%) ) data range. Values between 1000 and 10000 are recommended.Matplotlib. **kwargs) call signature: broken_barh(self. Required arguments: Argument xranges yrange Description sequence of (xmin. 1967).axes . bootstrap specifies the number of times to bootstrap the median to determine it’s 95% confidence intervals...5) defines the length of the whiskers as a function of the inner quartile range. Example: broken_barh(xranges. W. positions (default 1.A. and notches are calculated using a Gaussian-based asymptotic approximation (see McGill.Line2D instances created. yrange. and Kendall and Stuart.. 1978. J. •patch_artist = False (default) produces boxes with the Line2D artist •patch_artist = True produces boxes with the Patch artist Returns a dictionary mapping each component of the boxplot to a list of the matplotlib. ie: facecolors = ’black’ or a sequence of arguments for the various bars.1 Table 36.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. matplotlib axes . Release 1.5 – continued from previous page clip_path [ (Path. ‘dotted’ | (offset. ’green’) Example: can_zoom() Return True if this axes support the zoom box cla() Clear the current axes clabel(CS. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number these can either be a single argument.0. *args.figure. where cs is a ContourSet object returned by contour.Matplotlib. **kwargs) adds labels to line contours in cs. **kwargs) call signature: clabel(cs. ie: facecolors = (’black’. Transform) | Patch | None ] cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib. ’red’. 418 Chapter 36. ‘dashdot’. etc). matplotlib.0.g.1 200 150 100 50 0 50 100 1 clabel(cs. colors = ‘r’ or colors = ‘red’. inline_spacing: space in pixels to leave on each side of label when placing inline.axes 419 .sf.3f’ Alternatively. this can be a dictionary matching contour levels with arbitrary strings to use for each contour level 36. Defaults to 5. This spacing will be exact for labels at locations where the contour is straight. fmt: a format string for the label. all labels will be plotted in this color • if a tuple of matplotlib color args (string.html colors: • if None.1. float. Optional keyword arguments: fontsize: See http://matplotlib. different labels will be plotted in different colors in the order specified inline: controls whether the underlying contour is removed or not. Default is ‘%1. Release 1. e.Matplotlib.net/fonts. rgb. the color of each label matches the color of the corresponding contour • if one string color. **kwargs) only labels contours listed in v. less so for labels on curved contours. Default is True. v. window=<function window_hanning at 0x3a178c0>. NFFT=256. contour labels will be placed manually using mouse clicks. Fc=0. matplotlib axes . noverlap=0. Release 1. therefore this can be used if aspect of the axes changes. delete or backspace act like the third mouse button. the keyboard can be used to select label locations (enter to end label placement. fmt[level]=string) manual: if True.Matplotlib. The third button can be used to remove the last label added. label rotations will always be plus or minus 90 degrees from level. use_clabeltext: if True (default is False).. and any other key will select a label location). ClabelText class (instead of matplotlib. pad_to=None.0. **kwargs) call signature: 1 420 Chapter 36.Text) is used to create labels. y. detrend=<function detrend_none at 0x3a1c668>. sides=’default’. Click the first button near a contour to add a label. ClabelText recalculates rotation angles of texts during the drawing time.1 200 150 100 50 0 50 100 (i. click the second button (or potentially both mouse buttons at once) to finish adding labels. clear() clear the axes cohere(x. rightside_up: if True (default). scale_by_freq=None. Fs=2.e. Alternatively. but only if labels are not inline. Matplotlib, Release 1.0.1 200 150 100 50 0 50 100 1 cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend = mlab.detrend_none, window = mlab.window_hanning, noverlap=0, pad_to=None, sides=’default’, scale_by_freq=None, **kwargs) cohere() the coherence between x and y. Coherence is the normalized cross spectral density: C xy = Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. Must be even; a power 2 is most efficient. The default value is 256. Fs: scalar The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit. The default value is 2. detrend: callable The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in matplotlib is it a function. The pylab module defines detrend_none(), detrend_mean(), and detrend_linear(), but you can use a custom function as well. window: callable or ndarray A function or a vector of length NFFT. To create window vectors see window_hanning(), window_none(), 36.1. matplotlib.axes 421 |P xy |2 P xx Pyy (36.1) Matplotlib, Release 1.0.1 120 100 80 60 40 20 0 20 1 numpy.blackman(), numpy.hamming(), numpy.bartlett(), scipy.signal(), scipy.signal.get_window(), etc. The default is window_hanning(). If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment. noverlap: integer The number of points of overlap between blocks. The default value is 0 (no overlap). pad_to: integer The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. Default gives the default behavior, which returns one-sided for real data and both for complex data. ‘onesided’ forces the return of a one-sided PSD, while ‘twosided’ forces two-sided. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency, which gives density in units of Hz^-1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility. 422 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 1 100 50 0 50 100 150 200 Fc: integer The center frequency of x (defaults to 0), which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband. The return value is a tuple (Cxy, f ), where f are the frequencies of the coherence vector. kwargs are applied to the lines. References: •Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986) kwargs control the Line2D properties of the coherence plot: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path Description unknown float (0.0 transparent through 1.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.transforms.Bbox instance [True | False] [ (Path, Transform) | Patch | None ] 36.1. matplotlib.axes 423 Matplotlib, Release 1.0.1 color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x, y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.figure.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’,’ | ’.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind, stride) float distance in points or callable pick function fn(artist, event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.transforms.Transform instance a url string [True | False] 1D array 1D array any number Example: connect(s, func) Register observers to be notified when certain events occur. Register with callback functions with the following signatures. The function has the following signature: func(ax) # where ax is the instance making the callback. The following events can be connected to: ‘xlim_changed’,’ylim_changed’ 424 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 1 100 50 0 50 100 150 200 The connection id is is returned - you can use this with disconnect to disconnect from the axes event contains(mouseevent) Test whether the mouse event occured in the axes. Returns T/F, {} contains_point(point) Returns True if the point (tuple of x,y) is inside the axes (the area defined by the its patch). A pixel coordinate is required. contour(*args, **kwargs) contour() and contourf() draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions. contourf() differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to contour(). call signatures: contour(Z) make a contour plot of an array Z. The level values are chosen automatically. 36.1. matplotlib.axes 425 Matplotlib, Release 1.0.1 200 150 100 50 0 50 100 1 2 3 contour(X,Y,Z) X, Y specify the (x, y) coordinates of the surface contour(Z,N) contour(X,Y,Z,N) contour N automatically-chosen levels. contour(Z,V) contour(X,Y,Z,V) draw contour lines at the values specified in sequence V contourf(..., V) fill the (len(V)-1) regions between the values in V contour(Z, **kwargs) Use keyword args to control colors, linewidth, origin, cmap ... see below for more details. X, Y, and Z must be arrays with the same dimensions. Z may be a masked array, but filled contouring may not handle internal masked regions correctly. 426 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 race interrupted Jim Bill 0 50 100 150 seconds since start 200 C = contour(...) returns a QuadContourSet object. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None, the colormap specified by cmap will be used. If a string, like ‘r’ or ‘red’, all levels will be plotted in this color. If a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None. If cmap is None and colors is None, a default Colormap is used. norm: [ None | Normalize ] A matplotlib.colors.Normalize instance for scaling data values to colors. If norm is None and colors is None, the default linear scaling is used. levels [level0, level1, ..., leveln] A list of floating point numbers indicating the level curves to draw; eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None, the first value of Z will correspond to the lower left corner, location (0,0). If ‘image’, the rc value for image.origin will be used. 36.1. matplotlib.axes 427 Matplotlib, Release 1.0.1 Simplest default with labels 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 1 0 1 2 0.50 0 -0.50 1.500 0 1.000 0.00 0 00 -1.0 This keyword is not active if X and Y are specified in the call to contour. extent: [ None | (x0,x1,y0,y1) ] If origin is not None, then extent is interpreted as in matplotlib.pyplot.imshow(): it gives the outer pixel boundaries. In this case, the position of Z[0,0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0,0], and (x1, y1) is the position of Z[-1,-1]. This keyword is not active if X and Y are specified in the call to contour. locator: [ None | ticker.Locator subclass ] If locator is None, the default MaxNLocator is used. The locator is used to determine the contour levels if they are not given explicitly via the V argument. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’, contour levels are automatically added to one or both ends of the range so that all data are included. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range, but can be set via matplotlib.colors.Colormap.set_under() and matplotlib.colors.Colormap.set_over() methods. xunits, yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib.units.ConversionInterface. 428 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 Single color -0.000 negative contours dashed 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 -0.5 00 -1.0 00 0.500 1.000 1.500 0.00 0 1 0 1 2 contour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None, the default width in lines.linewidth in matplotlibrc is used. If a number, all levels will be plotted with this linewidth. If a tuple, different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None, the ‘solid’ is used. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary. If contour is using a monochrome colormap and the contour level is less than 0, then the linestyle specified in contour.negative_linestyle in matplotlibrc will be used. contourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. This 36.1. matplotlib.axes 429 Matplotlib, Release 1.0.1 Single color0.000 - negative contours solid 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 -0.5 00 -1.0 00 0.500 1.000 1.500 0.00 0 1 0 1 2 may never actually be advantageous, so this option may be removed. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. Note: contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array, then that minimum value will be included in the lowest interval. Examples: contourf(*args, **kwargs) contour() and contourf() draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions. contourf() differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to contour(). call signatures: contour(Z) make a contour plot of an array Z. The level values are chosen automatically. 430 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 0.000 Crazy lines 0.500 1.000 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 -0.5 00 1.500 -1.0 00 0.00 0 1 0 1 2 contour(X,Y,Z) X, Y specify the (x, y) coordinates of the surface contour(Z,N) contour(X,Y,Z,N) contour N automatically-chosen levels. contour(Z,V) contour(X,Y,Z,V) draw contour lines at the values specified in sequence V contourf(..., V) fill the (len(V)-1) regions between the values in V contour(Z, **kwargs) Use keyword args to control colors, linewidth, origin, cmap ... see below for more details. X, Y, and Z must be arrays with the same dimensions. Z may be a masked array, but filled contouring may not handle internal masked regions correctly. 36.1. matplotlib.axes 431 Matplotlib, Release 1.0.1 2.0 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 Lines with colorbar 0.2 0.6 1.4 1.0 -1.0 -0.2 -0.6 3 2 1 0 1.2 0.8 0.4 0.0 0.4 0.8 1.2 2 3 1 1.2 0.8 0.40.0 0.4 0.8 1.2 1.6 C = contour(...) returns a QuadContourSet object. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None, the colormap specified by cmap will be used. If a string, like ‘r’ or ‘red’, all levels will be plotted in this color. If a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None. If cmap is None and colors is None, a default Colormap is used. norm: [ None | Normalize ] A matplotlib.colors.Normalize instance for scaling data values to colors. If norm is None and colors is None, the default linear scaling is used. levels [level0, level1, ..., leveln] A list of floating point numbers indicating the level curves to draw; eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None, the first value of Z will correspond to the lower left corner, location (0,0). If ‘image’, the rc value for image.origin will be used. 432 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 0.08 0.06 0.04 0.02 0.00 0.02 0.04 0.060 1.0 0.8 0.6 0.4 0.2 0.00 s1 and s2 1 2 time 3 4 5 coherence 10 20 30 Frequency 40 50 This keyword is not active if X and Y are specified in the call to contour. extent: [ None | (x0,x1,y0,y1) ] If origin is not None, then extent is interpreted as in matplotlib.pyplot.imshow(): it gives the outer pixel boundaries. In this case, the position of Z[0,0] is the center of the pixel, not a corner. If origin is None, then (x0, y0) is the position of Z[0,0], and (x1, y1) is the position of Z[-1,-1]. This keyword is not active if X and Y are specified in the call to contour. locator: [ None | ticker.Locator subclass ] If locator is None, the default MaxNLocator is used. The locator is used to determine the contour levels if they are not given explicitly via the V argument. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’, contour levels are automatically added to one or both ends of the range so that all data are included. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range, but can be set via matplotlib.colors.Colormap.set_under() and matplotlib.colors.Colormap.set_over() methods. xunits, yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib.units.ConversionInterface. 36.1. matplotlib.axes 433 Matplotlib, Release 1.0.1 Simplest default with labels 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 1 0 1 2 0.50 0 -0.50 1.500 0 1.000 0.00 0 00 -1.0 contour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None, the default width in lines.linewidth in matplotlibrc is used. If a number, all levels will be plotted with this linewidth. If a tuple, different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None, the ‘solid’ is used. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If this iterable is shorter than the number of contour levels it will be repeated as necessary. If contour is using a monochrome colormap and the contour level is less than 0, then the linestyle specified in contour.negative_linestyle in matplotlibrc will be used. contourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. This 434 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 Single color -0.000 negative contours dashed 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 -0.5 00 -1.0 00 0.500 1.000 1.500 0.00 0 1 0 1 2 may never actually be advantageous, so this option may be removed. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. Note: contourf fills intervals that are closed at the top; that is, for boundaries z1 and z2, the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array, then that minimum value will be included in the lowest interval. Examples: csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=<function detrend_none at 0x3a1c668>, window=<function window_hanning at 0x3a178c0>, noverlap=0, pad_to=None, sides=’default’, scale_by_freq=None, **kwargs) call signature: csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides=’default’, scale_by_freq=None, **kwargs) The cross spectral density P xy by Welch’s average periodogram method. The vectors x and y are divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. The product of the direct FFTs of x and y are averaged over each segment to compute P xy , with a scaling to correct for power loss due to windowing. 36.1. matplotlib.axes 435 Matplotlib, Release 1.0.1 Single color0.000 - negative contours solid 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 -0.5 00 -1.0 00 0.500 1.000 1.500 0.00 0 1 0 1 2 Returns the tuple (Pxy, freqs). P is the cross spectrum (complex valued), and 10 log10 |P xy | is plotted. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. Must be even; a power 2 is most efficient. The default value is 256. Fs: scalar The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit. The default value is 2. detrend: callable The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in matplotlib is it a function. The pylab module defines detrend_none(), detrend_mean(), and detrend_linear(), but you can use a custom function as well. window: callable or ndarray A function or a vector of length NFFT. To create window vectors see window_hanning(), window_none(), numpy.blackman(), numpy.hamming(), numpy.bartlett(), scipy.signal(), scipy.signal.get_window(), etc. The default is window_hanning(). If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment. noverlap: integer The number of points of overlap between blocks. The default value 436 Chapter 36. matplotlib axes Matplotlib, Release 1.0.1 0.000 Crazy lines 0.500 1.000 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 3 2 -0.5 00 1.500 -1.0 00 0.00 0 1 0 1 2 is 0 (no overlap). pad_to: integer The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. Default gives the default behavior, which returns one-sided for real data and both for complex data. ‘onesided’ forces the return of a one-sided PSD, while ‘twosided’ forces two-sided. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency, which gives density in units of Hz^-1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility. Fc: integer The center frequency of x (defaults to 0), which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband. References: Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John 36.1. matplotlib.axes 437 Matplotlib, Release 1.0.1 2.0 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0 Lines with colorbar 0.2 0.6 1.4 1.0 -1.0 -0.2 -0.6 3 2 1 0 1.2 0.8 0.4 0.0 0.4 0.8 1.2 2 3 1 1.2 0.8 0.40.0 0.4 0.8 1.2 1.6 Wiley & Sons (1986) kwargs control the Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle Description unknown float (0.0 transparent through 1.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.transforms.Bbox instance [True | False] [ (Path, Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x, y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.figure.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] 438 Chapter 36. matplotlib axes matplotlib. *args. labels) 36.’ | ’. button is the mouse button number: •1: LEFT •2: MIDDLE •3: RIGHT key is a “shift” key x. stride) float distance in points or callable pick function fn(artist. key.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.1. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. Release 1.axes 439 . axes. y are the mouse coordinates in display coords.0. y) Called when the mouse moves during a pan operation. Note: Intended to be overridden by new projection types.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. renderer. drag_pan(button. **kwargs) Draw everything (plot lines.Matplotlib.transforms. x.1 gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder an id string any string [ ’-’ | ’--’ | ’-.Transform instance a url string [True | False] 1D array 1D array any number Example: disconnect(cid) disconnect from the Axes event. draw(artist. barsabove=False. Vertical errorbars are plotted if yerr is not None. Release 1. ecolor=None. errorbar(x. barsabove=False. matplotlib axes . fmt=’-‘. capsize=3.) Note: Intended to be overridden by new projection types.2 1. yerr=None. capsize=3. xlolims=False. etc are not updated) end_pan() Called when a pan operation completes (when the mouse button is up. y. fmt=’-’.6 1. yerr=None.6 0. It is used to efficiently update Axes data (axis ticks. y. lolims=False. xuplims=False) Plot x versus y with error deltas in yerr and xerr. Horizontal errorbars are plotted if xerr is not None. uplims=False. lolims=False. xuplims=False. y. ecolor=None.8 draw_artist(a) This method can only be used after an initial draw which caches the renderer. labels.2 verbosity coefficient 0.1 Nonsense (3 masked regions) 2 sentence length anomaly 1 0 1 2 33 2 1 0 1 2 word length anomaly 1.0. uplims=False. y. **kwargs) call signature: errorbar(x. x.0 0. xerr. elinewidth=None. which plots a single error bar at x. and yerr can all be scalars. elinewidth=None. xlolims=False. xerr=None. xerr=None.Matplotlib. Optional keyword arguments: 440 Chapter 36. Nx1. for example.0 0. or 2xN array-like ] If a scalar number. errorbars are drawn at -row1 and +row2 fmt: ‘-‘ The plot format symbol. Release 1. errorbars are drawn +/. 0 1.5 1. elinewidth: scalar the linewidth of the errorbar lines. if None.0 0. If fmt is None. lolims/uplims/xlolims/xuplims: [ False | True ] These arguments can be used to indicate that a value gives only upper/lower limits. This is used for adding errorbars to a bar plot.0 -0. ecolor: [ None | mpl color ] a matplotlib color arg which gives the color the errorbar lines.5 0.0 0.5 xerr/yerr: [ scalar | N.Matplotlib. will plot the errorbars above the plot symbols. If None. use the marker color. All other keyword arguments are passed on to the plot command for the markers. capsize: scalar the size of the error bar caps in points barsabove: [ True | False ] if True. matplotlib. lims-arguments may be of the same type as xerr and yerr.5 -1. only the errorbars are plotted.1.axes 441 . In that case a caret symbol is used to indicate this.1 Listed colors (3 masked regions) 2 1 0 1 2 33 2 1 0 1 2 0.0. this code makes big red squares with thick green edges: 36.value. or an Nx1 array-like object. len(N) array-like object.0 1.5 0. If a sequence of shape 2xN.0 1. Default is below. For example.5 -1. use the linewidth. valid kwargs for the marker properties are Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle Description unknown float (0.1 Simplest default with labels 1.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. ms=20. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] 442 Chapter 36.0 x. marker=’s’.5 1.0. mec=’green’. Release 1.10) errorbar(x.0 1. matplotlib axes .50 0 -0.5 2. markersize and markeredgewith.yerr = rand(3. markerfacecolor.0 3 2 1 0 1 2 0.50 1. ms and mew are aliases for the longer property names.Matplotlib.Bbox instance [True | False] [ (Path. mfc=’red’.0 transparent through 1.0 0. markeredgecolor. mec.500 0 1.5 0.000 0.y. mew=4) where mfc.5 1. y. yerr.0 0.transforms.00 0 00 -1. barlinecols): plotline: Line2D instance x.’ | ’. **kwargs) call signature: fill(*args. allowing for multiple x. y pairs with an optional color format string. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. matplotlib.0.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.Matplotlib. see plot() for details on the argument parsing. y plot markers and/or line caplines: list of error bar cap Line2D instances barlinecols: list of LineCollection instances for the horizontal and vertical error ranges. args is a variable length argument.1. **kwargs) Plot filled polygons. caplines. to 36.Transform instance a url string [True | False] 1D array 1D array any number Returns (plotline.figure. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. Example: fill(*args.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. stride) float distance in points or callable pick function fn(artist. For example.transforms. Release 1.axes 443 .1 dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder sequence of on/off ink in points 2D array (rows are x. 5 2.500 0.0 0.1 Single color -0.000 1.500 1. color groups can be specified: ax. y in blue. y1. ’b’ ) An arbitrary number of x.0 3 2 -0.0 1. If you would like to fill below a curve.000 negative contours dashed 1.5 1.: ax. y2.fill(x.5 00 -1. Release 1.0 00 0. The same color strings that plot() supports are supported by the fill format string. shade a region between 0 and y along x. y.Matplotlib. ’r’) Return value is a list of Patch instances that were added.y. kwargs control the Polygon properties: 444 Chapter 36. x2.0 0. eg.5 0.5 1. use fill_between() The closed kwarg will close the polygon when True (default).fill(x1.0. ’g’.00 0 1 0 1 2 plot a polygon with vertices at x. matplotlib axes . or None for default.0 1.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] 445 .5 00 -1. or None for default.000 .axes transform url visible Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. matplotlib.Bbox instance [True | False] [ (Path.00 0 1 0 1 2 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap 36.500 1.000 1.5 1.transforms.0. or ‘none’ for no color mpl color spec.Matplotlib.figure. or ‘none’ for no color a matplotlib.5 1. Release 1.negative contours solid 1.1.0 3 2 -0.5 2.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.500 0.0 00 0.1 Single color0.0 0.0 0.5 0. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. 000 1. default to fill between everywhere. interpolate=False. where=None. **kwargs) call signature: fill_between(x.Matplotlib. **kwargs) Create a PolyCollection filling the regions between y1 and y2 where where==True x an N length np array of the x data y1 an N length scalar or np array of the y data y2 an N length scalar or np array of the y data where if None.0 0.5 00 1. y2=0. interpolate between the two lines to find the precise point of intersection.0 1.0 00 0. y1.1 0. If not None. Otherwise.5 1. where=None.0.500 1.5 0.0 3 2 -0. it is a a N length numpy boolean array and the fill will only happen over the regions where where==True interpolate If True. y1.5 2.00 0 1 0 1 2 Example: fill_between(x. matplotlib axes . the start and end points of the filled region will only occur on explicit values in the x array.5 1. y2=0. kwargs keyword args passed on to the PolyCollection kwargs control the Polygon properties: 446 Chapter 36. Release 1.0 0.500 -1.000 Crazy lines 0. Release 1.1.1 2.8 0.8 1. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib.Matplotlib.5 0.0 0.4 1.transforms.4 0.figure.6 3 2 1 0 1.Bbox instance [True | False] [ (Path.40.2 1.0 0.2 0.2 0.6 1.axes 447 .4 0.0 0.5 1.8 0.0 Lines with colorbar 0.0 -1.0 1.5 2.2 0.Figure instance an id string any string Continued on next page 36.0 0.0.0 -0.6 Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. matplotlib.4 0.0 1.5 1.2 2 3 1 1.2 -0.8 1. x2=0. x1. **kwargs) call signature: fill_between(y. where=None. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number See Also: fill_betweenx() for filling between two sets of x-values fill_betweenx(y.0. Release 1. x1. **kwargs) Create a PolyCollection filling the regions between x1 and x2 where where==True y an N length np array of the y data x1 an N length scalar or np array of the x data x2 an N length scalar or np array of the x data where if None. matplotlib axes . ‘dotted’ | (offset.1 Table 36. default to fill between everywhere. If not None.9 – continued from previous page linestyle or linestyles or dashes [’solid’ | ‘dashed’. x2=0. it is a a N length numpy boolean array and the fill will only happen over the regions where where==True kwargs keyword args passed on to the PolyCollection kwargs control the Polygon properties: Property agg_filter alpha animated antialiased or antialiaseds array axes Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance Continued on next page 448 Chapter 36. where=None.Matplotlib. ‘dashdot’. else will fall back on the xaxis major formatter format_ydata(y) Return y string formatted. matplotlib.fmt_xdata if it is callable.transforms.Bbox instance clip_on [True | False] clip_path [ (Path. y) return a format string formatting the x.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’.0. This function will use the attribute self. Transform) | Patch | None ] cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib. y coord format_xdata(x) Return x string formatted. This function will use the fmt_ydata attribute if it is callable. Release 1.1. ‘dotted’ | (offset.10 – continued from previous page clim a length 2 sequence of floats clip_box a matplotlib. ‘dashdot’.figure.axes 449 . on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number See Also: fill_between() for filling between two sets of y-values format_coord(x.1 Table 36. else will fall back on the yaxis major formatter frame get_adjustable() 36.Matplotlib. Matplotlib.8 .6 1.0. matplotlib axes 1. Release 1. Deprecated since version 0.1 Nonsense (3 masked regions) 2 sentence length anomaly 1 0 1 2 33 get_anchor() get_aspect() get_autoscale_on() Get whether autoscaling is applied for both axes on plot commands get_autoscalex_on() Get whether autoscaling for the x-axis is applied on plot commands get_autoscaley_on() Get whether autoscaling for the y-axis is applied on plot commands get_axes_locator() return axes_locator get_axis_bgcolor() Return the axis background color get_axisbelow() Get whether axis below is true or not get_child_artists() Return a list of artists the axes contains.2 2 1 0 1 2 word length anomaly 1.6 0. get_children() return a list of child artists 450 Chapter 36.98.0 0.2 verbosity coefficient 0. This method is intended to be overridden by new projection types. get_data_ratio_log() Returns the aspect ratio of the raw data in log scale.axes 451 .5 1. Will be used when both axis scales are in log.0 0. get_frame() Return the axes Rectangle frame get_frame_on() Get whether the axes rectangle patch is drawn get_images() return a list of Axes images contained by the Axes get_legend() Return the legend.0 1.0 0. 0 1.0 -0.5 -1.0 0.5 0.5 -1. color) tuple.1 Listed colors (3 masked regions) 2 1 0 1 2 33 2 1 0 1 2 0.5 0. Release 1.0 1. where linewidth is a float and color is an RGBA tuple get_data_ratio() Returns the aspect ratio of the raw data. or None if no legend is defined get_legend_handles_labels() 36.Legend instance.Matplotlib.5 get_cursor_props() return the cursor propertiess as a (linewidth.1.0. matplotlib. 0.00 0. l = ax.04 0.legend() is equivalent to h.08 0.04 0. Release 1.Matplotlib. or None get_position(original=False) Return the a copy of the axes rectangle as a Bbox get_rasterization_zorder() Get zorder value below which artists will be rasterized get_renderer_cache() get_shared_x_axes() Return a copy of the shared axes Grouper object for x axes 452 Chapter 36. l) get_lines() Return a list of lines contained by the Axes get_navigate() Get whether the axes responds to navigation commands get_navigate_mode() Get the navigation toolbar button status: ‘PAN’. matplotlib axes .get_legend_handles_labels() ax.080 45 55 65 75 850 s1 and s2 1 2 time 3 4 5 CSD (db) 10 20 30 Frequency 40 50 return handles and labels for legend ax.1 0. ‘ZOOM’.legend(h.06 0.02 0.06 0.02 0. 0. matplotlib.0 0.1. Note: This transformation is primarily used by the Axis class.4 Simplest errorbars.0.6 0. The x-direction is in data coordinates and the y-direction is in axis coordinates. **kwargs) get the axes bounding box in display space. get_window_extent(*args. get_title() Get the title text string.2 0.0 0.5 3. 0.2 0. and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.8 0.5 4.0 2.2 1.0 1.1 1. halign) where valign and halign are requested alignments for the text. which will add the given amount of padding (in points) between the axes and the label.4 0.axes 453 .5 0.2 in x. 36.0 0. The dimension of the Bbox in canvas coordinate.5 2.Matplotlib. args and kwargs are empty get_xaxis() Return the XAxis instance get_xaxis_text1_transform(pad_points) Get the transformation used for drawing x-axis labels.0 3. valign. Returns a 3-tuple of the form: (transform.5 1.40.4 in y 1.0 get_shared_y_axes() Return a copy of the shared axes Grouper object for y axes get_tightbbox(renderer) return the tight bounding box of the axes. Release 1. Note: This transformation is primarily used by the Axis class.1 1.4 0.5 H.0 Hor. valign. symmetric 1.0 0. Note: This transformation is primarily used by the Axis class.. and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations. and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.6 0. Returns a 3-tuple of the form: (transform.2 6 0. The x-direction is in data coordinates and the y-direction is in axis coordinates. get_xaxis_transform(which=’grid’) Get the transformation used for drawing x-axis labels.5 2 0 2 4 0. symmetric 1.Matplotlib.0 0.5 0. V asymmetric 1.0 0.8 0. halign) where valign and halign are requested alignments for the text.0 2Mixed sym.5 Vert. get_xbound() Returns the x-axis numerical bounds where: lowerBound < upperBound get_xgridlines() Get the x grid lines as a list of Line2D instances 454 Chapter 36. log y 6 0 2 4 1 10 100 10-1 10-2 2 6 0 2 4 6 Variable errorbars get_xaxis_text2_transform(pad_points) Get the transformation used for drawing the secondary x-axis labels. The x-direction is in data coordinates and the y-direction is in axis coordinates.0 0. which will add the given amount of padding (in points) between the axes and the label.5 2 0 2 4 1. ticks and gridlines. Release 1. matplotlib axes .5 0.0. 3 0.1.axes 455 .0 0. matplotlib.6 0.4 0.0 get_xlabel() Get the xlabel text string.2 0.2 0. right] get_xmajorticklabels() Get the xtick labels as a list of Text instances get_xminorticklabels() Get the xtick labels as a list of Text instances get_xscale() get_xticklabels(minor=False) Get the xtick labels as a list of Text instances get_xticklines() Get the xtick lines as a list of Line2D instances get_xticks(minor=False) Return the x ticks as a list of locations get_yaxis() Return the YAxis instance get_yaxis_text1_transform(pad_points) 36.1 0.5 0.2 0.4 0.1 0.8 1. Release 1.0 0.6 0.Matplotlib. get_xlim() Get the x-axis range [left.0.1 0. The x-direction is in axis coordinates and the y-direction is in data coordinates.0 0. The x-direction is in 456 Chapter 36.0 0.5 0.5 1.5 2. halign) where valign and halign are requested alignments for the text. get_yaxis_transform(which=’grid’) Get the transformation used for drawing y-axis labels.0 1.5 1. which will add the given amount of padding (in points) between the axes and the label. which will add the given amount of padding (in points) between the axes and the label.5 0.0 0.0 1. Note: This transformation is primarily used by the Axis class.0 0.5 2. valign.0 0.0 x 1.0 0.0 0.5 1.5 0. Release 1. and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations. Returns a 3-tuple of the form: (transform.5 1. Returns a 3-tuple of the form: (transform. Note: This transformation is primarily used by the Axis class. halign) where valign and halign are requested alignments for the text.0 1. ticks and gridlines.0 0.5 1.5 1.0 0.0 1.0.Matplotlib. matplotlib axes .0 Get the transformation used for drawing y-axis labels.5 2. The x-direction is in axis coordinates and the y-direction is in data coordinates. valign.0 0.0 1.5 1.0 0. get_yaxis_text2_transform(pad_points) Get the transformation used for drawing the secondary y-axis labels.1 between y1 andbetween y1 and 1 y2 between y1 and 0 1. and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.5 0. 5 0.5 1.axes 457 .Matplotlib.0 1.5 0.1.0 Now regions with y2>1 are1.5 0.0 axis coordinates and the y-direction is in data coordinates.0 0. get_ybound() Return y-axis numerical bounds in the form of lowerBound < upperBound get_ygridlines() Get the y grid lines as a list of Line2D instances get_ylabel() Get the ylabel text string.0.5 1.1 1.5 1.0 1. and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations. Note: This transformation is primarily used by the Axis class.5 0.0 0. Release 1.0 1.0 0.0 fill between where 0.0 1.5 1. top] get_ymajorticklabels() Get the xtick labels as a list of Text instances get_yminorticklabels() Get the xtick labels as a list of Text instances get_yscale() get_yticklabels(minor=False) Get the xtick labels as a list of Text instances 36.5 2.0 0.5 1. get_ylim() Get the y-axis range [bottom. matplotlib.0 0.5 masked 2. toggle the grid state.5 2.Matplotlib. **kwargs) Set the axes grids on or off. b=None.5 1.0 0.0 0. (For MATLAB compatibility.5 0. linewidth=2) Valid Line2D kwargs are 458 Chapter 36.0 0. or both are affected. which=’major’. Release 1.0 1. minor tick grids. linestyle=’-’. ‘minor’.0 get_yticklines() Get the ytick lines as a list of Line2D instances get_yticks(minor=False) Return the y ticks as a list of locations grid(b=None.) If b is None and len(kwargs)==0.grid(color=’r’. matplotlib axes . which=’major’.0.5 1. or ‘both’ to control whether major tick grids.1 1. If kwargs are supplied. which can be ‘major’ (default).0 0. b may also be a string. b is a boolean. kawrgs are used to set the grid line properties. eg: ax. **kwargs) call signature: grid(self. ‘on’ or ‘off’. it is assumed that you want a grid and b is thus set to True. 5 1.5 0.0 1.5 1.0 0.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string 36.Matplotlib.0 1.5 1.transforms.5 0.0 0.5 2.0 0.axes 459 . matplotlib.0 x 0.1.1 between y1 andbetween y1 and 1 y2 between y1 and 0 2.0 1.01.0 0.5 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label Description unknown float (0.0 1.figure.5 2.0 1.5 1.5 1.0.01.5 0.5 1.Bbox instance [True | False] [ (Path. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.01.0 1.0 0.0 transparent through 1.5 0.0 0.0 0.5 1.5 0. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.0 0.5 1.5 0.5 1. Release 1.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. N. C=None. bins = None. cmap=None. edgecolors=’none’ reduce_C_function = np.mean. y are 1-D sequences of the same length. vmax=None. **kwargs) call signature: hexbin(x. it specifies values at the coordinate (x[i]. bins=None. which defaults to 460 Chapter 36.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. hexbin(x. Release 1. mincnt=None.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. vmin=None. This should not be used to determine whether the dataLim need to be updated. cmap=None. yscale=’linear’. linewidths=None. gridsize=100. marginals=False. linewidths=None.1 linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [ ’-’ | ’--’ | ’-. edgecolors=’none’. reduce_C_function=<function mean at 0x2b55320>.y[i]).Matplotlib. vmin=None.y[i]). If C is specified.transforms. where x. xscale = ’linear’.’ | ’. mincnt=None. extent=None. vmax=None. norm=None. stride) float distance in points or callable pick function fn(artist. norm=None. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. If C is None (the default). xscale=’linear’. and may not actually be useful for anything. C = None. y. These values are accumulated for each hexagonal bin and then reduced according to reduce_C_function. yscale = ’linear’. this is a histogram of the number of occurences of the observations at (x[i].Transform instance a url string [True | False] 1D array 1D array any number has_data() Return True if any artists have been added to axes. gridsize = 100. matplotlib axes . y. marginals=True **kwargs) Make a hexagonal binning plot of x versus y. alpha=None.0. alpha=None. 5 1. divide the counts in the specified number of bins.0.0 0.0 > 10.0 0.5 1.5 1.5 2. scale: [ ‘linear’ | ‘log’ ] Use a linear or log10 scale on the vertical axis. Release 1. The corresponding number of hexagons in the y-direction is chosen such that the hexagons are approximately regular.0 0. If ‘log’. the color of each hexagon directly corresponds to its count value. If an integer.Matplotlib. use a logarithmic scale for the color map. Internally. y and/or C may be masked arrays.0 1.01.1 2. Optional keyword arguments: gridsize: [ 100 | integer ] The number of hexagons in the x-direction.5 0. and color the hexagons accordingly.) x. log10 (i + 1) is used to determine the hexagon color.5 masked 1. the values of the lower bound of the bins to be used.5 Now regions with0.axes 461 .5 y2 are 1. (If C is specified. If a sequence of values.mean). 36.5 0. xscale: [ ‘linear’ | ‘log’ ] Use a linear or log10 scale on the horizontal axis. it must also be a 1-D sequence of the same length as x and y. gridsize can be a tuple with two elements specifying the number of hexagons in the x-direction and the y-direction. in which case only unmasked points will be plotted.0 0. matplotlib.0 1.0 1. bins: [ None | ‘log’ | integer | sequence ] If None. no binning is applied.0 fill between where 1.1.01.5 numpy’s mean function (np.5 1. default is 100. Alternatively.0 0.5 0. transforms. as required by RegularPolyCollection. or None the alpha value for the patches linewidths: [ None | scalar ] If None. If a matplotlib color arg or sequence of rgba tuples. bottom. draws the outlines in the specified color. Note that this is a tuple. Other keyword arguments controlling color mapping and normalization arguments: cmap: [ None | Colormap ] a matplotlib.cm.Normalize instance is used to scale luminance data to 0.1. your settings for vmin and vmax will be ignored. matplotlib axes 462 . Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples Continued on next page Chapter 36. only display cells with more than mincnt number of points in the cell marginals: True|False if marginals is True.cmap.1 mincnt: None | a positive integer If not None. the min and max of the color array C is used.0. vmin/vmax: scalar vmin and vmax are used in conjunction with norm to normalize luminance data. x. draws the outlines in the default color. xscale and yscale.colors. Other keyword arguments controlling the Collection properties: edgecolors: [ None | mpl color | color sequence ] If ‘none’. If None. alpha: scalar between 0 and 1.linewidth.Bbox instance [True | False] [ (Path. The default assigns the limits based on gridsize. top) ] The limits of the bins. Release 1. Note if you pass a norm instance. Here are the standard descriptions of all the Collection kwargs: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. defaults to rc image. This is the default. as it avoids unsightly unpainted pixels between the hexagons. plot the marginal density as colormapped rectagles along the bottom of the x-axis and left of the y-axis extent: [ None | scalars (left. defaults to rc lines. If either are None. norm: [ None | Normalize ] matplotlib. right.Colormap instance. and if you set the linewidths argument you must set it as a sequence of floats. y. If None.Matplotlib. draws the edges in the same color as the fill color. . bins=10. If marginals is True. x1. [patches0. matplotlib. bins=10. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number The return value is a PolyCollection instance. histtype=’bar’. normed=False. histtype=’bar’. align=’mid’. label=None.. rwidth=None.. patches1. n1. weights=None. Multiple data can be provided via x as a list of datasets of potentially different length ([x0. Keyword arguments: 36. color=None.0. use get_array() on this PolyCollection to get the counts in each hexagon. horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar Example: hist(x... bottom=None. range=None. or as a 2-D ndarray in which each column is a dataset. orientation=’vertical’.]. ‘dashdot’. cumulative=False. bins. . ‘dotted’ | (offset.Matplotlib.axes 463 . log=False. cumulative=False. rwidth=None. align=’mid’.. range=None.. bins.]). bottom=None.figure. patches) or ([n0.12 – continued from previous page colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib. log=False.1. orientation=’vertical’. The return value is a tuple (n.. Note that the ndarray form is transposed relative to the list form. **kwargs) call signature: hist(x. Release 1. normed=False. **kwargs) Compute and draw the histogram of x.. Masked arrays are not supported at present.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’.]) if the input contains multiple data.1 Table 36. 00 1. of the same shape as x. If bins is a sequence or range is specified. you can verify that with a trapezoidal integration of the probability density function: pdf. the first element of the return tuple will be the counts normalized to form a probability density. In a probability density. consistent with numpy.hist(.00 0. Range has no effect if bins is a sequence. the underlying numpy histogram function was incorrect with normed*=*True if bin sizes were unequal.25 4010 20 0 20 4 3 2 10 1 2 3 4 bins: Either an integer number of bins or a sequence giving the bins. bins + 1 bin edges will be returned.. MPL inherited that error.sum(pdf * np..histogram() for numpy version >= 1. n/(len(x)*dbin).Matplotlib. the integral of the histogram should be 1. Lower and upper outliers are ignored.75 1.e. autoscaling is based on the specified bin range instead of the range of x. bins. normed: If True. and with the new = True argument in earlier versions.50 0.3. i.75 0. If bins is an integer.50 1.25 4 3 2 10 1 2 3 4 0. Release 1. x. range: The lower and upper range of the bins. Unequally spaced bins are supported if bins is a sequence. It is now corrected within MPL when using earlier numpy versions weights An array of weights.max()). range is (x.min().) print np. Each value in x only contributes 464 Chapter 36..5. matplotlib axes .0.diff(bins)) Note: Until numpy release 1.1 Hexagon binning 20 10 0 10 20 With a log color scale 20 140 120 10 100 80 60 counts 0 2. If not provided. patches = ax.00 log10(N) 1. If normed is also True then the histogram is normalized such that the last bin equals 1. • ‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other. -1). then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. • ‘mid’: bars are centered between the bin edges. log: If True.Matplotlib. automatically compute the width. but only the first gets the label. align: [’left’ | ‘mid’ | ‘right’ ] Controls how the histogram is plotted. orientation: [ ‘horizontal’ | ‘vertical’ ] If ‘horizontal’. so that the integral of the density over the range remains 1. bins. If cumulative evaluates to less than 0 (e. rwidth: The relative width of the bars as a fraction of the bin width. label=’women’.g. The last bin gives the total number of datapoints. • ‘step’ generates a lineplot that is by default unfilled.1. the histogram axis will be set to a log scale. empty bins will be filtered out and only the non-empty (n. Release 1.random.randn(1000). label=’men’) ax. if normed is also True. • ‘stepfilled’ generates a lineplot that is by default filled. label: String. • ‘right’: bars are centered on the right bin edges. If normed is True. alpha=0. histtype: [ ‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’ ] The type of histogram to draw. the weights are normalized.5) ax. cumulative: If True. • ‘left’: bars are centered on the left bin edges. one per dataset.0. matplotlib.random. Bar charts yield multiple patches per dataset. • ‘bar’ is a traditional bar-type histogram. In this case. Default (None) uses the standard line color sequence. patches) will be returned. or sequence of strings to match multiple datasets. barh() will be used for bartype histograms and the bottom kwarg will be the left edges.hist(12+3*np.hist(10+2*np. If None.axes 465 . then the histogram is normalized such that the first bin equals 1.randn(1000). color: Color spec or sequence of color specs.1 its associated weight towards the bin count (instead of 1). the direction of accumulation is reversed. so that the legend command will work as expected: ax. If log is True and x is a 1D array. Ignored if histtype = ‘step’ or ‘stepfilled’. If multiple data are given the bars are aranged side by side.legend() kwargs are used to update the properties of the Patch instances returned by hist: 36. or ‘none’ for no color a matplotlib. colors=’k’. or None for default.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Example: Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. xmin.figure. **kwargs) call signature: hlines(y. If they are scalars. Required arguments: y: a 1-D numpy array or iterable. linestyles=’solid’. label=’‘.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number hlines(y. **kwargs) Plot horizontal lines at each y from xmin to xmax. linestyles=’solid’. either a single color or a len(y) list of colors 466 Chapter 36. Optional keyword arguments: colors: a line collections color argument.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. Release 1. colors=’k’. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. xmax. else the widths of the lines are determined by xmin and xmax. xmax.Matplotlib. then the respective values are constant.transforms. or None for default.Bbox instance [True | False] [ (Path. or ‘none’ for no color mpl color spec. xmin. Returns the LineCollection that was added. xmin and xmax: can be scalars or len(x) numpy arrays. matplotlib axes .0. toggle the hold state.020 Probability 0. origin=None.1 0. aspect=None. norm=None.axes 467 . url=None. σ =15 60 80 100 120 Smarts 140 160 linestyles: [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] Example: hold(b=None) call signature: hold(b=None) Set the hold state. Release 1. extent=None. shape=None. alpha=None. filternorm=1. cmap=None.005 0.025 0. the current axes and figure will be cleared on the next plot command imshow(X. filterrad=4. vmin=None. interpolation=None.030 0. Else set the hold state to boolean value b.000 40 Histogram of IQ : µ =100.0. vmax=None. When hold is False. resample=None. If hold is None (default). subsequent plot commands will be added to the current axes.1. **kwargs) call signature: 36.015 0.0. matplotlib. imlim=None. Examples: •toggle hold: >>> hold() •turn hold on: >>> hold(True) •turn hold off >>> hold(False) When hold is True.Matplotlib.010 0. MxN float arrays may be normalised. **kwargs) Display the image in X to current axes.6 0. aspect=None. vmax=None.0 to 1. If None.cmap value. vmin=None. cm.image. eg.0.9 0. cmap=None. changes the image aspect ratio to match that of the axes 468 Chapter 36.2 0.1 0. X can have the following shapes: •MxN – luminance (grayscale.8 0. origin=None.3 0. alpha=None. norm=None.cm.jet. If X is an array. cmap is ignored when X has RGB(A) information aspect: [ None | ‘auto’ | ‘equal’ | scalar ] If ‘auto’. default to rc image.AxesImage instance is returned.7 0.Colormap instance. Release 1. An matplotlib. X may be a float array.0 time (s) imshow(X.4 0.1 5 4 3 2 1 Comparison of model with data 0 0.0.5 0. matplotlib axes . interpolation=None. extent=None. float array only) •MxNx3 – RGB (float or uint8 array) •MxNx4 – RGBA (float or uint8 array) The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0. a uint8 array or a PIL image. Keyword arguments: cmap: [ None | Colormap ] A matplotlib.Matplotlib. 0.0.0 which means that any sum of pixel weights must be equal to 1.1. the min and max of the luminance values will be used.origin.axes 469 . If extent is not None. the axes aspect ratio is changed to match that of the extent. The default assigns zero-based row.interpolation. Release 1. ‘hanning’. ‘sinc’. and extent is None. default to rc image. column indices to the x. it corrects only integers according to the rule of 1. if filternorm = 1. If None. i.0] index of the array in the upper left or lower left corner of the axes. ‘hamming’. rows) ] For raw buffer images filternorm: A parameter for the antigrain image resize filter. matplotlib.colors. alpha: scalar The alpha blending value. the filter normalizes integer values and corrects the rounding errors. ‘spline16’. ‘hermite’. ‘gaussian’.e. y centers of the pixels. default to rc image. bottom.1 If ‘equal’. default to rc image. vmin/vmax: [ None | scalar ] Used to scale a luminance image to 0-1. the filter function must produce a graph of the proper shape. ‘quadric’. ‘spline36’. shape: [ None | scalars (columns. ‘catrom’. If None. ‘mitchell’. interpolation: Acceptable values are None. top) ] Data limits for the axes. when interpolation is one of: ‘sinc’. See also the filternorm and filterrad parameters norm: [ None | Normalize ] An matplotlib. If either is None. ‘bicubic’. extent: [ None | scalars (left. the settings for vmin and vmax will be ignored.Normalize instance. Note if norm is not None. So. between 0 (transparent) and 1 (opaque) or None origin: [ None | ‘upper’ | ‘lower’ ] Place the [0. It doesn’t do anything with the source floating point values. filterrad: The filter radius for filters that have a radius parameter. This scales luminance -> 0-1 norm is only used for an MxN float array. changes the axes aspect ratio to match that of the image. ‘kaiser’. ‘nearest’. ‘lanczos’ If interpolation is None. ‘bessel’. From the antigrain documentation.Matplotlib. ‘lanczos’ or ‘blackman’ Additional kwargs are Artist properties: if 36.aspect value. default is normalization(). right. ‘bilinear’. None. Transform) | Patch | None ] a callable function a matplotlib.0 transparent through 1.transforms. Release 1. matplotlib axes .Figure instance an id string any string [True | False] [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 3 2 1 0 1 2 33 2 1 0 1 2 3 470 Chapter 36.Matplotlib.0 opaque) [True | False] an Axes instance a matplotlib.1 Property agg_filter alpha animated axes clip_box clip_on clip_path contains figure gid label lod picker rasterized snap transform url visible zorder Example: Description unknown float (0.0.figure.Bbox instance [True | False] [ (Path. ’label2’. **kwargs) Place a legend on the current axes at location loc. ’label3’) ) To make a legend for a list of lines and labels: legend( (line1. loc=’upper left’) or: legend( (line1. ’label3’) ) To make a legend at a given location. line2. ’label2’. To make a legend with existing lines: legend() legend() by itself will try and build a legend using the label property of the lines/patches/collections. label=’my data’) or: line.Matplotlib.0.set_label(’my data’). Labels are a sequence of strings and loc can be a string or an integer specifying the legend location. ’label2’. ’label3’). line2.1. (’label1’. matplotlib. If label is set to ‘_nolegend_’. ishold() return the HOLD status of the axes legend(*args. ’label2’. line3). line3). To automatically generate the legend from labels: legend( (’label1’. **kwargs) call signature: legend(*args. invert_yaxis() Invert the y-axis. the item will not be shown in legend. You can set the label of a line by doing: plot(x.axes 471 . using a location argument: legend( (’label1’. (’label1’. loc=2) The location codes are 36.1 in_axes(mouseevent) return True if the given mouseevent (in display coords) is in the Axes invert_xaxis() Invert the x-axis. y. Release 1. ’label3’). use rc settings. If prop is a dictionary. The legend location can be specified in other coordinate. Keyword arguments: prop: [ None | FontProperties | dict ] A matplotlib. loc = ‘upper right’. If None.5. use rc shadow: [ None | False | True ] If True. draw a shadow behind legend. If None. For example. use rc settings. numpoints: integer The number of points in the legend for line scatterpoints: integer The number of points in the legend for scatter plot scatteroffsets: list of floats a list of yoffsets for scatter symbols in legend markerscale: [ None | scalar ] The relative size of legend markers vs. bbox_to_anchor = (0. default is 1 mode [[ “expand” | None ]] if mode is “expand”.Matplotlib. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.font_manager. matplotlib axes . Default is True fancybox: [ None | False | True ] if True. 0. If None. a new instance will be created with prop. draw a frame with a round fancybox.1 Location String ‘best’ ‘upper right’ ‘upper left’ ‘lower left’ ‘lower right’ ‘right’ ‘center left’ ‘center right’ ‘lower center’ ‘upper center’ ‘center’ Location Code 0 1 2 3 4 5 6 7 8 9 10 Users can specify any arbitrary location for the legend using the bbox_to_anchor keyword argument. Release 1.FontProperties instance.y of the lower-left corner of the legend in axes coords (bbox_to_anchor is ignored). original. frameon: [ True | False ] if True. use rc settings. by using the bbox_transform keyword. ncol [integer] number of columns.5) will place the legend so that the upper right corner of the legend at the center of the axes.0. the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor) bbox_to_anchor [an instance of BboxBase or a tuple of 2 or 4 floats] the bbox that the legend will be anchored. draw a frame. If None. The loc itslef can be a 2-tuple giving x. 472 Chapter 36. Keyword borderpad labelspacing handlelength handletextpad borderaxespad columnspacing Example: Description the fractional whitespace inside the legend border the vertical space between the legend entries the length of the legend handles the pad between the legend handle and text the pad between the axes and legend border the spacing between columns Minimum Message Length Model length Data length Total message length Message length ---> Model complexity ---> Also see Legend guide. tight=None. title [string] the legend title Padding and spacing between various elements use following keywords parameters. Keyword arguments: 36.1 bbox_transform [[ an instance of Transform | None ]] the transform for the bbox. Release 1. Values from rcParams will be used if None. **kwargs) Convenience method for controlling tick locators. transAxes if None. locator_params(axis=’both’.0. matplotlib..axes 473 . a fontsize of 10 points and a handlelength=5 implies a handlelength of 50 points.Matplotlib. These values are measure in font-size units. E.1.g. axes. Default is None. for example: ax. loglog(*args.Axes.set_yscale(). This presently works only for the MaxNLocator used by default on linear axes. matplotlib axes . Transform) | Patch | None ] any matplotlib color a callable function and 474 Chapter 36. or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains Description unknown float (0. tight [True | False | None] Parameter passed to autoscale_view(). which depend on the number of decades in the plot.0.set_yscale() for details nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. Typically one might want to reduce the maximum number of ticks and use tight bounds when plotting small subplots. None defaults to autosubs. **kwargs) Make a plot with log scaling on the x and y axis.transforms.Axes. Remaining keyword arguments are passed to directly to the set_params() method.set_xscale() / matplotlib.Axes.0 transparent through 1. **kwargs) call signature: loglog(*args.1 axis [’x’ | ‘y’ | ‘both’] Axis on which to operate.Bbox instance [True | False] [ (Path.axes. default is ‘both’. Notable keyword arguments: basex/basey: scalar > 1 base of the x/y logarithm subsx/subsy: [ None | sequence ] the location of the minor x/y ticks. autoscale_view() is called automatically after the parameters are changed. nbins=4) Because the locator is involved in autoscaling. Release 1.Matplotlib.axes. see matplotlib.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.locator_params(tight=True.axes.Axes.set_xscale() / matplotlib. loglog() supports all the keyword arguments of plot() matplotlib. but it may be generalized. for no change. Release 1.1 dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.Transform instance a url string [True | False] 1D array 1D array any number Example: margins(*args.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. signatures: margins() returns xmargin.axes 475 . ymargin margins(margin) margins(xmargin. ymargin) 36. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. matplotlib.figure.’ | ’.0.transforms.Matplotlib. stride) float distance in points or callable pick function fn(artist.1.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. **kw) Convenience method to set or retrieve autoscaling margins. The tight parameter is passed to autoscale_view(). for example.5 15 201.0 0..1 100 10-1 10-2 0 102 semilogy 104 103 101 102 101 100 100 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 10-1 -1 0 2 2 2 2 2 2 2 2 2 2 2 2 25 10 10 101 102 103 margins(x=xmargin. interpolation.0 0. then xmargin times the X data interval will be added to each end of that interval before it is used in autoscaling. Release 1. Setting tight to None will preserve the previous setting. Row and column numbering is zero-based. which is executed after a margin is changed. y=ymargin) margins(. Specifying any margin changes only the autoscaling.. (Also. **kwargs) Plot a matrix or array as an image. origin. A single argument specifies both xmargin and ymargin.. matplotlib axes . tight=False) loglog base 4 on x 105Errorbars go negative 5 10 semilogx 1.0 -2 10-1 100 101 102 10 All three forms above set the xmargin and ymargin parameters. All keyword parameters are optional. The matrix will be shown the way it would be printed.5 0. use care in overriding the extent and origin kwargs. and aspect. matshow(Z. Argument: Z anything that can be interpreted as a 2-D array kwargs all are passed to imshow(). no additional padding to match tick marks is usually desired. the default here is True. with the first row at the top. if you want to change them.0. you probably should be using imshow directly in your own version of 476 Chapter 36.Matplotlib. because they interact. on the assumption that when margins are specified. matshow() sets defaults for extent. if xmargin is not None. and the row index corresponds to y. (X[i+1. if ‘flat’. defaults to normalize(). **kwargs) Create a pseudocolor plot of a 2-D array. If either are None. minorticks_off() Remove minor ticks from the axes. **kwargs) pcolor(X. the quadrilateral for C[i. j]). shading: [ ‘flat’ | ‘faceted’ ] If ‘faceted’. specify the (x.cm. pcolor(*args. Y[i+1.Colormap instance. then the last row and column of C will be ignored. matplotlib. (X[i. C is the array of color values. If None. making a rectangular grid. the min and max of the color array C is used. j+1]. a black grid is drawn around each rectangle. j].Normalize instance is used to scale luminance data to 0. they will be expanded as needed into the appropriate 2-D arrays. This kwarg is deprecated. use rc settings. vmin and vmax will be ignored.[i+1. vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data.AxesImage instance.axes 477 . C. if the dimensions are the same. norm: [ None | Normalize ] An matplotlib. Release 1. If either C[i. nothing is plotted. j+1]). [i+1. if given. (X[i+1.colors. [i. edges are not drawn. j+1]). j+1]. **kwargs) call signatures: pcolor(C. j]. Ideally the dimensions of X and Y should be one greater than those of C. X and Y. y) coordinates of the colored quadrilaterals. X. j].image. j]).j] (X or Y at [i. Y[i. contrary to MATLAB.) Returns: an matplotlib. Y[i+1. Keyword arguments: cmap: [ None | Colormap ] A matplotlib. Y. for details. j+1]) is masked. j].1. Y[i. j]. see the Grid Orientation section below. please use ‘edgecolors’ instead: 36. If None. j+1].Matplotlib. minorticks_on() Add autoscaling minor ticks to the axes. Y and C may be masked arrays.0.1. or one of the vertices surrounding C[i.1 matshow. Note that the the column index corresponds to the x-coordinate. If either or both of X and Y are 1-D arrays or column vectors. Default is ‘flat’. If you pass a norm instance.j] has corners at: (X[i. 1. 2. 2. but matplotlib displays the last row and column if X and Y are not specified. 0. 0.Matplotlib. An mpl color or sequence of colors will set the edge color alpha: 0 <= scalar <= 1 or None the alpha blending value Return value is a matplotlib. increasing up. 1. ncolumns) is plotted with the column number as X and the row number as Y. [0. or if X and Y have one more row and column than C. The grid orientation follows the MATLAB convention: an array C with shape (nrows.y) is equivalent to: X = array([[0. len(y)) then you need: pcolor(X. the rc setting is used by default. That is. 3. 3. [1. 2. x). 2. 4]. If ‘none’. 1. except that the Y axis is reversed.T) MATLAB pcolor() always discards the last row and column of C. edges will not be visible. C. 0].0. Release 1. Y. 1. 4]. kwargs can be used to control the PolyCollection properties: Property agg_filter alpha animated antialiased or antialiaseds array axes Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance Continued on next page 478 Chapter 36. 4]]) Y = array([[0. [2.arange(5) y = np. Similarly for meshgrid(): x = np.1 • shading=’flat’ – edgecolors=’none’ • shading=’faceted – edgecolors=’k’ edgecolors: [ None | ‘none’ | color | color sequence] If None. 3. 1. C is taken as C*(*y. 2.Collection instance. 2. 1].T) or: pcolor(C. Y = meshgrid(x. 0. 2]]) so if you have: C = rand( len(x).collection. hence it is plotted the way the array would be printed. matplotlib axes . 1.arange(3) X. [0. that provides the fastest possible rendering with the Agg backend.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’.14 – continued from previous page clim a length 2 sequence of floats clip_box a matplotlib.antialiased’]. An alternative it to set edgecolors to ‘face’. **kwargs) 36. Unfortunately. **kwargs) pcolor(X. this is a version of pcolor that does not draw lines. **kwargs) pcolor(x. Transform) | Patch | None ] cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib. C. ‘dashdot’.Bbox instance clip_on [True | False] clip_path [ (Path.Matplotlib.axes 479 .1. matplotlib. y. Release 1. C. **kwargs) pcolor(xr. which defaults to True. pcolorfast(*args. there seems to be no single combination of parameters that eliminates artifacts under all conditions. yr. Y. In some cases. particularly if alpha is 1.1 Table 36. C. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number Note: the default antialiaseds is taken from rcParams[’patch. and that can handle any quadrilateral grid. Call signatures: pcolor(C. you may be able to reduce rendering artifacts (light or dark patch boundaries) by setting it to False. ‘dotted’ | (offset.transforms.0.figure. **kwargs) pseudocolor plot of a 2-D array Experimental. and a QuadMesh collection in the general quadrilateral case. the min and max of the color array C is used. but the slowest to render. the quadrilateral for C[i. alpha: 0 <= scalar <= 1 or None the alpha blending value Return value is an image if a regular or rectangular grid is specified. (x0.j]. Release 1. and svg backends. pdf. nc +1) that specify the (x. norm: [ None | Normalize ] An mcolors. **kwargs) 480 Chapter 36. The cells need not be rectangular. Note that the the column index corresponds to the x-coordinate.j]). All cells are rectangles of the same size. defaults to normalize() vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data. (X[i+1. Y. and if found to be uniform the fast version is used. y1) is the outermost corner of cell (nr-1.y) coordinates of the corners of the colored quadrilaterals. It may produce faster and more compact output using ps. giving the x and y boundaries of the cells.j+1]). etc.j+1]). however.y1] then x goes from x0 to x1 as the second index of C goes from 0 to nc. If you pass a norm instance. for details.Y[i. Let (nr. pcolormesh(*args.Normalize instance is used to scale luminance data to 0. and (x1. This is the fastest version.) X and Y are 2D arrays with shape (nr +1.Matplotlib. **kwargs) xr.Y[i+1. respectively. **kwargs) call signatures: pcolormesh(C) pcolormesh(X. C.1 C is the 2D array of color values corresponding to quadrilateral cells. [0. and the row index corresponds to y.j+1]. use rc settings. yr specify the ranges of x and y corresponding to the rectangular region bounding C.j]).1. x. If either are None. (The grid is checked. If None.nc]. see the “Grid Orientation” section below. Hence the cells are rectangular but the grid may be nonuniform. x1] and: yr = [y0. (X[i+1. The speed is intermediate. y are 1D arrays of length nc +1 and nr +1. If: xr = [x0.0.Y[i+1.Y[i. pcolor(C. This is the most general. **kwargs) is equivalent to pcolor([0.j] has corners at (X[i.j]. nc) be its shape. y0) is the outermost corner of cell (0. C) pcolormesh(C. If None. Optional keyword arguments: cmap: [ None | Colormap ] A cm Colormap instance from cm.nr]. C may be a masked array.j+1]. matplotlib axes .0). (X[i. vmin and vmax will be None. nc-1). 1. contrary to MATLAB. Keyword arguments: cmap: [ None | Colormap ] A matplotlib. pcolor() simply does not draw quadrilaterals with masked colors or vertices.Normalize instance is used to scale luminance data to 0. matplotlib.QuadMesh properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. use rc settings. Release 1. An mpl color or sequence of colors will set the edge color alpha: 0 <= scalar <= 1 or None the alpha blending value Return value is a matplotlib. If None. If ‘None’.1. edges will not be visible. kwargs can be used to control the matplotlib.collection. but X and Y may not. This kwarg is deprecated. vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data.axes .Bbox instance [True | False] [ (Path. Default is ‘flat’.Colormap instance.cm.1 C may be a masked array. If either are None.Matplotlib. if ‘flat’. the min and max of the color array C is used. vmin and vmax will be ignored. If None. Masked array support is implemented via cmap and norm. defaults to normalize(). norm: [ None | Normalize ] A matplotlib.QuadMesh object. in contrast. shading: [ ‘flat’ | ‘faceted’ | ‘gouraud’ ] If ‘faceted’. If you pass a norm instance. the rc setting is used by default. please use ‘edgecolors’ instead: • shading=’flat’ – edgecolors=’None’ • shading=’faceted – edgecolors=’k’ edgecolors: [ None | ‘None’ | color | color sequence] If None.0. edges are not drawn. a black grid is drawn around each rectangle.colors. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function Continued on next page 481 36.collections.transforms. autopct=None. ’c’. autopct=None. labeldistance=1. pctdistance=0. pick(*args) call signature: pick(mouseevent) each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set pie(x. explode=None. ’w’).1 Table 36.Matplotlib. shadow=False. labels=None. 482 Chapter 36. The fractional area of each wedge is given by x/sum(x). pctdistance=0.59999999999999998. Keyword arguments: explode: [ None | len(x) sequence ] If not None.0. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number See Also: pcolor() For an explanation of the grid orientation and the expansion of 1-D X and/or Y to 2-D arrays. ‘dashdot’. ‘dotted’ | (offset. colors=(’b’. ’r’. colors=None. ’k’.1. labels=None.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. Release 1. explode=None. labeldistance=1. If sum(x) <= 1.1000000000000001) call signature: pie(x. ’y’.15 – continued from previous page edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib. matplotlib axes . then the values of x give the fractional area directly and the array will not be normalized. is a len(x) array which specifies the fraction of the radius with which to offset each wedge.6. shadow=False) Make a pie chart of array x.figure. ’g’. ’m’. text. Release 1. then the corresponding columns will be plotted.6.patches. y. ’g-’) Return value is a list of lines that were added. **kwargs) Plot lines and/or markers to the Axes.8]) Return value: If autopct is None. If it is a function.1 colors: [ None | color sequence ] A sequence of matplotlib color args through which the pie chart will cycle. If it is a format string. labeldistance: scalar The radial distance at which the pie labels are drawn shadow: [ False | True ] Draw a shadow beneath the pie. each of the following is legal: plot(x.: figure(figsize=(8. labels: [ None | len(x) sequence of strings ] A sequence of strings providing the labels for each wedge autopct: [ None | format string | format function ] If not None. y1.8)) ax = axes([0.N-1 but with red plusses If x and/or y is 2-dimensional. ’g^’. allowing for multiple x. where patches and texts are as above. The label will be placed inside the wedge. For example. matplotlib.8.1.1. fmt groups can be specified. 0. args is a variable length argument.plot(x1. autotexts). plot(*args. and y using default line style and color and y using blue circle markers using x as index array 0.Matplotlib.1.. Ignored if autopct is None. is a string or function used to label the wedges with their numeric value. the label will be fmt%pct. The following format string characters are accepted to control the line style or marker: 36. Eg.axes 483 . 0.Wedge instances • texts is a list of the label matplotlib. return the tuple (patches. pctdistance: scalar The ratio between the center of each pie slice and the start of the text generated by autopct. y pairs with an optional format string. return the tuple (patches. and autotexts is a list of Text instances for the numeric labels.0. default is 0. 0. y2. texts): • patches is a sequence of matplotlib. If autopct is not None. ’r+’) # # # # plot x plot x plot y ditto. x2. texts. The pie chart will probably look best if the figure and axes are square. as in: a.Text instances. ’bo’) plot(y) plot(y. it will be called. y) plot(x. y. An arbitrary number of x. RGB or RGBA tuples ((0. Release 1. the string specifications can be used in place of a fmt group.’ ’:’ ’. as in ’bo’ for blue circles. you can specify colors in many weird and wonderful ways.Matplotlib. anitialising.8’). Of these.0. marker face color.1.’ ’o’ ’v’ ’^’ ’<’ ’>’ ’1’ ’2’ ’3’ ’4’ ’s’ ’p’ ’*’ ’h’ ’H’ ’+’ ’x’ ’D’ ’d’ ’|’ ’_’ description solid line style dashed line style dash-dot line style dotted line style point marker pixel marker circle marker triangle_down marker triangle_up marker triangle_left marker triangle_right marker tri_down marker tri_up marker tri_left marker tri_right marker square marker pentagon marker star marker hexagon1 marker hexagon2 marker plus marker x marker diamond marker thin_diamond marker vline marker hline marker The following color abbreviations are supported: character ‘b’ ‘g’ ‘r’ ‘c’ ‘m’ ‘y’ ‘k’ ‘w’ color blue green red cyan magenta yellow black white In addition.1)) or grayscale intensities as a string (’0. linewidth. Line styles and colors are combined in a single format string. but the tuple forms can be used only as kwargs.0.’ ’. etc. including full names (’green’). hex strings (’#008000’). Here is an example: 484 Chapter 36.1 character ’-’ ’--’ ’-. You can use this to set a line label (for auto legends). matplotlib axes . The kwargs can be used to set line properties (any property that has a set_* method). [1.0 transparent through 1. label=’line 1’.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.1.lines.4.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color 36.3]. the kwargs apply to all those lines.1 plot([1. matplotlib. y1. Release 1. For example.transforms.Bbox instance [True | False] [ (Path. x2.’ | ’. [1.0. linewidth=2) plot([1.2.2. y.2. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x. 10]) legend() If you make multiple lines with one plot command. linestyle=’dashed’. markerfacecolor=’blue’. You do not need to use format strings. marker. ’go-’.g. linestyle. which are just abbreviations. color=’green’.figure. and markercolor with: plot(x. antialised=False) Neither line will be antialiased. marker=’o’.3].: plot(x1.axes 485 .9]. All of the line properties can be controlled by keyword arguments. 4. e. 0. markersize=12). y2. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. ’rs’.Matplotlib.3]. See :class:‘~matplotlib. label=’line 2’) axis([0. The kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt Description unknown float (0.Line2D‘ for details. you can set the color. fmt=’bo’. the default is True. xdate=True. y. ydate=False. stride) float distance in points or callable pick function fn(artist. the y-axis will be labeled with dates.dates. **kwargs) call signature: plot_date(x. Note if you are using custom date tickers and formatters. Keyword arguments: fmt: string The plot format string. tz=None. matplotlib axes .AutoDateLocator (if the tick locator is not already set to a matplotlib.transforms.Matplotlib. y.0. xdate: [ True | False ] If True. and the axis is labeled accordingly. If None.AutoDateFormatter (if the tick formatter is not already set to a matplotlib. except the x or y (or both) data is considered to be dates. tz: [ None | timezone string ] The time zone to use in labeling dates.1 markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder float None | integer | (startind. ydate: [ False | True ] If True. if defined. tz=None.dates.DateFormatter instance). xdate=True. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. defaults to rc value. **kwargs) Similar to the plot() command. ydate=False.Transform instance a url string [True | False] 1D array 1D array any number kwargs scalex and scaley.dates. Valid kwargs are Line2D properties: Property Description 486 Chapter 36. fmt=’bo’. x and/or y can be a sequence of dates represented as float days since 0001-01-01 UTC.DateLocator instance) and the default tick formatter to matplotlib. plot_date(x.dates. Release 1. the x-axis will be labeled with dates. it may be necessary to set the formatters/locators after the call to plot_date() since plot_date() will set the default tick locator to matplotlib. are passed on to autoscale_view() to determine whether the x and y axes are autoscaled. ’ | ’.figure.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.transforms. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.transforms.0 transparent through 1.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. Release 1.0.axes 487 .0 opaque) [True | False] [True | False] an Axes instance a matplotlib.Transform instance a url string [True | False] 1D array 1D array any number See Also: dates for helper functions 36.Bbox instance [True | False] [ (Path.1 agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder unknown float (0.1.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. stride) float distance in points or callable pick function fn(artist. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Matplotlib. matplotlib. This can be different from NFFT. noverlap=0. sides=’default’. pad_to=None. sides=’default’. window=<function window_hanning at 0x3a178c0>.detrend_none. **kwargs) The power spectral density by Welch’s average periodogram method. window=mlab. allowing for more detail. this can give more points in the plot. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. pad_to: integer The number of points to which the data segment is padded when performing the FFT. The pylab module defines detrend_none(). Release 1. which specifies the number of data points used. 488 Chapter 36. numpy. The default is window_hanning(). While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). with a scaling to correct for power loss due to windowing.blackman(). freqs. NFFT=256.window_hanning.hamming(). Must be even. Fs=2. scale_by_freq=None. To create window vectors see window_hanning(). but you can use a custom function as well. If a function is passed as the argument. scale_by_freq=None. scipy. numpy. Fc=0. etc. noverlap=0. detrend=mlab.1 date2num(). in matplotlib is it a function. detrend: callable The function applied to each segment before fft-ing. noverlap: integer The number of points of overlap between blocks. Default gives the default behavior. detrend_mean(). Fs=2. a power 2 is most efficient. The default value is 256. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. psd(x. while ‘twosided’ forces two-sided. Fc=0. NFFT=256. where the detrend parameter is a vector. noverlap gives the length of the overlap between segments. it must take a data segment as an argument and return the windowed version of the segment.signal(). scipy. matplotlib axes . It is used to calculate the Fourier frequencies. num2date() and drange() for help on creating the required floating point dates. The default value is 0 (no overlap). The default value is 2. designed to remove the mean or linear trend. ‘onesided’ forces the return of a one-sided PSD. **kwargs) call signature: psd(x.signal. Fs is the sampling frequency.0. numpy. pad_to=None. Fs: scalar The sampling frequency (samples per time unit).bartlett(). Each segment is detrended by function detrend and windowed by function window. The default is None. The vector x is divided into NFFT length segments.Matplotlib. The |fft(i)|2 of each segment i are averaged to compute Pxx. which returns one-sided for real data and both for complex data.get_window(). and detrend_linear(). window_none(). in cycles per time unit. This corresponds to the n parameter in the call to fft(). window: callable or ndarray A function or a vector of length NFFT. Unlike in MATLAB. detrend=<function detrend_none at 0x3a1c668>. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.Matplotlib.’ | ’. Fc: integer The center frequency of x (defaults to 0). though Pxx itself is returned.figure. event) 36. matplotlib. which gives density in units of Hz^-1. For plotting. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Bbox instance [True | False] [ (Path. stride) float distance in points or callable pick function fn(artist. which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband. the power is plotted as 10 log10 (P xx ) for decibels. References: Bendat & Piersol – Random Data: Analysis and Measurement Procedures.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. Returns the tuple (Pxx.transforms. John Wiley & Sons (1986) kwargs control the Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker Description unknown float (0. Release 1. freqs).0 transparent through 1.0.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.1 scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency.axes 489 . matplotlib axes .Matplotlib.05 0.15 0.1 pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.10 0.150 10 20 30 40 50 60 70 80 900 2 4 6 8 10 10 20 30 Frequency 40 50 quiver(*args.transforms.00 0.Transform instance a url string [True | False] 1D array 1D array any number Example: Power Spectral Density (dB/Hz) 0. call signatures: 490 Chapter 36.05 0. **kw) Plot a 2-D field of arrows.0. Release 1.10 0. y) to (x+u. V. matplotlib. C. but masked X. or sqrt(X^2+Y^2) data units The arrows scale differently depending on the units. C may be masked arrays. For ‘x’ or ‘y’.g. the arrow points from (x. angles: [’uv’ | ‘xy’ | array] With the default ‘uv’. Keyword arguments: units: [’width’ | ‘height’ | ‘dots’ | ‘inches’ | ‘x’ | ‘y’ | ‘xy’] arrow units.meshgrid().0. a simple autoscaling algorithm 36. For ‘width or ‘height’. **kw) U. based on the figure dpi • ‘x’. Release 1. V. With ‘xy’. for ‘dots’ or ‘inches’. ‘y’. Y: The x and y coordinates of the arrow locations (default is tail of arrow. for other units. see pivot kwarg) U. the arrow aspect ratio is 1. resizing does not change the arrows. Alternatively. V. arbitrary angles may be specified as an array of values in degrees. quiver(U. V. CCW from the x-axis.1. the arrow dimensions except for length are in multiples of this unit. If None. y+v).axes 491 . quiver(X. when the the window is resized. quiver(X. U.Matplotlib. e. V: give the x and y components of the arrow vectors C: an optional array used to map colors to the arrows All arguments may be 1-D or 2-D arrays or sequences. they will be generated as a uniform grid. If U and V are 2-D arrays but X and Y are 1-D. scale: [ None | float ] data units per arrow length unit. the arrow size increases with the width and height of the axes. • ‘width’ or ‘height’: the width or height of the axes • ‘dots’ or ‘inches’: pixels or inches.1 quiver(U. **kw) Arguments: X. Y. V. **kw) C. the arrows get larger as one zooms in. then X and Y will be expanded with numpy. m/s per plot width. Y. Y. If X and Y are absent. **kw) U. a smaller scale parameter makes the arrow longer. and if len(X) and len(Y) match the column and row dimensions of U. so that if U*==*V the angle of the arrow on the plot is 45 degrees CCW from the x-axis. Y are not supported at present. the arrow size is independent of the zoom state. respectively. or ‘xy’: X. in units of head length. You will probably do best to leave minshaft alone. or small arrows will look terrible! Default is 1 minlength: scalar minimum length as a multiple of shaft width. default is 4. use “angles=’xy’. based on the average vector length and the number of vectors.005 times the width of the plot. to make the head a triangle. make headaxislength the same as headlength. pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point. with u and v having the same units as x and y. If C has been set. if scale_units is ‘inches’.0. The arrow length unit is given by the scale_units parameter scale_units: None.transforms. Do not set this to less than 1.5 minshaft: scalar length below which arrow scales.0. color has no effect. above. if an arrow length is less than this.0). scale=1”. or any of the units options. Transform) | Patch | None ] a colormap or registered colormap name Continued on next page Chapter 36. scale_units=’xy’. PolyCollection keyword arguments: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap Additional Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.Bbox instance [True | False] [ (Path. then the vector will be 0. scale is 2. matplotlib axes 492 .1 is used. color: [ color | color sequence ] This is a synonym for the PolyCollection facecolor kwarg. hence the name pivot. The defaults give a slightly swept-back arrow.5 x-axis units. To make the arrow more pointed. reduce headwidth or increase headlength and headaxislength. a typical starting value is about 0. default is 3 headlength: scalar head length as multiple of shaft width.v) = (1. plot a dot (hexagon) of this diameter instead. the arrow rotates about this point. If scale_units is ‘x’ then the vector will be 0.5 inches long. If scale_units is ‘width’. scale down all the head parameters. Release 1. and (u. headwidth: scalar head width as multiple of shaft width. To make the head smaller relative to the shaft. default is 5 headaxislength: scalar head length at shaft intersection. then the vector will be half the width of the axes. width: shaft width in arrow units. default depends on choice of units. and number of vectors.Matplotlib. To plot vectors in the x-y plane. Default is 1. For example. linewidths and edgecolors can be used to customize the arrow outlines. U: The length of the key label: a string with the length and units of the key Keyword arguments: coordinates = [ ‘axes’ | ‘figure’ | ‘data’ | ‘inches’ ] Coordinate system and units for X.Matplotlib. label. Y: ‘axes’ and ‘figure’ are normalized coordinate systems with 0. X. X.0 at the lower left corner. Y: The location of the key.1. with 0.0. Y. ‘inches’ is position in the figure in inches.1 in the upper right. matplotlib.19 – continued from previous page color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. **kw) Arguments: Q: The Quiver instance returned by a call to quiver.axes 493 . **kw) Add a key to a quiver plot. call signature: quiverkey(Q. 36. ‘dashdot’. U. ‘data’ are the axes data coordinates (used for the locations of the vectors in the quiver plot itself).0 in the lower left and 1.figure. additional explanation follows. ‘dotted’ | (offset.1 Table 36. Release 1. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number quiverkey(*args. X. It is a scalar or an array of the same length as x and y. If labelpos is ‘E’. X. Keyword arguments: s: size in points^2. c=’b’. vmin=None. If labelpos is ‘N’ or ‘S’. Collection instances are not supported. N. alpha=None. style. below. matplotlib axes . c can be a 2-D array in which the rows are RGB or RGBA. **kwargs) call signatures: scatter(x. cmap=None. norm=None. c can be a single color format string. to the right. weight by the Any additional keyword arguments are used to override vector properties taken from Q. c=’b’. At present. or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Y is somewhere in the middle of the arrow+label key object. y. reset_position() Make the original position the active position scatter(x.0. c: a color.1 labelcolor: defaults to default Text color. redraw_in_frame() This method can only be used after an initial draw which caches the renderer. marker: can be one of: 494 Chapter 36. Y positions the head. s=20. or a sequence of color specifications of length N. alpha=None. variant. It is used to efficiently update Axes data (axis ticks.Matplotlib. Y.1 color: overrides face and edge colors from Q. linewidths=None. norm=None. vmax=None. size. labelpos = [ ‘N’ | ‘S’ | ‘E’ | ‘W’ ] Position the label above. where x. Y give the position of the middle of the key arrow. and if labelpos is ‘W’. linewidths=None. **kwargs) Make a scatter plot of x versus y. cmap=None. y are converted to 1-D sequences which must be of the same length. marker=’o’. labelsep: Distance in inches between the arrow and the label. verts=None. The positioning of the key depends on X. s=20. verts=None. labels. vmax=None. in either of these two cases. y. X. and labelpos. faceted=True. etc are not updated) relim() Recompute the data limits based on current artists. Release 1. Default is 0. X. respectively. Y positions the tail. marker=’o’. to the left of the arrow. fontproperties: A dictionary with keyword arguments accepted FontProperties initializer: family. however. Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. coordinates. vmin=None. Alternatively. norm is only used if c is an array of floats. s.1.colors. cmap: [ None | Colormap ] A matplotlib. verts = verts. Release 1. regular symbol. your settings for vmin and vmax will be ignored.Normalize instance is used to scale luminance data to 0. in which case all masks will be combined and only unmasked points will be plotted. If None. y. the min and max of the color array C is used. and c may be masked arrays. numsides: the number of sides style: the style of the regular symbol: Value 0 1 2 3 Description a regular polygon a star-like symbol an asterisk a circle (numsides and angle is ignored) angle: the angle of rotation of the symbol Finally. use the default normalize(). Any or all of x. marker can be (verts.1 Value ’s’ ’o’ ’^’ ’>’ ’v’ ’<’ ’d’ ’p’ ’h’ ’8’ ’+’ ’x’ Description square circle triangle up triangle right triangle down triangle left diamond pentagon hexagon octagon plus cross The marker can also be a tuple (numsides. angle). use the kwarg combination marker = None. norm: [ None | Normalize ] A matplotlib.axes 495 .0. If None.Colormap instance or registered name. 1. which will create a custom. alpha: 0 <= scalar <= 1 or None The alpha value for the patches 36. y) vertices for a custom scatter symbol.colors. 0): verts is a sequence of (x. Other keyword arguments: the color mapping and normalization arguments will be used only if c is an array of floats. cmap is only used if c is an array of floats. Note if you pass a norm instance. If either are None.Matplotlib.cmap. defaults to rc image. style. matplotlib. vmin/vmax: vmin and vmax are used in conjunction with norm to normalize luminance data. transforms.Figure instance an id string any string [’solid’ | ‘dashed’. defaults to (lines.Bbox instance [True | False] [ (Path. in particular: edgecolors: The string ‘none’ to plot faces with no outlines facecolors: The string ‘none’ to plot unfilled outlines Here are the standard descriptions of all the Collection kwargs: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized snap transform url urls visible zorder Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib.linewidth.).1 linewidths: [ None | scalar | sequence ] If None. matplotlib axes . as required by RegularPolyCollection. ‘dashdot’. Optional kwargs control the Collection properties. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number 496 Chapter 36. ‘dotted’ | (offset. Note that this is a tuple. Release 1.Matplotlib.0. and if you set the linewidths argument you must set it as a sequence of floats.figure. Release 1.0.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.1. semilogx() supports all the keyword matplotlib.Axes.axes 497 .’ | ’. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. nonposx: [’mask’ | ‘clip’ ] non-positive values in x can be masked as invalid.figure. or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew arguments of plot() and Description unknown float (0.axes. **kwargs) call signature: semilogx(*args. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.set_xscale(). None defaults to autosubs. **kwargs) Make a plot with log scaling on the x axis.Matplotlib.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points 36. Notable keyword arguments: basex: scalar > 1 base of the x logarithm subsx: [ None | sequence ] The location of the minor xticks.1 A Collection instance is returned. semilogx(*args.0 transparent through 1.Bbox instance [True | False] [ (Path.transforms. which depend on the number of decades in the plot. see set_xscale() for details. matplotlib. None defaults to autosubs. see set_yscale() for details.transforms.axes.set_yscale().0 transparent through 1. Notable keyword arguments: basey: scalar > 1 Base of the y logarithm subsy: [ None | sequence ] The location of the minor yticks. nonposy: [’mask’ | ‘clip’ ] non-positive values in y can be masked as invalid.Axes.0. **kwargs) Make a plot with log scaling on the y axis.Transform instance a url string [True | False] 1D array 1D array any number See Also: loglog() For example code and figure semilogy(*args. matplotlib axes . or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha Description unknown float (0.1 markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder any matplotlib color any matplotlib color float None | integer | (startind. which depend on the number of decades in the plot. stride) float distance in points or callable pick function fn(artist. Release 1. **kwargs) call signature: semilogy(*args. semilogy() supports all the keyword matplotlib.0 opaque) arguments of plot() and 498 Chapter 36. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Matplotlib. Bbox instance [True | False] [ (Path.figure.0. Release 1.’ | ’. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.axes 499 .1 animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [True | False] [True | False] an Axes instance a matplotlib. matplotlib.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.transforms.Transform instance a url string [True | False] 1D array 1D array any number See Also: loglog() For example code and figure 36.1.Matplotlib.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.transforms. stride) float distance in points or callable pick function fn(artist. anchor value ‘C’ ‘SW’ ‘S’ ‘SE’ etc.Matplotlib. ‘box’ does not allow axes sharing. Release 1. aspect=1 is the same as aspect=’equal’. anchor=None) aspect value ‘auto’ ‘normal’ ‘equal’ num adjustable value ‘box’ ‘datalim’ ‘box-forced’ description change physical size of axes change xlim or ylim same as ‘box’. as this can cause unintended side effect. but axes can be shared description automatic. deprecated same scaling from data to plot units for x and y a circle will be stretched such that the height is num times the width. For cases when sharing axes is fine. adjustable=None.0.1 set_adjustable(adjustable) ACCEPTS: [ ‘box’ | ‘datalim’ | ‘box-forced’] set_anchor(anchor) anchor value ‘C’ ‘SW’ ‘S’ ‘SE’ ‘E’ ‘NE’ ‘N’ ‘NW’ ‘W’ description Center bottom left bottom bottom right right top right top top left left set_aspect(aspect. use ‘box-forced’. description centered lower left corner middle of bottom edge lower right corner set_autoscale_on(b) Set whether autoscaling is applied on plot commands accepts: [ True | False ] set_autoscalex_on(b) Set whether autoscaling for the x-axis is applied on plot commands 500 Chapter 36. fill position rectangle with data same as ‘auto’. matplotlib axes . Figure instance set_frame_on(b) Set whether the axes rectangle patch is drawn ACCEPTS: [ True | False ] set_navigate(b) Set whether the axes responds to navigation toolbar commands ACCEPTS: [ True | False ] 36.set_cursor_props((linewidth.1. color)) ACCEPTS: a (float. color) tuple set_figure(fig) Set the class:~matplotlib.1 accepts: [ True | False ] set_autoscaley_on(b) Set whether autoscaling for the y-axis is applied on plot commands accepts: [ True | False ] set_axes_locator(locator) set axes_locator ACCEPT [a callable object which takes an axes instance and renderer and] returns a bbox. set_cursor_props(*args) Set the cursor property as: ax. matplotlib.axes 501 .0. Release 1.Axes figure accepts a class:~matplotlib.figure. color) or: ax.Matplotlib. set_axis_bgcolor(color) set the axes background color ACCEPTS: any matplotlib color .set_cursor_props(linewidth.axes.see colors() set_axis_off() turn off the axis set_axis_on() turn on the axis set_axisbelow(b) Set whether the axis ticks and gridlines are above or below most artists ACCEPTS: [ True | False ] set_color_cycle(clist) Set the color cycle for any future plot commands on this Axes. clist is a list of mpl color specifiers. **kwargs) call signature: set_title(label. but which may be modified by apply_aspect(). Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.figure.1 set_navigate_mode(b) Set the navigation toolbar button status. **kwargs): Set the title for the axes.Figure instance a matplotlib. kwargs are Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha Description unknown float (0. set_position(pos. or pos can be a Bbox There are two position variables: one which is ultimately used. Warning: this is not a user-API function. which=’both’) Set the axes position with: pos = [left.Bbox instance [True | False] [ (Path.transforms. width.0.0 transparent through 1. Release 1.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] 502 Chapter 36.Matplotlib. Optional keyword arguments: which value ‘active’ ‘original’ ‘both’ description to change the first to change the second to change both set_rasterization_zorder(z) Set zorder value below which artists will be rasterized set_title(label. and a second which is the starting point for apply_aspect(). fontdict=None.font_manager. height] in relative 0.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. fontdict=None. matplotlib axes .1 coords. bottom. set_xlabel(xlabel. **kwargs) Set the label for the xaxis. fontdict=None. matplotlib. fontdict=None.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. labelpad=None. labelpad=None.1. **kwargs) call signature: set_xlabel(xlabel. upper=None) Set the lower and upper numerical bounds of the x-axis.23 – continued fro label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.1 Table 36. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: str See Also: text() for information on how override and the optional args work set_xbound(lower=None.Matplotlib.axes 503 . It will not change the _autoscaleXon attribute.0. This method will honor axes inversion regardless of parameter order. labelpad is the spacing in points between the label and the x-axis Valid kwargs are Text properties: 36. Release 1. y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.0.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. Release 1. matplotlib axes .figure.transforms.font_manager.Matplotlib.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.0 transparent through 1.Figure instance a matplotlib. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: str See Also: 504 Chapter 36.Bbox instance [True | False] [ (Path.1 Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder Description unknown float (0. right)) set_xlim(left. 0) so 5000 years ago is on the left of the plot and the present is on the right. may still be used right: scalar the right xlim.0. accepts: float in range 0 to 1 set_xscale(value. **kwargs) call signature: set_xscale(value) Set the scaling of the x-axis: ‘linear’ | ‘log’ | ‘symlog’ ACCEPTS: [’linear’ | ‘log’ | ‘symlog’] Different kwargs are accepted. off (False. default).axes 505 . emit=True. suppose x is years before present. the previous name. **kwargs): Set the data limits for the xaxis Examples: set_xlim((left. Then one might use: set_ylim(5000. Release 1. m times the data interval will be added to each end of that interval before it is used in autoscaling.Matplotlib. auto=False. xmin. **kw) call signature: set_xlim(self. depending on the scale: ‘linear’ ‘log’ 36. right) set_xlim(left=1) # right unchanged set_xlim(right=1) # left unchanged Keyword arguments: left: scalar the left xlim.1. the previous name.1 text() for information on how override and the optional args work set_xlim(left=None. *args. Returns the current xlimits as a length 2 tuple ACCEPTS: len(2) sequence of floats set_xmargin(m) Set padding of X data limits prior to autoscaling. may still be used emit: [ True | False ] notify observers of lim change auto: [ True | False | None ] turn x autoscaling on (True). For example. matplotlib. right=None. xmax. or leave unchanged (None) Note: the left (formerly xmin) value may be greater than the right (formerly xmax). fontdict=None.font_manager. Return a list of axis text instances. kwargs set the Text properties. 3.1 basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. 6. **kwargs) call signature: set_xticklabels(labels. 7. 8. in a log10 scale: [0. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. 9] will place 10 logarithmically spaced minor ticks between each major tick.0.figure. 2. fontdict=None. 1. Release 1. 4. 3. Should be a sequence of integers. 7. minor=False. 1.transforms. 6. **kwargs) Set the xtick labels with list of strings labels.0 transparent through 1. matplotlib axes . in a log10 scale: [0. 5. minor=False. 9] will place 10 logarithmically spaced minor ticks between each major tick.Bbox instance [True | False] [ (Path. For example.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) 506 Chapter 36. Should be a sequence of integers. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick. set_xticklabels(labels. 8. For example. Valid properties are Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing Description unknown float (0. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. 5. 4. subsx/subsy: Where to place the subticks between each major tick. x) within which the plot is linear (to avoid having the plot go to infinity around zero).0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.Matplotlib.Figure instance a matplotlib. 2. 0.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.25 – continued fro lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. matplotlib. **kwargs) Set the label for the yaxis labelpad is the spacing in points between the label and the y-axis Valid kwargs are Text properties: Property Description 36.1. **kwargs) call signature: set_ylabel(ylabel. fontdict=None.1 Table 36. Release 1. set_ylabel(ylabel.axes 507 . It will not change the _autoscaleYon attribute. upper=None) Set the lower and upper numerical bounds of the y-axis. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: sequence of strings set_xticks(ticks. labelpad=None. labelpad=None. fontdict=None.Matplotlib. minor=False) Set the x ticks with list of ticks ACCEPTS: sequence of floats set_ybound(lower=None. This method will honor axes inversion regardless of parameter order. 0 transparent through 1.Figure instance a matplotlib.figure.font_manager. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: str See Also: 508 Chapter 36.0.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. matplotlib axes .transforms. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.Matplotlib. Release 1.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.Bbox instance [True | False] [ (Path.1 Table 36.26 – continued fro agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder unknown float (0.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. **kwargs) call signature: set_yscale(value) Set the scaling of the y-axis: ‘linear’ | ‘log’ | ‘symlog’ ACCEPTS: [’linear’ | ‘log’ | ‘symlog’] Different kwargs are accepted. For example. Release 1. is at the top. accepts: float in range 0 to 1 set_yscale(value.0. ymax. Then one might use: set_ylim(5000. Returns the current ylimits as a length 2 tuple ACCEPTS: len(2) sequence of floats set_ymargin(m) Set padding of Y data limits prior to autoscaling. or leave unchanged (None) Note: the bottom (formerly ymin) value may be greater than the top (formerly ymax). m times the data interval will be added to each end of that interval before it is used in autoscaling. the previous name. 0 m. emit=True. matplotlib.1. **kw) call signature: set_ylim(self.axes 509 . depending on the scale: ‘linear’ ‘log’ 36. ymin. top) set_ylim(bottom=1) # top unchanged set_ylim(top=1) # bottom unchanged Keyword arguments: bottom: scalar the bottom ylim. off (False. default).Matplotlib. auto=False. *args. 0) so 5000 m depth is at the bottom of the plot and the surface. suppose y is depth in the ocean. may still be used emit: [ True | False ] notify observers of lim change auto: [ True | False | None ] turn y autoscaling on (True). the previous name.1 text() for information on how override and the optional args work set_ylim(bottom=None. may still be used top: scalar the top ylim. **kwargs): Set the data limits for the yaxis Examples: set_ylim((bottom. top=None. top)) set_ylim(bottom. Return a list of Text instances. minor=False. 7. 6. 8.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) 510 Chapter 36. **kwargs) Set the ytick labels with list of strings labels.transforms. fontdict=None. For example.Figure instance a matplotlib. fontdict=None. 2. 5. 9] will place 10 logarithmically spaced minor ticks between each major tick. 4. minor=False.Matplotlib. set_yticklabels(labels.0 transparent through 1. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick. 1. 3. Release 1. For example. Valid properties are Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing Description unknown float (0.figure.0. 2.font_manager. kwargs set Text properties for the labels. 6. 4. in a log10 scale: [0. 8. Should be a sequence of integers.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.1 basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid.Bbox instance [True | False] [ (Path. in a log10 scale: [0. matplotlib axes . x) within which the plot is linear (to avoid having the plot go to infinity around zero). subsx/subsy: Where to place the subticks between each major tick. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. 3. Should be a sequence of integers. 1. 9] will place 10 logarithmically spaced minor ticks between each major tick. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. 5. **kwargs) call signature: set_yticklabels(labels. 7. noverlap=128. cmap=None. minor=False) Set the y ticks with list of ticks ACCEPTS: sequence of floats Keyword arguments: minor: [ False | True ] Sets the minor ticks if True specgram(x. Fs=2.Matplotlib. xextent=None.1. pad_to=None. Release 1. detrend=mlab. Keyword arguments: 36. detrend=<function detrend_none at 0x3a1c668>. **kwargs) Compute a spectrogram of data in x.27 – continued fro lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. cmap=None.window_hanning. Fc=0. Data are split into NFFT length segments and the PSD of each section is computed. matplotlib. Fs=2. NFFT=256. noverlap=128. pad_to=None. scale_by_freq=None. The windowing function window is applied to each segment.0. sides=’default’. window=<function window_hanning at 0x3a178c0>.detrend_none. and the amount of overlap of each segment is specified with noverlap.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. scale_by_freq=None. Fc=0. window=mlab. NFFT=256. sides=’default’. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number ACCEPTS: sequence of strings set_yticks(ticks.axes 511 . xextent=None.1 Table 36. **kwargs) call signature: specgram(x. ‘onesided’ forces the return of a one-sided PSD. The default is window_hanning(). which specifies the number of data points used.signal. matplotlib axes . while ‘twosided’ forces two-sided. scipy.xmax) The default is (0. noverlap: integer The number of points of overlap between blocks. The default value is 2. Must be even. and detrend_linear(). The default value is 0 (no overlap).Colormap instance. numpy. bins. freqs.0.hamming(). where bins is the return value from mlab. etc.blackman(). This can be different from NFFT.max(bins)). detrend: callable The function applied to each segment before fft-ing. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). pad_to: integer The number of points to which the data segment is padded when performing the FFT. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. cmap: A matplotlib. which offsets the y extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband. a power 2 is most efficient. but you can use a custom function as well. if None use default determined by rc xextent: The image extent along the x-axis. window_none(). scipy. detrend_mean(). which gives density in units of Hz^-1. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. The default value is 256. To create window vectors see window_hanning(). Unlike in MATLAB. This corresponds to the n parameter in the call to fft().get_window(). The default is True for MATLAB compatibility. freqs.bartlett(). Release 1.specgram() kwargs: Additional kwargs are passed on to imshow which makes the specgram image Return value is (Pxx. this can give more points in the plot. it must take a data segment as an argument and return the windowed version of the segment. xextent = (xmin. The default is None. This allows for integration over the returned frequency values. im): •bins are the time points the spectrogram is calculated over 512 Chapter 36. Default gives the default behavior.signal().Matplotlib. which returns one-sided for real data and both for complex data. If a function is passed as the argument. in cycles per time unit. numpy.1 NFFT: integer The number of data points used in each block for the FFT. The pylab module defines detrend_none(). allowing for more detail. where the detrend parameter is a vector. Fs: scalar The sampling frequency (samples per time unit). numpy. Fc: integer The center frequency of x (defaults to 0).cm. window: callable or ndarray A function or a vector of length NFFT. in matplotlib is it a function. designed to remove the mean or linear trend. It is used to calculate the Fourier frequencies. aspect=’equal’.0. precision=0. any non-zero value will be plotted.spmatrix instances.Matplotlib. marker=None.1.image. any value present in the array will be plotted. there is a special case: if precision is ‘present’.sparse. Release 1. only the positive spectrum is shown. precision=0. else. **kwargs) spy(Z) plots the sparsity pattern of the 2-D array Z. If precision is 0. non-complex). aspect=’equal’. marker=None. markersize=None. For scipy.AxesImage instance Note: If x is real (i.axes 513 . 36. both positive and negative parts of the spectrum are shown. This can be overridden using the sides keyword argument. Example: 3 2 1 0 1 2 30 1000 800 600 400 200 00 5 10 15 20 5 10 15 20 spy(Z. **kwargs) call signature: spy(Z. If x is complex.e. values of |Z| > precision will be plotted.1 •freqs is an array of frequencies •Pxx is a len(times) x len(freqs) array of power •im is a matplotlib. markersize=None. matplotlib. even if it is identically zero. an image will be returned and any remaining kwargs are passed to imshow(). button is the mouse button number: •1: LEFT •2: MIDDLE 514 Chapter 36. For controlling colors.’r’]) If marker or markersize is not None.0. and any remaining kwargs passed to the plot() method.1 The array will be plotted as it would be printed. with the first index (row) increasing down and the second index (column) increasing to the right. useful kwargs include: •cmap •alpha See Also: imshow() For image options. y. Two plotting styles are available: image or marker. or to any scalar number to specify the aspect ratio of an array element directly. Both are available for full arrays. useful kwargs include: •marker •markersize •color Useful values for marker include: •‘s’ square (default) •‘o’ circle •‘. Release 1. If marker and markersize are None. but only the marker style works for scipy.g. set the aspect kwarg to ‘auto’ to allow the plot to fill the plot box. e.sparse. y are the mouse coordinates in display coords.spmatrix instances. cyan background and red marks. x.’ pixel See Also: plot() For plotting options start_pan(x. By default aspect is ‘equal’. If marker and markersize are None.ListedColormap([’c’. a Line2D object will be returned with the value of marker determining the marker type. else. button) Called when a pan operation has started.Matplotlib.’ point •‘. use: cmap = mcolors. matplotlib axes . so that each array element occupies a square space. colWidths=None. *args. y. rowLoc=’left’.Table instance. cellLoc=’right’. **kwargs) Make a step plot. that x is uniformly increasing.0. y.1. Keyword arguments: where: [ ‘pre’ | ‘post’ | ‘mid’ ] If ‘pre’. x and y must be 1-D sequences. markerfmt=’bo’. that interval has level y[i] If ‘mid’.table. colColours=None. stem(x. markerfmt=’bo’. y. A horizontal line at 0 is is plotted using basefmt. y. but not checked. matplotlib. and places a marker there using markerfmt. stemlines. table(**kwargs) call signature: table(cellText=None.axes 515 . See Also: this document for details examples/pylab_examples/stem_plot. baseline). cellColours=None. Thanks to John Gill for providing the class and table. the jumps in y occur half-way between the x-values. the interval from x[i] to x[i+1] has level y[i+1] If ‘post’. colLoc=’center’. **kwargs) call signature: step(x. basefmt=’r-‘) call signature: stem(x. rowLabels=None. For finer grained control over tables. Return value is a tuple (markerline.1 •3: RIGHT Note: Intended to be overridden by new projection types. and it is assumed. linefmt=’b-‘. kwargs control the Table properties: 36. *args. use the Table class and add it to the axes with add_table(). Release 1.py for a demo step(x. Returns a matplotlib. linefmt=’b-’.Matplotlib. colLabels=None. loc=’bottom’. basefmt=’r-’) A stem plot plots vertical lines (using linefmt) at each x location from the baseline to y. rowColours=None. bbox=None): Add a table to the current axes. Additional keyword args to step() are the same as those for plot(). s.0. matplotlib axes . horizontalalignment=’center’. 0. fontdict=None. withdash: [ False | True ] Creates a TextWithDash instance instead of a Text instance. withdash=False. fontsize=12) The default transform specifies that text is in data coords. bbox is a dictionary of matplotlib. verticalalignment=’center’. **kwargs) call signature: text(x. Keyword arguments: fontdict: A dictionary to override the default text properties. **kwargs) Add text in string s to axis at location x.transAxes) You can put a rectangular box around the text instance (eg. alternatively.5.5. Transform) | Patch | None ] a callable function a matplotlib.Matplotlib. y.figure.1 is upper-right).0 opaque) [True | False] an Axes instance a matplotlib.0 is lower-left and 1.0 transparent through 1.patches.Bbox instance [True | False] [ (Path. s. y. the defaults are determined by your rc parameters.1 Property agg_filter alpha animated axes clip_box clip_on clip_path contains figure fontsize gid label lod picker rasterized snap transform url visible zorder Description unknown float (0.transforms. fontdict=None. Release 1. If fontdict is None.Rectangle properties.Figure instance a float in points an id string any string [True | False] [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number text(x. data coordinates.’matplotlib’. transform = ax. y. y. Individual keyword arguments can be used to override any given parameter: text(x. to set a background color) by using the keyword bbox. For example: 516 Chapter 36. The example below places text in the center of the axes: text(0. you can specify text in axis coords (0. s. Bbox instance [True | False] [ (Path. s.Figure instance a matplotlib.font_manager. Release 1. bbox=dict(facecolor=’red’.Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder Description unknown float (0.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.5)) Valid kwargs are matplotlib.Matplotlib.0 transparent through 1.1.figure. y.axes 517 . matplotlib. alpha=0.text. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.transforms. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number 36.1 text(x.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.0.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. Matplotlib. width=2. Optional keyword arguments: Keyword style scilimits useOffset axis Description [ ‘sci’ (or ‘scientific’) | ‘plain’ ] plain turns off scientific notation (m. right Boolean or [’on’ | ‘off’]. ‘large’). which [’major’ | ‘minor’ | ‘both’] Default is ‘major’: apply arguments to major ticks only. controls whether to draw the respective ticks. it will be used. colors Changes the tick color and the label color to the same value: mpl color spec. length=6. labelbottom. labelsize Tick label font size in points or as a string (e. color Tick color. zorder Tick and label zorder. **kwargs) Convenience method for changing the appearance of ticks and tick labels. if False. reset [True | False] If True. Example: ax. bottom. colors=’r’) This will make all major ticks be red.tick_params(direction=’out’. labeltop. top. accepts any mpl color spec. [True | False | offset]. matplotlib axes . Default is False. no offset will be used. default is ‘both’. mpl color spec. controls whether to draw the respective tick labels. pair of integers. n). labelright Boolean or [’on’ | ‘off’]. if style is ‘sci’. Use (0. scientific notation will be used for numbers outside the range 10‘-m‘:sup: to 10‘n‘:sup:. and with dimensions 6 points by 2 points. pointing out of the box. if a numeric offset is specified. width Tick width in points.1 tick_params(axis=’both’. if True. direction [’in’ | ‘out’] Puts ticks inside or outside the axes. Keyword arguments: axis [’x’ | ‘y’ | ‘both’] Axis on which to operate. labelcolor Tick label color. set all parameters to defaults before processing other keyword arguments. [ ‘x’ | ‘y’ | ‘both’ ] 518 Chapter 36. the offset will be calculated as needed.g.0) to include all numbers. ticklabel_format(**kwargs) Convenience method for manipulating the ScalarFormatter used by default for linear axes. Release 1. pad Distance in points between tick and label. length Tick length in points.0. labelleft. Tick labels will also be red. left. tricontour(. V) draw contour lines at the values specified in sequence V tricontourf(. 36. tricontour(x. tricontour(x. **kwargs) tricontour() and tricontourf() draw contour lines and filled contours.. **kwargs) Use keyword args to control colors.. Z. tricontour(.. on an unstructured triangular grid. y. tricontour(x. Z) where Z is the array of values to contour.) triangles. tricontour(x. y. function signatures and return values are the same for both versions. tricontour(*args.. Release 1... N) contour N automatically-chosen levels.) mask.. mask=mask. matplotlib.) where triangulation is a Triangulation object. tricontour(x.. either: tricontour(triangulation..) returns a TriContourSet object. . y. y.axes 519 . See Triangulation for a explanation of these possibilities. an AttributeError will be raised... y. .) triangles.... the colormap specified by cmap will be used.. origin. .1.... cmap .. Z..) triangles. all levels will be plotted in this color. C = tricontour(.... Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None. tricontour(x.. . The remaining arguments may be: tricontour(. respectively. y... mask. one per point in the triangulation.) in which case a Triangulation object will be created.. . Z. The level values are chosen automatically.. Except as noted.Matplotlib. like ‘r’ or ‘red’. y. .0.) mask=mask..) triangles=triangles. see below for more details. The triangulation can be specified in one of two ways. If the method is called when the ScalarFormatter is not the Formatter being used.. If a string.1 Only the major ticks are affected. . . V) fill the (len(V)-1) regions between the values in V tricontour(Z. or tricontour(x... linewidth. levels [level0.0.y0. xunits. then (x0. If cmap is None and colors is None.Matplotlib.origin will be used. tricontour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None. float.y1) ] If origin is not None.Locator subclass ] If locator is None. then extent is interpreted as in matplotlib. a default Colormap is used.0] is the center of the pixel.Colormap. the position of Z[0.Normalize instance for scaling data values to colors.imshow(): it gives the outer pixel boundaries. If a tuple. rgb.linewidth in matplotlibrc is used. all levels will be plotted with this linewidth. leveln] A list of floating point numbers indicating the level curves to draw. the first value of Z will correspond to the lower left corner. level1. the default linear scaling is used. the default MaxNLocator is used. If origin is None..Colormap.set_over() methods.x1.pyplot.1 If a tuple of matplotlib color args (string.0]. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. y0) is the position of Z[0. If a number. This keyword is not active if X and Y are specified in the call to contour. . norm: [ None | Normalize ] A matplotlib. If ‘image’. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None.set_under() and matplotlib. In this case.ConversionInterface. location (0. This keyword is not active if X and Y are specified in the call to contour. not a corner. the default width in lines. The locator is used to determine the contour levels if they are not given explicitly via the V argument..0). different levels will be plotted in different colors in the order specified.units. extent: [ None | (x0. If norm is None and colors is None. etc). y1) is the position of Z[-1. matplotlib axes .. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’. but can be set via matplotlib. the rc value for image. Release 1.-1].colors.colors. and (x1. contour levels are automatically added to one or both ends of the range so that all data are included. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None. different levels will be plotted with different linewidths in the order specified 520 Chapter 36.colors. locator: [ None | ticker. Except as noted.) triangles. tricontour(x. then the linestyle specified in contour. either: tricontour(triangulation. respectively. . y.... y. the ‘solid’ is used. mask=mask. y. . linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. The triangulation can be specified in one of two ways. mask.. y. tricontour(x. . then that minimum value will be included in the lowest interval. y. . The remaining arguments may be: 36.. for boundaries z1 and z2.. Release 1.negative_linestyle in matplotlibrc will be used. This may never actually be advantageous.Matplotlib.. . See Triangulation for a explanation of these possibilities.) mask. Note: tricontourf fills intervals that are closed at the top. tricontourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0. no subdivision of the domain. that is. tricontour(x. **kwargs) tricontour() and tricontourf() draw contour lines and filled contours.) in which case a Triangulation object will be created.. on an unstructured triangular grid.. tricontour(x. tricontour(x. y. tricontour(x. or tricontour(x. matplotlib.. function signatures and return values are the same for both versions. so this option may be removed. y.) mask=mask.. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points.1.) triangles=triangles.) where triangulation is a Triangulation object. . ..) triangles..0. Examples: tricontourf(*args.axes 521 .1 linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. If contour is using a monochrome colormap and the contour level is less than 0... . If this iterable is shorter than the number of contour levels it will be repeated as necessary. the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array..) triangles. .) returns a TriContourSet object. tricontour(. V) fill the (len(V)-1) regions between the values in V tricontour(Z.0 0. cmap . see below for more details. C = tricontour(. The level values are chosen automatically.. N) contour N automatically-chosen levels.0.. Z..25 0.Matplotlib.5 1. Z.00 0. Z. Release 1..00 1..75 1.5 0.. V) draw contour lines at the values specified in sequence V tricontourf(. matplotlib axes .0 0. origin.25 0...1 Contour plot of Delaunay triangulation 1.. Optional keyword arguments: 522 Chapter 36.0 0. one per point in the triangulation.0 0..00 tricontour(.5 1.5 0... **kwargs) Use keyword args to control colors.50 0.75 0. Z) where Z is the array of values to contour.0 0.... linewidth.50 0.01. tricontour(. 65 0. rgb.y1) ] 36. If a string. a default Colormap is used..1 Contour plot of user-specified triangulation 1.80 0. matplotlib.95 0.y0. levels [level0. Release 1.0. like ‘r’ or ‘red’..x1.0). the first value of Z will correspond to the lower left corner. norm: [ None | Normalize ] A matplotlib.origin will be used.1. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None. location (0.70 0. the rc value for image. If cmap is None and colors is None. leveln] A list of floating point numbers indicating the level curves to draw.75 0.Normalize instance for scaling data values to colors. different levels will be plotted in different colors in the order specified. the colormap specified by cmap will be used.axes 523 . all levels will be plotted in this color.85 0. .60 colors: [ None | string | (mpl_colors) ] If None. extent: [ None | (x0. etc).90 0.. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None. If norm is None and colors is None. If ‘image’.Matplotlib. float. This keyword is not active if X and Y are specified in the call to contour.00 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) 0. If a tuple of matplotlib color args (string.colors. level1. the default linear scaling is used. matplotlib axes .set_under() and matplotlib. If a number. If contour is using a monochrome colormap and the contour level is less than 0.ConversionInterface. and (x1.colors. If this iterable is shorter than the number of contour levels it will be repeated as necessary. the default MaxNLocator is used. then the linestyle specified in contour. contour levels are automatically added to one or both ends of the range so that all data are included. the position of Z[0.Colormap. that is.pyplot. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range. for boundaries z1 and z2. If origin is None. the filled region is: 524 Chapter 36. no subdivision of the domain. The locator is used to determine the contour levels if they are not given explicitly via the V argument.0]. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. In this case. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. This may never actually be advantageous. tricontour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None.set_over() methods. different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. the ‘solid’ is used.0] is the center of the pixel. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. all levels will be plotted with this linewidth.0. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’. not a corner. Note: tricontourf fills intervals that are closed at the top. the default width in lines.1 If origin is not None. but can be set via matplotlib.imshow(): it gives the outer pixel boundaries.Matplotlib. y0) is the position of Z[0. then (x0.-1]. xunits.units.Colormap. tricontourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0. then extent is interpreted as in matplotlib.Locator subclass ] If locator is None.negative_linestyle in matplotlibrc will be used. so this option may be removed. This keyword is not active if X and Y are specified in the call to contour. y1) is the position of Z[-1.colors. If a tuple. Release 1. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. locator: [ None | ticker.linewidth in matplotlibrc is used. 5 0. y.5 1. y.0 0. tripcolor(x.. y.. ..) triangles..) triangles.. .50 0.0 0.) mask. .0 0. .) triangles=triangles. Release 1. **kwargs) Create a pseudocolor plot of an unstructured triangular grid to the Axes.75 0. matplotlib.1 z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array. either: tripcolor(triangulation. y.. The triangulation can be specified in one of two ways.axes 525 .5 0. then that minimum value will be included in the lowest interval. y.. y. y.0. 36.Matplotlib.00 0. tripcolor(x.0 0.) mask=mask.) where triangulation is a Triangulation object..01.50 0. . .) triangles. mask.) in which case a Triangulation object will be created. tripcolor(x.25 0. .. tripcolor(x.00 tripcolor(*args. . tripcolor(x. mask=mask.00 1...5 1... tripcolor(x.25 0. or tripcolor(x...1. Examples: Contour plot of Delaunay triangulation 1.75 1.0 0.. See Triangulation for a explanation of these possibilities. ) where triangulation is a Triangulation object. The remaining kwargs are the same as for pcolor().85 0. .60 The next argument must be C.00 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) 0.. . triplot(x. mask=mask. . The triangulation to plot can be specified in one of two ways. .) mask.. either: triplot(triangulation..90 0.) triangles=triangles.) triangles..65 0.. y..0. triplot(x. ..70 0. .. mask. The colors used for each triangle are from the mean C of the triangle’s three points.Matplotlib. matplotlib axes .. or triplot(x.) triangles. Release 1..) triangles. .95 0. y. triplot(x. y. triplot(x. y.. the array of color values. y. one per point in the triangulation. y. y.) mask=mask. ... triplot(x.80 0.1 Contour plot of user-specified triangulation 1. triplot(x.. Example: triplot(*args. **kwargs) Draw a unstructured triangular grid as lines and/or markers to the Axes..75 0..) 526 Chapter 36. updatey=True) Update the data lim bbox with seq of xy tups or equiv. Example: twinx() call signature: ax = twinx() create a twin of Axes for generating a plot with a sharex x-axis but independent y axis.5 1. The y-axis of self will have ticks on left and the returned axes will have ticks on the right twiny() call signature: ax = twiny() create a twin of Axes for generating a plot with a shared y-axis but independent x axis. updatex=True.5 1. The remaining args and kwargs are the same as for plot().0 tripcolor of Delaunay triangulation 0.8 0.1.01. 2-D array 36.5 0.0 0. See Triangulation for a explanation of these possibilities.5 0.0 0.0 0. Release 1.6 0. The x-axis of self will have ticks on bottom and the returned axes will have ticks on the top update_datalim(xys.4 0.8 in which case a Triangulation object will be created.0.4 0.2 0.6 0. matplotlib.0 0.2 0.1 1.0 0.axes 527 .Matplotlib. LineCollection that was added. ymin.72 0. then the respective values are constant. linestyles=’solid’) 0.68 0. linestyles=’solid’. If they are scalars. label=’‘. ymax. color=’k’.64 Plot vertical lines at each x from ymin to ymax. colors a line collections color args.0.collections.88 0. **kwargs) call signature: vlines(x.Matplotlib. else the heights of the lines are determined by ymin and ymax. colors=’k’.96 0. Release 1. matplotlib axes . ymin. ymax. either a single color or a len(x) list of colors linestyles one of [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] Returns the matplotlib.76 0. kwargs are LineCollection properties: Continued on next page 528 Chapter 36. ymin or ymax can be scalars or len(x) numpy arrays.92 0.1 tripcolor of user-specified triangulation 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) update_datalim_bounds(bounds) Update the datalim to include the given Bbox bounds update_datalim_numerix(x. y) Update the data lim bbox with seq of xy tups vlines(x.80 0.84 0. 1 Table 36.transforms.1. Defaults to rc value.Bbox instance [True | False] [ (Path. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib.29 – continued from previous page Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized segments snap transform url urls verts visible zorder Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.axes 529 . ‘dashdot’. tz is the time zone to use in labeling dates. ‘dotted’ | (offset. 36.Figure instance an id string any string [’solid’ | ‘dashed’.figure. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown unknown Transform instance a url string unknown unknown [True | False] any number xaxis_date(tz=None) Sets up x-axis ticks and labels that treat the x data as dates. xaxis_inverted() Returns True if the x-axis is inverted. Release 1. matplotlib.0.Matplotlib. 0. maxlags=10. detrend=mlab.01. line) where: •lags are a length 2*maxlags+1 lag vector •c is the 2*maxlags+1 auto correlation vector •line is a Line2D instance returned by plot().0 xcorr(x.0 0. usevlines=True.Matplotlib. y.5 triplot of Delaunay triangulation 1. c. c. maxlags=10. normalize the data by the cross correlation at 0-th lag. detrend=<function detrend_none at 0x3a1c668>. x.0 0. Data are plotted as plot(lags. Release 1. The cross correlation is performed with numpy. usevlines=True. If normed = True. y. normed=True. **kwargs) call signature: def xcorr(self.5 1. x and y must be equal length.5 0. though these can be overridden with keyword args.correlate() with mode = 2. **kwargs) Return value is a tuple (lags. matplotlib axes . The default linestyle is None and the default marker is ‘o’. **kwargs): Plot the cross correlation between x and y.0 0.5 0.1 1.0 0. normed=True. 530 Chapter 36.detrend_none. If usevlines is True: vlines() rather than plot() is used to draw vertical lines from the origin to the xcorr. x and y are detrended by the detrend callable (default no normalization). Matplotlib. c.0. *args. which are Axes instances with additional methods to facilitate generating and 36. yaxis_inverted() Returns True if the y-axis is inverted.axes. matplotlib. b) where linecol is the matplotlib. The default value of None will return all (2*len(x)-1) lags. The return value is a tuple (lags.axes 531 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) Otherwise the plotstyle is determined by the kwargs. Release 1.1. and acorr() below.1 triplot of user-specified triangulation 58 Latitude (degrees) Example: xcorr() above.collections.LineCollection instance and b is the x-axis.SubplotBase(fig. Example: yaxis_date(tz=None) Sets up y-axis ticks and labels that treat the y data as dates. tz is the time zone to use in labeling dates. which are Line2D properties. . Defaults to rc value.Subplot alias of AxesSubplot class matplotlib. matplotlib. maxlags is a positive integer detailing the number of lags to show.axes. linecol. **kwargs) Base class for subplots. from 1.05 0.1.8 0.3 get_subplotspec() get the SubplotSpec instance associated with the subplot is_first_col() is_first_row() is_last_col() is_last_row() 532 Chapter 36.10 0. numCols. If numRows <= numCols <= plotNum < 10.10 0. numcols.15 0.0.0 0.260 40 20 0 20 40 60 40 20 0 20 40 60 manipulating a set of Axes within a figure.05 0.0 0. plotNum starts at 1 in the upper left corner and increases to the right. where the array of subplots in the figure has dimensions numRows.2060 1.Matplotlib. change_geometry(numrows.2.figure. eg 2.1 0.00 0.6 0. numCols.1 to 2. num) change subplot geometry.3 get_geometry() get the subplot geometry. Release 1.15 0.4 0.2 0. args can be the decimal integer numRows * 100 + numCols * 10 + plotNum. eg.Figure instance.20 0. args is the tuple (numRows. and where plotNum is the number of the subplot being created.2. matplotlib axes . plotNum). fig is a matplotlib. matplotlib.subplot_class_factory(axes_class=None) 36. Note: Deprecated 2010/01/03.axes.1.axes. Release 1. matplotlib.axes 533 .subplotpars matplotlib.set_default_color_cycle(clist) Change the default cycle of colors that will be used by the plot command. See also: set_color_cycle(). it will apply to all future axes.color_cycle’] directly.1 label_outer() set the visible property on ticklabels so xticklabels are visible only if the subplot is in the last row and yticklabels are visible only if the subplot is in the first column set_subplotspec(subplotspec) set the SubplotSpec instance associated with the subplot update_params() update the subplot position from fig.0. Set rcParams[’axes. This must be called before creating the Axes to which it will apply. clist is a sequence of mpl color specifiers.Matplotlib. 1 534 Chapter 36. Release 1.0. matplotlib axes .Matplotlib. Axis(axes. *args.transform data coords to display coords •axes.transform axis coords to display coords •labelpad .transData . renderer.transAxes . grid lines.artist.number of points between the axis and its label Init the axis with the parent Axes instance axis_date() Sets up x-axis ticks and labels that treat the x data as dates. tick lines and labels get_children() get_data_interval() return the Interval instance for this axis data limits get_gridlines() Return the grid lines as a list of Line2D instance get_label() Return the axis label as a Text instance get_label_text() Get the text of the label 535 .axis. pickradius=15) Bases: matplotlib.1 matplotlib.Artist Public attributes •axes.axis Classes for the ticks and x and y axis class matplotlib.CHAPTER THIRTYSEVEN MATPLOTLIB AXIS 37. **kwargs) Draw the axis lines. cla() clear the current axis convert_units(x) draw(artist. Matplotlib. matplotlib axis . grow as necessary get_majorticklabels() Return a list of Text instances for the major ticklabels get_majorticklines() Return the major tick lines as a list of Line2D instances get_majorticklocs() Get the major tick locations in data coordinates as a numpy array get_minor_formatter() Get the formatter of the minor ticker get_minor_locator() Get the locator of the minor ticker get_minor_ticks(numticks=None) get the minor tick instances. get_ticklabels(minor=False) Return a list of Text instances for ticklabels get_ticklines(minor=False) Return the tick lines as a list of Line2D instances 536 Chapter 37. grow as necessary get_minorticklabels() Return a list of Text instances for the minor ticklabels get_minorticklines() Return the minor tick lines as a list of Line2D instances get_minorticklocs() Get the minor tick locations in data coordinates as a numpy array get_offset_text() Return the axis offsetText as a Text instance get_pickradius() Return the depth of the axis used by the picker get_scale() get_smart_bounds() get whether the axis has smart bounds get_ticklabel_extents(renderer) Get the extents of the tick labels on either side of the axes.0. Release 1.1 get_major_formatter() Get the formatter of the major ticker get_major_locator() Get the locator of the major ticker get_major_ticks(numticks=None) get the tick instances. You can also specify the coordinate system of the label with the transform. vmax) pan(numsteps) Pan numsteps (can be positive or negative) reset_ticks() set_clip_path(clippath. b is a boolean. If b is None and len(kwargs)==0. y. If None. Use which = ‘major’ | ‘minor’ | ‘both’ to set the grid for major or minor ticks. By default. (0. fontdict=None. xax. **kwargs) Set the axis grid on or off.5.1 get_ticklocs(minor=False) Get the tick locations in data coordinates as a numpy array get_transform() get_units() return the units for axis get_view_interval() return the Interval instance for this axis view limits grid(b=None. kwargs are used to set the line properties of the grids.bottom). Ditto for the y coodinate of the x label.axis 537 . toggle the grid state. If kwargs are supplied.grid(color=’r’. 0.0) is (left. eg. it is assumed you want the grid on and b will be set to True. transform=None) set_data_interval() set the axis data limits set_default_intervals() set the default limits for the axis data and view interval if they are not mutated set_label_coords(x. **kwargs) Sets the text value of the axis label ACCEPTS: A string value for the label set_major_formatter(formatter) Set the formatter of the major ticker 37.5) is middle. the default coordinate system will be the axes coordinate system (0. but this can lead to poor alignment of multiple ylabels if there are multiple axes. linestyle=’-‘.1.0. transform=None) Set the coordinates of the label. which=’major’.Matplotlib. linewidth=2) have_units() iter_ticks() Iterate through all of the major and minor ticks. matplotlib. limit_range_for_scale(vmin. Release 1. the x coordinate of the y label is determined by the tick label bounding boxes. etc set_label_text(label. regardless of the state of label1On and label2On. **kwargs) Set the text values of the tick labels. minor=False) Set the locations of the tick marks from sequence ticks ACCEPTS: sequence of floats set_units(u) set the units for axis ACCEPTS: a units tag set_view_interval(vmin. As for get_ticklabels.Axes. label1 (left or bottom) is affected for a given tick only if its label1On attribute is True. matplotlib axis . **kw) Set appearance parameters for ticks and ticklabels.1 ACCEPTS: A Formatter instance set_major_locator(locator) Set the locator of the major ticker ACCEPTS: a Locator instance set_minor_formatter(formatter) Set the formatter of the minor ticker ACCEPTS: A Formatter instance set_minor_locator(locator) Set the locator of the minor ticker ACCEPTS: a Locator instance set_pickradius(pickradius) Set the depth of the axis used by the picker ACCEPTS: a distance in points set_scale(value. set_ticklabels(ticklabels. The input ticklabels is assumed to match the set of tick locations.0. vmax. see matplotlib.axes. and similarly for label2. **kwargs) set_smart_bounds(value) set the axis to have smart bounds set_tick_params(which=’major’. For documentation of keyword arguments.Matplotlib. *args.tick_params(). ACCEPTS: sequence of strings set_ticks(ticks. Use kwarg minor=True to select minor ticks. Release 1. The list of returned label text objects consists of all such label1 objects followed by all such label2 objects. reset=False. All other kwargs are used to update the text object properties. ignore=False) 538 Chapter 37. Return a list of Text instances. tick1On=True. labelsize=None.converter instance if necessary.axis. width=None. *args. if direction is >0 zoom in. labelcolor=None.1 update_units(data) introspect data for units converter and update the axis. This function always returns false. size=None._pad and self. zorder=None. label1On=True.Tick(axes. loc.artist.1. label2On=False.Artist Abstract base class for the axis ticks. draw(artist. else zoom out class matplotlib.0. label. color=None. renderer. Release 1. tickdir=None. pad=None. matplotlib. grid lines and labels 1 refers to the bottom of the plot for xticks and the left for yticks 2 refers to the top of the plot for xticks and the right for yticks Publicly accessible attributes: tick1line a Line2D instance tick2line a Line2D instance gridline a Line2D instance label1 a Text instance label2 a Text instance gridOn a boolean which determines whether to draw the tickline tick1On a boolean which determines whether to draw the 1st tickline tick2On a boolean which determines whether to draw the 2nd tickline label1On a boolean which determines whether to draw tick label label2On a boolean which determines whether to draw tick label bbox is the Bound2D bounding box in display coords of the Axes loc is the tick location in data coords size is the tick size in points apply_tickdir(tickdir) Calculate self. Return True is data is registered for unit conversion zoom(direction) Zoom in/out on axis. tick2On=True.axis 539 . major=True) Bases: matplotlib. **kwargs) get_children() get_loc() Return the tick location (data coords) as a scalar 37.Matplotlib. It is more useful to test if the axis as a whole contains the mouse rather than the set of tick marks._tickmarkers contains(mouseevent) Test whether the mouse event occured in the Tick marks. gridOn=None. in which case an optional Transform instance may be provided. which will be applied to the path before using it for clipping. to remove the clipping path For efficiency.axis.Ticker class matplotlib. matplotlib axis . ignore=False) class matplotlib. transform=None) Set the artist’s clip path. vmax.0.Axis Init the axis with the parent Axes instance contains(mouseevent) Test whether the mouse event occured in the x axis. get_data_interval() return the Interval instance for this axis data limits 540 Chapter 37. •None.XAxis(axes. pickradius=15) Bases: matplotlib.axis.Matplotlib. ACCEPTS: [ (Path. Release 1.axis. this method will set the clipping box to the corresponding rectangle and set the clipping path to None. which may be: •a Patch (or subclass) instance •a Path instance.1 get_pad() Get the value of the tick label pad in points get_pad_pixels() get_view_interval() return the view Interval instance for the axis this tick is ticking set_clip_path(clippath. Transform) | Patch | None ] set_label(s) Set the text of ticklabel ACCEPTS: str set_label1(s) Set the text of ticklabel ACCEPTS: str set_label2(s) Set the text of ticklabel2 ACCEPTS: str set_pad(val) Set the tick label pad in points ACCEPTS: float set_view_interval(vmin. if the path happens to be an axis-aligned rectangle. default or unknown) get_view_interval() return the Interval instance for this axis view limits set_data_interval(vmin. bottom. pad=None. labelsize=None. size=None. ignore=False) set the axis data limits set_default_intervals() set the default limits for the axis interval if they are not mutated set_label_position(position) Set the label position (top or bottom) ACCEPTS: [ ‘top’ | ‘bottom’ ] set_ticks_position(position) Set the ticks position (top. both. ‘none’ can be used if you don’t want any ticks. below) get_ticks_position() Return the ticks position (top. tick2On=True. label2On=False.axis. bottom.axis 541 . label1On=True.1. label. ignore=False) If ignore is False.Matplotlib. ACCEPTS: [ ‘top’ | ‘bottom’ | ‘both’ | ‘default’ | ‘none’ ] set_view_interval(vmin. tick_bottom() use ticks only on bottom tick_top() use ticks only on top class matplotlib.1 get_label_position() Return the label position (top or bottom) get_minpos() get_text_heights(renderer) Returns the amount of space one should reserve for text above and below the axes. vmax.Tick Contains all the Artists needed to make an x tick . tick1On=True. vmax does not matter. default or none) both sets the ticks to appear on both positions.XTick(axes. Release 1. width=None. vmax. tickdir=None.the tick line. but does not change the tick labels. labels at bottom. gridOn=None. the original axis orientation will be preserved. major=True) Bases: matplotlib. the order of vmin. zorder=None. labelcolor=None.axis. not the labels. Returns a tuple (above. matplotlib. ‘none’ and ‘both’ affect only the ticks. loc. color=None. ‘default’ resets the tick positions to the default: ticks on both positions.0. the label text and the grid line bbox is the Bound2D bounding box in display coords of the Axes loc is the tick location in data coords size is the tick size in points apply_tickdir(tickdir) 37. Release 1. both or unknown) get_view_interval() return the Interval instance for this axis view limits set_data_interval(vmin. vmax. right.Matplotlib. default or none) ‘both’ sets the ticks to appear on both positions.0. not the labels. Returns True | False get_data_interval() return the Interval instance for this axis data limits get_label_position() Return the label position (left or right) get_minpos() get_text_widths(renderer) get_ticks_position() Return the ticks position (left. vmax.1 get_data_interval() return the Interval instance for this axis data limits get_minpos() get_view_interval() return the Interval instance for this axis view limits set_view_interval(vmin. labels at left. ‘none’ can be used if you don’t want any ticks.YAxis(axes. ignore=False) update_position(loc) Set the location of tick in data coords with scalar loc class matplotlib.axis.Axis Init the axis with the parent Axes instance contains(mouseevent) Test whether the mouse event occurred in the y axis. right. ‘default’ resets the tick positions to the default: ticks on both positions. both. ‘none’ and ‘both’ affect only the ticks. pickradius=15) Bases: matplotlib. ignore=False) set the axis data limits set_default_intervals() set the default limits for the axis interval if they are not mutated set_label_position(position) Set the label position (left or right) ACCEPTS: [ ‘left’ | ‘right’ ] set_offset_position(position) set_ticks_position(position) Set the ticks position (left.axis. matplotlib axis . but does not change the tick labels. 542 Chapter 37. ignore=False) If ignore is False. gridOn=None. the order of vmin. label2On=False.axis 543 .YTick(axes.0. Release 1. tick1On=True. pad=None. tickdir=None. color=None. vmax. the original axis orientation will be preserved. vmax does not matter.axis. tick_left() use ticks only on left tick_right() use ticks only on right class matplotlib.1 ACCEPTS: [ ‘left’ | ‘right’ | ‘both’ | ‘default’ | ‘none’ ] set_view_interval(vmin. tick2On=True. zorder=None.Tick Contains all the Artists needed to make a Y tick . major=True) Bases: matplotlib. label. width=None.Matplotlib. size=None. labelcolor=None. vmax. the label text and the grid line bbox is the Bound2D bounding box in display coords of the Axes loc is the tick location in data coords size is the tick size in points apply_tickdir(tickdir) get_data_interval() return the Interval instance for this axis data limits get_minpos() get_view_interval() return the Interval instance for this axis view limits set_view_interval(vmin. label1On=True. labelsize=None. matplotlib. loc.axis.the tick line.1. ignore=False) update_position(loc) Set the location of tick in data coords with scalar loc 37. 1 544 Chapter 37. matplotlib axis .Matplotlib.0. Release 1. squared=4.cbook. ondrink) #tmp = callbacks.process(’drink’.cbook.disconnect(ideat) callbacks. ’drink’. but a small do.1 matplotlib. ondrink) # this will raise a ValueError callbacks.activestate.Bunch(**kwds) Often we want to just collect a bunch of stuff together. and prettier to use. ’be merry’ def oneat(x): print ’eat’. 456) callbacks.connect(’drunk’. x callbacks = CallbackRegistry(signals) ideat = callbacks. Many (but not all) from the Python Cookbook – hence the name cbook class matplotlib.process(’eat’.process(’be merry’. naming each item of the bunch.CallbackRegistry(signals) Handle registering and disconnecting for a set of signals and callbacks: signals = ’eat’.nothing class is even handier.connect(’drink’.connect(’eat’.CHAPTER THIRTYEIGHT MATPLOTLIB CBOOK 38.process(’eat’. 123) callbacks. oneat) iddrink = callbacks. x def ondrink(x): print ’drink’. 456) # # # # # will call oneat will call ondrink nothing will be called disconnect oneat nothing will be called 545 .datum By: Alex Martelli From: http://aspn. Whenever you want to group a few variables: >>> point = Bunch(datum=2. a dictionary’s OK for that.cbook A collection of utility functions and classes. coord=12) >>> point.com/ASPN/Cookbook/Python/Recipe/52308 class matplotlib. 456) callbacks. and due to its design... **kwargs) process signal s.process(s. one should always disconnect all callbacks when they are no longer needed to avoid dangling references (and thus memory leaks).s .1 In practice. class. self. @organization: IBM Corporation @copyright: Copyright (c) 2005. For example: >>> class Foo: ... signals is a sequence of valid signals class BoundMethodProxy(cb) Bases: object Our own proxy object which enables weak references to bound and unbound methods and arbitrary callables. Pulls information about the function. To get around this.. def __repr__(self): . the CallbackRegistry won’t keep it alive. we instead store weak references to bound methods only. Stores a weak reference to the instance to support garbage collection. Release 1. s): . matplotlib cbook .. d. so we need to create a proxy object to handle weak references to bound methods (or regular free functions). e.cbook. and all disjoint sets can be retreived by using the object as an iterator. However. and instance out of a bound method. f = [Foo(x) for x in ’abcdef’] >>> g = Grouper() 546 Chapter 38. All of the functions registered to receive callbacks on s will be called with *args and **kwargs class matplotlib. so when the destination object needs to die. return self.. Objects can be joined using join(). The Python stdlib weakref module can not create weak references to bound methods directly.disconnect(cid) disconnect the callback registered with callback id cid CallbackRegistry. real code in matplotlib rarely does so.cbook.s = s . 2006 IBM Corporation @license: The BSD License Minor bugfixes by Michael Droettboom CallbackRegistry.Matplotlib. This technique was shared by Peter Parente on his “Mindtrove” blog.. it is rather difficult to place this kind of code..GetRealpathAndStat class matplotlib. b. and prevent this class of memory leaks.Grouper(init=[]) Bases: object This class provides a lightweight way to group arbitrary objects together into disjoint sets when a full-blown graph data structure would be overkill. The objects being joined must be hashable and weak-referenceable. *args..0.connect(s. >>> a. def __init__(self. func) register func to be called when a signal s is generated func will be called CallbackRegistry. c. tested for connectedness using joined(). join(d.Scheduler Bases: threading. Release 1. fig=None) report(segments=4) xy(i0=0.joined(a.join(b.cbook.cbook. isub=1) class matplotlib.Matplotlib.0. b. class matplotlib.cbook. e].joined(a.cbook 547 . c]] >>> g.1 >>> g. Accepts one or more arguments.cbook.join(a.cbook.” class matplotlib.RingBuffer(size_max) class that implements a not-yet-full buffer append(x) append an element at the end of the buffer get() Return a list of elements from the oldest to the newest.Scheduler Schedule callbacks when scheduler is idle run() class matplotlib. **kwargs) Null objects always and reliably “do nothing.joined(a. c) >>> g. b) Returns True if a and b are members of the same set.Thread 38.Idle(func) Bases: matplotlib. b) True >>> g. c) True >>> g. matplotlib. isub=1. join(a.1. [a.MemoryMonitor(nmax=20000) clear() plot(i0=0. e) >>> list(g) [[d. joined(a. class matplotlib.Null(*args. *args) Join given arguments into the same set. including itself. d) False clean() Clean dead weak references from the dictionary get_siblings(a) Returns all of the items joined with a. b) >>> g.cbook. Matplotlib.Sorter Sort by attribute or item Example usage: sort = Sorter() list = [(1. o must be in the stack clear() empty the stack empty() forward() move the position forward and return the current element home() push the first element onto the top of the stack push(o) push object onto stack at current position . itemindex=None.0. 2). 3)] dict = [{’a’: 3. ’b’: 0}. Release 1. (0. inplace=1) class matplotlib.cbook.1 Base class for timeout and idle scheduling stop() class matplotlib.Stack(default=None) Bases: object Implement a stack where elements can be pushed on and you can move back and forth. itemindex=None. matplotlib cbook . Should mimic home / back / forward in a browser back() move the position back and return the current element bubble(o) raise o to the top of the stack and return o. inplace=1) byItem(data. ’b’: 2}. {’a’: 9. attributename. 8).all elements occurring later than the current position are discarded remove(o) remove element o from the stack 548 Chapter 38. {’a’: 0. {’a’: 5. ’b’: 9}] sort(list) sort(list. inplace=1) sort(data. ’a’) # default sort # sort by index 1 # sort a list of dicts by key ’a’ byAttribute(data. (4. ’b’: 4}. 1) sort(dict. But no pop.cbook. matplotlib. "creator" : "Benevolent Dictator for Life". msg. class matplotlib.1.cbook. hdrs) Read the file from the cache since the server has no newer version. fp.cbook.pck. "Perl" : "Python". func) Bases: matplotlib.Matplotlib.0.cbook. If it does not exist.pck holds the directory of files that have been cached. a file object will be returned.ViewVCCachedServer(cache_dir. cache_file(url. code. data.Timeout(wait.cbook. response) Update the cache with the returned file. fetch it with urllib from the svn repo and store it in the cachedir. Else the path to the file as a string will be returned. baseurl) Bases: urllib2. asfileobj=True) Check the cachedirectory for a sample_data file. get_sample_data(fname.Scheduler Schedule recurring events with a wait time in seconds run() class matplotlib. http_response(req. } 38. in_cache_dir(fn) read_cache() Read the cache file from the cache directory. remove_stale_files() Remove files from the cache directory that are not listed in cache. write_cache() Write the cache data structure into the cache directory.cbook 549 . Release 1.Xlator Bases: dict All-in-one multiple-string-substitution class Example usage: text = "Larry Wall is the creator of Perl" adict = { "Larry Wall" : "Guido van Rossum".1 class matplotlib. The file cache. headers) Store a received file in the cache directory. If asfileobj is True. http_error_304(req. http_request(req) Make the request conditional if we have a cached file.BaseHandler Urllib2 handler that takes care of caching files. alltrue(seq) Return True if all elements of seq evaluate to True. matplotlib cbook . any argument with a length differing from that of the first argument (and hence anything in category 5) then will be passed through unchanged. If seq is 0 or 1 length.python matplotlib.l. It differs from textwrap.cbook.cbook. If seq is empty.1-D masked arrays 2.1 print multiple_replace(adict. 550 Chapter 38.cbook.cbook. missingval=None) Base class for handling string -> python type with support for missing values is_missing(s) matplotlib. [rows from all iterators matching func(row)]) It is used by matplotlib.xlat(text) xlat(text) Translate text.ndarrays with more than one dimension 4.allpairs(x) return all possible pairs in sequence x Condensed by Alex Martelli from this thread on c.1-D ndarrays 3.dedent(s) Remove excess indentation from docstring s. matplotlib. and return the arguments with only the unmasked points remaining.align_iterators(func.mlab.cbook. return False. It is also faster in most cases. return True matplotlib.converter(missing=’Null’.cbook.anything else The first argument must be in one of the first four categories. where n is the number of leading whitespace characters in the first line.Matplotlib.allequal(seq) Return True if all elements of seq compare equal. returns the modified text. Arguments can be in any of 5 categories: 1.0.other non-string iterables 5. Release 1. text) xlat = Xlator(adict) print xlat.dedent in its deletion of leading blank lines and its use of the first non-blank line to determine the indentation. class matplotlib.cbook. *iterables) This generator takes a bunch of iterables that are ordered by func It sends out ordered tuples: (func(row).delete_masked_points(*args) Find all masked and/or non-finite points in a set of arguments. then removes up to n whitespace characters from each line. Discards any leading blank lines.recs_join() to join record arrays matplotlib. matplotlib. 23)]]]]) so that >>> for i in flatten(l): print i.distances_along_curve(X) This function has been moved to matplotlib. a file object will be returned.12 in cookbook matplotlib. a point is bad if masked in a masked array or if it is a nan or inf.1 Masks are obtained from all arguments of the correct length in categories 1. keys) delete all of the keys from the dict d matplotlib.sourceforge. and 4 if np. No attempt is made to extract a mask from categories 2.cbook. you need to check out sample_data from matplotlib svn: svn co https://matplotlib. 38.scatter(). (1. [[[[42. and 4.flatten(seq. if case is True require an exact case match. matplotlib. 3.directory to the directory where we should look.com/ASPN/Cookbook/Python/Recipe/121294 and Recipe 1.svn.cbook. scalarp=<function is_scalar_or_string at 0x2f19410>) this generator flattens nested containers such as >>> l=( (’John’.get_recursive_filelist(args) Recurse all the files and dirs in args ignoring symbolic links and return the files as a list of strings matplotlib. asfileobj=True) Check the cachedirectory ~/. Else the path to the file as a string will be returned To add a datafile to this directory.net/svnroot/matplotlib/trunk/sample_data/ and store it in the cachedir. 2. This is primarily intended for use in mpl examples that need custom data.1.get_sample_data(fname.(5. If asfileobj is True.svn. Release 1.sourceforge. set the rc parameter examples. John Hunter 1 23 42 5 23 By: Composite of Holger Krekel and Luther Blissett From: http://aspn.net/svnroot/matplotlib/trunk/sample_data and svn add the data file you want to support. ’Hunter’).cbook. match.cbook.Matplotlib. fetch it with urllib from the mpl svn repo http://matplotlib.mlab – please import it from there matplotlib.cbook.exception_to_str(s=None) matplotlib. If it does not exist. A vastly simpler version of this function was originally written as a helper for Axes.cbook 551 .cbook.download to False and examples.23).dict_delall(d. All input arguments that are not passed unchanged are returned as ndarrays after removing the points or rows corresponding to masks in any of the arguments. matplotlib. To bypass all downloading.isfinite() does not yield a Boolean array.matplotlib/sample_data for a sample_data file.activestate. matplotlib.0.finddir(o. case=False) return all attributes of o which match string in match.cbook. get_split_ind(seq.cbook. Release 1.maxdict(maxsize) Bases: dict A dictionary with a maximum size.cbook.isvector(X) This function has been moved to matplotlib.Matplotlib. matplotlib cbook . return_folders=0) Recursively list files from Parmar and Martelli in the Python Cookbook class matplotlib. so use with caution matplotlib.join(seq[:ind])<=N matplotlib.is_sequence_of_strings(obj) Returns true if obj is iterable and contains strings matplotlib.mkdirs(newdir.1 matplotlib.cbook.cbook.is_string_like(obj) Return True if obj looks like a string matplotlib.cbook. klass) and return False on a TypeError matplotlib.issubclass_safe(x.cbook.less_simple_linear_interpolation(x. extrap=False) This function has been moved to matplotlib. Return the index into seq such that: len(’ ’.iterable(obj) return true if obj is iterable matplotlib. klass) return issubclass(x.cbook.mlab – please import it from there matplotlib.is_closed_polygon(X) This function has been moved to matplotlib.cbook.cbook.cbook.is_scalar_or_string(val) matplotlib. patterns=’*’. y.mlab – please import it from there matplotlib.is_scalar(obj) return true if obj is not string like and is not iterable matplotlib.cbook. Equivalent to > mkdir -p NEWDIR > chmod MODE NEWDIR 552 Chapter 38.cbook.0.is_math_text(s) matplotlib.cbook. xi. recurse=1.cbook. and set mode.is_writable_file_like(obj) return true if obj looks like a file object with a write method matplotlib. this doesn’t override all the relevant methods to contrain size.listFiles(root. mode=511) make directory newdir recursively.is_numlike(obj) return true if obj looks like a number matplotlib. N) seq is a list of words. just setitem.mlab – please import it from there matplotlib.cbook.cbook. q1y.1. q2y) This function has been moved to matplotlib. outstream=<open file ‘<stdout>’.cbook. q1x.soundex(name. flag=’rU’.report_memory(i=0) return the memory consumed by process matplotlib.cbook.cbook. return_opened=False) fname can be a filename or a file handle. matplotlib.cbook 553 .gz.popall(seq) empty a list matplotlib. missing=’Null’. Support for gzipped files is automatic.cbook. show_progress If True.Matplotlib.cbook. print the number of objects reached as they are found. mode ‘w’ at 0x7fe77cfc0150>.cbook. matplotlib.cbook.cbook.pieces(seq.path_length(X) This function has been moved to matplotlib.cbook.quad2cubic(q0x.cbook. if the filename ends in . len=4) soundex module conforming to Odell-Russell algorithm matplotlib.1 matplotlib.0.cbook. q0y. missingval=None) Bases: matplotlib. seq=None) Bases: list override repr when returning a list of matplotlib artists to prevent long.recursive_remove(path) matplotlib.mlab – please import it from there matplotlib.cbook. return False.safezip(*args) make sure args are equal len before zipping class matplotlib. outstream The stream for output.strip_math(s) remove latex formatting from mathtext matplotlib. flag is a read/write flag for file() class matplotlib.cbook.safe_masked_invalid(x) matplotlib. num=2) Break up the seq into num tuples matplotlib. Release 1. meaningless output.converter 38.garbage to find the cycles that are preventing some objects from being garbage collected.print_cycles(objects.reverse_dict(d) reverse the dictionary – may lose data if values are not unique! matplotlib.simple_linear_interpolation(a. show_progress=False) objects A list of objects to find cycles in.mlab – please import it from there matplotlib.to_filehandle(fname.cbook.cbook. This is meant to be used for a homogeneous list of a give type matplotlib. matplotlib. steps) matplotlib. q2x. It is often useful to pass in gc.cbook.todate(fmt=’%Y-%m-%d’.silent_list(type.onetrue(seq) Return True if one element of seq is True.cbook.cbook. It seq is empty. cbook. this was used to support masked arrays in Line2D. missingval=None) Bases: matplotlib.0.ndarray with each row the start and stop indices for slices of the compressed numpy. 554 Chapter 38. missingval=’‘) Bases: matplotlib.getmaskarray(y)) # returns array [[0. 5]] y.cbook.0. Returns None if there are no unmasked values. Returns Nx2 numpy.getmaskarray(y).1.4.arange(5).cbook. If optional argument compressed is False.compressed()[ii[1.cbook.tofloat(missing=’Null’.unicode_safe(s) matplotlib.cbook. Example: y = ma.converter convert to string or None matplotlib. mask = [0.2.0]) ii = unmasked_index_ranges(ma.0.filled()[ii[1.cbook.cbook. matplotlib cbook . missingval=None) Bases: matplotlib.strptime() format string for conversion class matplotlib.ndarray corresponding to each of N uninterrupted runs of unmasked values.tostr(missing=’Null’.cbook.Matplotlib.] [2.0]:ii[1. Release 1. mask will be flattened if it is not already 1-D. 2].ndarray. compressed=False) # returns array [[0.converter convert to an int or None class matplotlib.1 convert to a date or None use a time.4.converter convert to a datetime or None use a time.converter convert to a float or None class matplotlib.0]:ii[1.strptime() format string for conversion class matplotlib.ndarray. it returns the start and stop indices into the original numpy.1]] # returns array [3.cbook. not the compressed numpy.cbook.unmasked_index_ranges(mask. missing=’Null’. missingval=None) Bases: matplotlib.4.1]] # returns array [3.todatetime(fmt=’%Y-%m-%d’. compressed=True) Find index ranges where mask is False.cbook.unique(x) Return a list of unique elements of x matplotlib.toint(missing=’Null’.] ii = unmasked_index_ranges(ma.]] y.] Prior to the transforms refactoring. [3.array(np. P=2. cols) wrap text with prefix at length cols 38.cbook. text.mlab – please import it from there matplotlib.wrap(prefix.1 matplotlib.1.cbook 555 . axis=None) This function has been moved to matplotlib.cbook.vector_lengths(X.Matplotlib. matplotlib. Release 1.0.0. matplotlib cbook . Release 1.1 556 Chapter 38.0.Matplotlib. cm This module provides a large set of colormaps. max of the color limits for image scaling get_cmap() return the colormap set_array(A) Set the image array from numpy array A 557 .ScalarMappable(norm=None. return True. and a mixin class for adding color mapping functionality. autoscale() Autoscale the scalar limits on the norm instance using the current array autoscale_None() Autoscale the scalar limits on the norm instance using the current array.jet add_checker(checker) Add an entry to a dictionary of boolean flags that are set to True when the mappable is changed. functions for registering new colormaps and for getting a colormap by name.1 matplotlib. used to map luminance to 0-1.cm. cmap=None) This is a mixin class to support scalar -> RGBA mapping. else return False get_array() Return the array get_clim() return the min. cmap is a cm colormap instance. class matplotlib. changing only limits that are None changed() Call this whenever the mappable is changed to notify all the callbackSM listeners to the ‘changed’ signal check_update(checker) If mappable has changed since the last check. Handles normalization and colormapping norm is an instance of colors. for example cm.Normalize or one of its subclasses.CHAPTER THIRTYNINE MATPLOTLIB CM 39. Colormap instance. matplotlib. insert alpha.0.get_cmap(name=None. Colormaps added with register_cmap() take precedence over builtin colormaps. if vmin is a length2 sequence. and name must be a standard mpl colormap name with a corresponding data dictionary in datad. The name is optional.register_cmap(name=None. alpha=None. matplotlib. vmax=None) set the norm limits for image scaling. if absent. cmap=swirly_cmap) register_cmap(name=’choppy’. the name will be the name attribute of the cmap. lut=128) In the first case. matplotlib. bytes=False) Return a normalized rgba array corresponding to x. data=choppydata. If name is a colors. lut=None) Add a colormap to the set recognized by get_cmap(). return it unchanged.revcmap(data) 558 Chapter 39. interpret it as (vmin.cm. matplotlib cm . defaulting to rc values if name is None. data=None.cm.Colormap instance. the three arguments are passed to the colors. It can be used in two ways: register_cmap(name=’swirly’.1 set_clim(vmin=None. vmax) which is used to support setp ACCEPTS: a length 2 sequence of floats set_cmap(cmap) set the colormap for luminance data ACCEPTS: a colormap or registered colormap name set_colorbar(im. it will be returned. Release 1. if it is already rgba. If lut is not None it must be an integer giving the number of entries desired in the lookup table. return rgba as 4 uint8s instead of 4 floats.LinearSegmentedColormap initializer. In the second case. lut=None) Get a colormap instance. and the resulting colormap is registered. If x is already an rgb array.cm. If bytes is True. cmap must be a colors.Matplotlib. ax) set the colorbar image and axes associated with mappable set_norm(norm) set the normalization instance to_rgba(x. cmap=None. g.AsteriskPolygonCollection(numsides.CircleCollection collections.LineCollection collections.QuadMesh artist. sizes=(1.g. you may not be able to select all line styles) but they are meant to be fast for common use cases (e.StarPolygonCollection collections. numsides the number of sides of the polygon rotation the rotation of the polygon in radians sizes gives the area of the circle circumscribing the regular polygon in points^2 559 .Collection cm.AsteriskPolygonCollection collections.BrokenBarHCollection collections.PolyCollection collections.collections.PathCollection collections. a large set of solid line segemnts) class matplotlib.collections.ScalarMappable collections. **kwargs) Bases: matplotlib. ).g. a large number of line segments or polygons.CHAPTER FORTY MATPLOTLIB COLLECTIONS collections. e.RegularPolyCollection Draw a collection of regular asterisks with numsides points. The classes are not meant to be as flexible as their single element counterparts (e. rotation=0.collections Classes for the efficient drawing of large collections of objects that share most properties.RegularPolyCollection collections.EllipseCollection collections.PatchCollection 40.Artist collections.1 matplotlib. antialiaseds are None. matplotlib collections .cm.1) collection = RegularPolyCollection( numsides=5.1 Valid Collection keyword arguments: • edgecolors: None • facecolors: None • linewidths: None • antialiaseds: None • offsets: None • transOffset: transforms. in sequence form.py for complete example: offsets = np.ScalarMappable) • cmap: None (optional for matplotlib. yrange.). # a pentagon rotation=0. ) class matplotlib. xranges sequence of (xmin.PolyCollection A collection of horizontal bars spanning yrange with a sequence of xranges. sizes=(50.random.Matplotlib.2) facecolors = [cm.). transOffset = ax.rand(20)] black = (0. **kwargs) Bases: matplotlib. ywidth Valid Collection keyword arguments: • edgecolors: None • facecolors: None • linewidths: None • antialiaseds: None • offsets: None 560 Chapter 40. Example: see examples/dynamic_collection.).collections. they default to their matplotlib.0.cm. facecolors.rcParams patch setting.transData.collections. offsets = offsets. edgecolors = (black. Release 1.jet(x) for x in np.random.0. xwidth) yrange ymin.BrokenBarHCollection(xranges. linewidths = (1.0.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors. linewidths. facecolors = facecolors.rand(20.IdentityTransform() • norm: None (optional for matplotlib. urls=None. renderer.cm.rcParams patch setting.1. where. ymax.rcParams patch setting.artist. linewidths. The bars range on the y-axis from ymin to ymax A BrokenBarHCollection is returned. cmap=None. linewidths. **kwargs) Create a BrokenBarHCollection to plot horizontal bars from over the regions in x where where is True. in sequence form.collections. ymin.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors.cm. draw(artist.Collection(edgecolors=None.collections. 40.ScalarMappable) •cmap: None (optional for matplotlib. **kwargs) Bases: matplotlib. facecolors. linestyles=’solid’. antialiaseds are None. sizes Gives the area of the circle in points^2 Valid Collection keyword arguments: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •offsets: None •transOffset: transforms.CircleCollection(sizes.cm.ScalarMappable Base class for Collections. facecolors=None.collections 561 . antialiaseds=None.IdentityTransform() • norm: None (optional for matplotlib.0. linewidths=None. transOffset=None.ScalarMappable) • cmap: None (optional for matplotlib. facecolors.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors. they default to their matplotlib.0. norm=None. kwargs are passed on to the collection.Artist. Release 1. antialiaseds are None.Collection A collection of circles.cm. class matplotlib. *args. in sequence form. offsets=None. Must be subclassed to be usable. **kwargs) Bases: matplotlib.collections. they default to their matplotlib.cm. matplotlib. pickradius=5. matplotlib.1 • transOffset: transforms. **kwargs) get_sizes() return sizes of circles class matplotlib. drawn using splines.Matplotlib. static span_where(x.IdentityTransform() •norm: None (optional for matplotlib. Returns True | False. draw(artist. dict(ind=itemlist). renderer.cm. If any of edgecolors.Matplotlib.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets).IdentityTransform() •norm: None (optional for matplotlib. **kwargs) get_dashes() get_datalim(transData) get_edgecolor() get_edgecolors() get_facecolor() get_facecolors() get_linestyle() get_linestyles() get_linewidth() get_linewidths() 562 Chapter 40. they will be converted to sequences. they default to their matplotlib.1 All properties in a collection must be sequences or scalars.ScalarMappable) •cmap: None (optional for matplotlib. Release 1. Create a Collection %(Collection)s contains(mouseevent) Test whether the mouse event occurred in the collection. where every item in itemlist contains the event.cm. If the ScalarMappable matrix _A is not None (ie a call to set_array has been made). *args. in sequence form. linewidths. if scalars. matplotlib collections . The property of the ith element of the collection is: prop[i % len(props)] Keyword arguments and default values: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •offsets: None •transOffset: transforms. facecolors. antialiaseds are None. The use of ScalarMappable is optional.0. at draw time a call to scalar mappable will be made to set the face colors.rcParams patch setting. or a sequence of rgba tuples. c can be a matplotlib color arg (all patches have same color). the edge color will always be the same as the face color. the patch will not be filled. or a sequence of rgba tuples. 40. ACCEPTS: Boolean or sequence of booleans set_antialiaseds(aa) alias for set_antialiased set_color(c) Set both the edgecolor and the facecolor. if it is a sequence the patches will cycle through the sequence. if it is a sequence the patches will cycle through the sequence. matplotlib. If c is ‘face’.1.Matplotlib. the patch boundary will not be drawn. If c is ‘none’. ACCEPTS: matplotlib color arg or sequence of rgba tuples See Also: set_facecolor(). c can be a matplotlib color arg (all patches have same color). If it is ‘none’. alpha must be a float or None. ACCEPTS: float or None set_antialiased(aa) Set the antialiasing state for rendering. Release 1. set_edgecolor() For setting the edge or face color individually.0.1 get_offsets() Return the offsets for the collection. set_dashes(ls) alias for set_linestyle set_edgecolor(c) Set the edgecolor(s) of the collection.collections 563 . get_paths() get_pickradius() get_transforms() get_urls() get_window_extent(renderer) set_alpha(alpha) Set the alpha tranparencies of the collection. ACCEPTS: matplotlib color arg or sequence of rgba tuples set_edgecolors(c) alias for set_edgecolor set_facecolor(c) Set the facecolor(s) of the collection. on-off-dash-seq) ] set_linestyles(ls) alias for set_linestyle set_linewidth(lw) Set the linewidth(s) for the collection.1 ACCEPTS: matplotlib color arg or sequence of rgba tuples set_facecolors(c) alias for set_facecolor set_linestyle(ls) Set the linestyle(s) for the collection. ‘dotted’ | (offset.g.collections.EllipseCollection(widths. heights.0. drawn using splines.Matplotlib. if it is a sequence the patches will cycle through the sequence ACCEPTS: float or sequence of floats set_linewidths(lw) alias for set_linewidth set_lw(lw) alias for set_linewidth set_offsets(offsets) Set the offsets for the collection. lw can be a scalar or a sequence.. ACCEPTS: float or sequence of floats set_paths() set_pickradius(pickradius) set_urls(urls) update_from(other) copy properties from other to self update_scalarmappable() If the scalar mappable array is not none. offsets can be a scalar or a sequence. matplotlib collections . update colors from scalar data class matplotlib. widths: sequence lengths of first axes (e.Collection A collection of ellipses. angles.collections. Release 1. ‘dashdot’. major axis lengths) heights: sequence lengths of second axes angles: sequence angles of first axes. ACCEPTS: [’solid’ | ‘dashed’. **kwargs) Bases: matplotlib. degrees CCW from the X-axis units: [’points’ | ‘inches’ | ‘dots’ | ‘width’ | ‘height’ ‘x’ | ’y’ | ’xy’] 564 Chapter 40. units=’points’. rcParams patch setting. linestyles=’solid’.1. ‘width’ and ‘height’ refer to the dimensions of the axes. not allowed).. and equals the specified angle only when the aspect ratio is unity. *args.ScalarMappable) •cmap: None (optional for matplotlib. Release 1. renderer. linewidths.. The property of the ith line segment is: prop[i % len(props)] i.LineCollection(segments.0.Collection All parameters must be sequences or scalars. cmap=None. norm=None. etc. pickradius=5. the properties cycle if the len of props is less than the number of segments.cm. antialiaseds are None. onoffseq).collections. antialiaseds=None. they will be converted to sequences. ‘xy’ differs from all others in that the angle as plotted varies with the aspect ratio.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors. ym) or the equivalent numpy array with two columns. colors must be a sequence of RGBA tuples (eg arbitrary color strings. y1). they default to their matplotlib..1 units in which majors and minors are given.collections 565 . line2). transOffset=None. 40. . **kwargs) Bases: matplotlib. while ‘x’ and ‘y’ refer to the offsets data units. in sequence form. line1. linewidths=None. y0). Each line can be a different length. (xm. matplotlib. Hence it behaves the same as the Ellipse with axes. offsets=None. The dash tuple is: (offset. Additional kwargs inherited from the base Collection: Valid Collection keyword arguments: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •offsets: None •transOffset: transforms. where: linen = (x0. if scalars.e.Matplotlib.IdentityTransform() •norm: None (optional for matplotlib. facecolors.transData as its transform. antialiaseds must be a sequence of ones or zeros linestyles [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] a string or dash tuple. colors=None. segments a sequence of (line0. **kwargs) class matplotlib.collections.cm. (x1. draw(artist. If linewidths. In this case. patches a sequence of Patch objects. if it is a sequence the patches will cycle through the sequence ACCEPTS: matplotlib color arg or sequence of rgba tuples get_color() get_colors() set_color(c) Set the color(s) of the line collection. The default is 5 pt. at draw time a call to scalar mappable will be made to set the colors. norm None (optional for matplotlib.1 where onoffseq is an even length tuple of on and off ink in points.ScalarMappable) cmap None (optional for matplotlib. c can be a matplotlib color arg (all patches have same color).cm. c can be a matplotlib color arg (all patches have same color). then the offsets are added to the segments before any transformation. color(c) Set the color(s) of the line collection. This list may include a heterogeneous assortment of different patch types.yo) and this value will be added cumulatively to each successive segment. or a sequence or rgba tuples. colors. If the ScalarMappable matrix _A is not None (ie a call to set_array() has been made). This makes it easier to assign a color map to a heterogeneous collection of patches. 566 Chapter 40. match_original=False.collections. **kwargs) Bases: matplotlib. a single offset can be specified as: offsets=(xo. in sequence form. or antialiaseds is None. if it is a sequence the patches will cycle through the sequence. This also may improve plotting speed.ScalarMappable) pickradius is the tolerance for mouse clicks picking a line.Collection A generic collection of patches. or a sequence or rgba tuples. The use of ScalarMappable is optional.0.Matplotlib.PatchCollection(patches. then offsets are transformed by transOffset and applied after the segments have been transformed to display coordinates. Release 1. so as to produce a set of successively offset curves. they default to their rcParams setting.collections. matplotlib collections .cm. since PatchCollection will draw faster than a large number of patches. ACCEPTS: matplotlib color arg or sequence of rgba tuples set_paths(segments) set_segments(segments) set_verts(segments) class matplotlib. If offsets is not None but transOffset is None. If offsets and transOffset are not None. they default to their matplotlib. closed=True.Collection verts is a sequence of ( verts0.ScalarMappable) •cmap: None (optional for matplotlib.1. The use of ScalarMappable is optional. linewidths. antialiaseds are None. paths is a sequence of matplotlib. **kwargs) Bases: matplotlib. .rcParams patch setting. facecolors.cm. use the colors and linewidths of the original patches.rcParams patch setting. in sequence form. If len(sizes) < nv. Valid Collection keyword arguments: •edgecolors: None 40. sizes=None. linewidths.cm. set_paths(patches) class matplotlib. will explicitly close the polygon.. then the overall scaling is such that if verts_i specify a unit square.Collection This is the most basic Collection subclass.IdentityTransform() •norm: None (optional for matplotlib. in sequence form. 2).path. The scaling is applied before the Artist master transform. then sizes_i is the area of that square in points^2. Valid Collection keyword arguments: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •offsets: None •transOffset: transforms. If False.Matplotlib. verts1. sizes is None (default) or a sequence of floats that scale the corresponding verts_i. facecolors. Release 1.collections.collections. facecolor. at draw time a call to scalar mappable will be made to set the face colors.1 match_original If True. closed. they default to their matplotlib. edgecolor. norm or cmap.collections. linewidths. new colors may be assigned by providing the standard collection arguments. antialiaseds are None. set_paths(paths) class matplotlib. the additional values will be taken cyclically from the array. matplotlib.PathCollection(paths. or an equivalent numpy array of shape (nv.Path instances..collections 567 . If any of edgecolors.PolyCollection(verts.collections. when True. **kwargs) Bases: matplotlib.) where verts_i is a sequence of xy tuples of vertices.0. If the ScalarMappable matrix _A is not None (ie a call to set_array has been made). if the latter is an identity transform.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors. n + 1). The mesh need not be regular and the polygons need not be convex. linewidths.cm. (m. To define the function that maps from a data point to its corresponding color. matplotlib collections .rcParams patch setting.QuadMesh(meshWidth.collections. closed=True) This allows one to delay initialization of the vertices.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors. 1). antialiased=True. (m + 1. and (m + 1.Collection Class for the efficient drawing of a quadrilateral mesh.1 •facecolors: None •linewidths: None •antialiaseds: None •offsets: None •transOffset: transforms. they default to their matplotlib.ScalarMappable) •cmap: None (optional for matplotlib. and so on. 0). (1. n). shading=’flat’. set_verts(verts. 568 Chapter 40. in sequence form. 2) . closed=True) This allows one to delay initialization of the vertices. (0.collections. **kwargs) set_paths(verts. n + 1).IdentityTransform() •norm: None (optional for matplotlib. in the case of the colors). n) such that 0 <= m <= meshWidth and 0 <= n <= meshHeight. *args. (1. 1). The dimensions of this array are (meshWidth + 1. For example. the vertices at mesh coordinates (m. antialiaseds are None. meshHeight + 1). coordinates) Converts a given mesh into a sequence of matplotlib. 0). then the one at (0. coordinates. then at (0. showedges. draw(artist. **kwargs) Bases: matplotlib.. meshWidth). There are thus (meshWidth * meshHeight) quadrilaterals in the mesh. ‘faceted’ or ‘gouraud’ static convert_mesh_to_paths(meshWidth.Matplotlib.path. where each row is the x and y coordinates of one of the vertices. use the set_cmap() method. n) form one of the quadrilaterals in the mesh. This function is primarily of use to backend implementers.0. For any values (m. Each vertex in the mesh has a different set of “mesh coordinates” representing its position in the topology of the mesh. A quadrilateral mesh is represented by a (2 x ((meshWidth + 1) * (meshHeight + 1))) numpy array coordinates. the first entry in coordinates is the coordinates of the vertex at mesh coordinates (0. class matplotlib. A quadrilateral mesh consists of a grid of vertices. facecolors.Path objects for easier rendering by backends that do not directly support quadmeshes. Release 1.cm. renderer. Each of these arrays is indexed in row-major order by the mesh coordinates of the vertex (or the mesh coordinates of the lower left vertex. meshHeight. shading may be ‘flat’. meshHeight. coordinates) Converts a given mesh into a sequence of triangles.cm. matplotlib. draw(artist.IdentityTransform() • norm: None (optional for matplotlib.0. sizes=(1.rand(20.collections. linewidths = (1. **kwargs) get_datalim(transData) get_paths() set_paths() class matplotlib. meshHeight.Matplotlib. facecolors. renderer.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors.0. in sequence form.Collection Draw a collection of regular polygons with numsides.1. This is useful for experiments using draw_qouraud_triangle.collections 569 . Example: see examples/dynamic_collection. # a pentagon rotation=0.).random. they default to their matplotlib.1 convert_mesh_to_triangles(meshWidth.ScalarMappable) • cmap: None (optional for matplotlib. sizes=(50.1) collection = RegularPolyCollection( numsides=5. each point with its own color.cm. edgecolors = (black. offsets = offsets. antialiaseds are None. linewidths. ). facecolors = facecolors. *args.). 40. rotation=0.0. Release 1.2) facecolors = [cm.rcParams patch setting.random.py for complete example: offsets = np.).RegularPolyCollection(numsides. numsides the number of sides of the polygon rotation the rotation of the polygon in radians sizes gives the area of the circle circumscribing the regular polygon in points^2 Valid Collection keyword arguments: • edgecolors: None • facecolors: None • linewidths: None • antialiaseds: None • offsets: None • transOffset: transforms. **kwargs) Bases: matplotlib.jet(x) for x in np.collections.rand(20)] black = (0. renderer.). # a pentagon rotation=0.StarPolygonCollection(numsides.IdentityTransform() • norm: None (optional for matplotlib. linewidths. offsets = offsets. Release 1. Example: see examples/dynamic_collection.random.cm.rand(20.cm. **kwargs) get_numsides() get_rotation() get_sizes() class matplotlib. antialiaseds are None.transData.collections.). in sequence form. ) draw(artist.2) facecolors = [cm. matplotlib collections . sizes=(50.).rcParams patch setting.0.random. 570 Chapter 40.1 transOffset = ax.RegularPolyCollection Draw a collection of regular stars with numsides points. rotation=0.py for complete example: offsets = np. edgecolors = (black.jet(x) for x in np. **kwargs) Bases: matplotlib. linewidths = (1. sizes=(1.collections. facecolors.0.rand(20)] black = (0. facecolors = facecolors.0. numsides the number of sides of the polygon rotation the rotation of the polygon in radians sizes gives the area of the circle circumscribing the regular polygon in points^2 Valid Collection keyword arguments: • edgecolors: None • facecolors: None • linewidths: None • antialiaseds: None • offsets: None • transOffset: transforms.ScalarMappable) offsets and transOffset are used to translate the patch after rendering (default no offsets) If any of edgecolors. ).ScalarMappable) • cmap: None (optional for matplotlib. they default to their matplotlib.Matplotlib. *args.1) collection = RegularPolyCollection( numsides=5. transData.collections 571 .1.0. matplotlib.Matplotlib. ) 40. Release 1.1 transOffset = ax. 1 572 Chapter 40.0. Release 1. matplotlib collections .Matplotlib. instead. ticks=None.. Colorbar the derived class for use with images or contour plots. spacing=’uniform’.colorbar.Colorbar(ax. make_axes() a function for resizing an axes and adding a second axes suitable for a colorbar The colorbar() method uses make_axes() and Colorbar. boundaries=None.g. values=None. update_bruteforce(mappable) Destroy and rebuild the colorbar. lines. format=None. **kw) Bases: matplotlib. image) is not needed. This is meant to be called when the image or contour plot to which this colorbar belongs is changed.colorbar method are used to create the colorbar. cmap=None. It can be used as-is to make a colorbar for a given colormap.colorbar Colorbar toolkit with two classes and a function: ColorbarBase the base class with full colorbar drawing functionality. class matplotlib.colorbar. it does not clear the axes. update_normal(mappable) update solid.colorbar function or the Figure.1 matplotlib. class matplotlib. filled=True) 573 . use colorbar() or colorbar() to make your colorbar. It is not intended to be instantiated directly.colorbar. orientation=’vertical’. alpha=None.ColorbarBase This class connects a ColorbarBase to a ScalarMappable such as a AxesImage generated via imshow(). drawedges=False. It is not called when the pyplot. mappable. the colorbar() function is a thin wrapper over colorbar(). Unlike update_bruteforce. This is intended to become obsolete. norm=None. and will probably be deprecated and then removed. extend=’neither’. add_lines(CS) Add the lines from a non-filled ContourSet to the colorbar. a mappable object (e.CHAPTER FORTYONE MATPLOTLIB COLORBAR 41. etc.ColorbarBase(ax. Tick locations are updated immediately unless update_ticks is False. matplotlib colorbar . add_lines(levels.Matplotlib. It is also useful by itself for showing a colormap. **kw) Resize and reposition a parent axes. and return a child axes suitable for a colorbar: cax. update_ticks=True) set tick labels. To show the under. update_ticks() Force the update of the ticks and ticklabels. matplotlib. then the colormap will be displayed on a 0-1 scale. config_axis() draw_all() Calculate any free parameters based on the current cmap and norm. **kw) Label the long axis of the colorbar set_ticklabels(ticklabels. Useful attributes: ax the Axes instance in which the colorbar is drawn lines a LineCollection if lines were drawn. which are the usual ways of creating a colorbar. To manually update the ticks. call update_ticks method explicitly. This is a base class for the Colorbar class. colors.cm. set_ticks(ticks. and do all the drawing. use: norm=colors. Tick labels are updated immediately unless update_ticks is False. call update_ticks method explicitly. Release 1.NoNorm. **kw) Keyword arguments may include the following (with defaults): 574 Chapter 41.Normalize(clip=False) To show the colors versus index instead of on the 0-1 scale. which is the basis for the colorbar() function and the colorbar() method.ScalarMappable Draw a colorbar in an existing axes. This must be called whenever the tick locator and/or tick formatter changes. To manually update the ticks.0. If the cmap kwarg is given but boundaries and values are left as None. specify the norm as: colors. kw = make_axes(parent.make_axes(parent.colorbar.and over-value colors. set_alpha(alpha) set_label(label. update_ticks=True) set tick locations. linewidths) Draw lines on the colorbar.1 Bases: matplotlib. otherwise None dividers a LineCollection if drawedges is True. otherwise None Useful public methods are set_label() and add_lines(). 15 if horizontal.15.1 orientation ‘vertical’ or ‘horizontal’ Property orientation fraction pad shrink aspect Description vertical or horizontal 0.05 if vertical. matplotlib.0. fraction by which to shrink the colorbar 20. ratio of long to short dimensions All but the first of these are stripped from the input kw set. fraction of original axes between colorbar and new image axes 1.Matplotlib. Release 1. 0.0. Returns (cax. kw). fraction of original axes to use for colorbar 0.1. 41. the child axes and the reduced kw dictionary.colorbar 575 . matplotlib colorbar .Matplotlib.1 576 Chapter 41.0. Release 1. which is used for generating a custom colormap from a list of color specifications.75’ 577 . and ListedColormap. Two are provided here: LinearSegmentedColormap. 3 or 4 floats in the range 0-1. Colormapping typically involves two steps: a data array is first mapped onto the range 0-1 using an instance of Normalize or of a subclass.1 matplotlib. respectively. of the ColorConverter class providing methods for converting single color specifications or sequences of them to RGB or RGBA. For the basic builtin colors. e.g. you can use a single letter • b : blue • g : green • r : red • c : cyan • m : magenta • y : yellow • k : black • w : white Gray shades can be given as a string encoding a float in the 0-1 range. The module also provides a single instance. but is also useful for making custom colormaps. which is used to generate all the built-in colormap instances.colors A module for converting numbers or color arguments to RGB or RGBA RGB and RGBA are sequences of. Commands which take color arguments can use several formats to specify the colors.: color = ’0. This module includes functions and classes for color specification conversions. and for mapping numbers to colors in a 1-D array of colors called a colormap. colorConverter. then this number in the 0-1 range is mapped to a color using an instance of a subclass of Colormap.CHAPTER FORTYTWO MATPLOTLIB COLORS 42. alpha=None) Returns an RGBA tuple of four floats from 0-1. Finally. like ‘#00FFFF’ 3. as i varies from 0 to len(boundaries)-2. 578 Chapter 42. like ‘0.a letter from the set ‘rgbcmykw’ 2. where each of R . G .BoundaryNorm(boundaries. You can specify the color using an html hex string. Unlike Normalize or LogNorm.colors. Out-of-range values are mapped to -1 if low and ncolors if high. and reduces the number of conversions back and forth between integer and floating point.ColorConverter Provides methods for converting color specifications to RGB or RGBA Caching is used for more efficient conversion upon repeated calls with the same argument. class matplotlib. to_rgba(arg. ncolors. boundaries a monotonically increasing sequence ncolors number of colors in the colormap to be used If: b[i] <= v < b[i+1] then v is mapped to color j. like ‘red’. legal html names for colors. the A will simply be discarded.__call__() . G . Ordinarily only the single instance instantiated in this module.a standard name. Mapping to the 0-1 interval could have been done via piece-wise linear interpolation. Release 1. you have two options.4’. clip=False) Bases: matplotlib.1 For a greater range of colors. these are converted to valid indices by Colormap. indicating gray on a 0-1 scale if arg is RGBA. B are in the range [0. j goes from 0 to ncolors-1. inverse(value) class matplotlib. as in: color = ’#eeefff’ or you can pass an R . colorConverter.colors.a float.Matplotlib. ‘burlywood’ and ‘chartreuse’ are supported.colors.0. is needed. matplotlib colors .a hex color string. but using integers seems simpler. B tuple. to_rgb(arg) Returns an RGB tuple of three floats from 0-1. arg can be an RGB or RGBA sequence or a string in any of several forms: 1.1]. like ‘aqua’ 4. BoundaryNorm maps values to integers instead of to the interval 0-1.Normalize Generate a colormap index based on discrete intervals. alpha=None) Set color to be used for low out-of-range values. Angles are in degrees. Accepts a single mpl color spec or a sequence of specs. The default extremes are chose so that completely shaded points are nearly black (s = 1. then (0.clip = False class matplotlib. N=256) Base class for all scalar to rgb mappings Important methods: •set_bad() •set_under() •set_over() Public class attributes: N : number of rgb quantization levels name : name of colormap is_gray() set_bad(color=’k’. hsv_min_sat=1.clip = False set_under(color=’k’. Release 1. v = 0) and completely illuminated points are nearly white (s = 0.0. with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. v = 1). hsv_max_val=1. then adjust those color 42.0. matplotlib. The shade() is used to produce rgb values for a shaded relief image given a data array.colors 579 .0. In addition. to_rgba_array(c. then an empty array will be returned. If arg is an RGBA sequence and alpha is not None. hsv_min_val=0. shade(data.Matplotlib. alpha=None) Returns a numpy array of RGBA tuples. or lightened by sliding (s. Requires norm. Special case to handle “no color”: if c is “none” (case-insensitive). see to_rgb(). hsv_max_sat=0) Bases: object Create a light source coming from the specified azimuth and elevation.0) will be returned.v) values (in hsv colorspace) toward (hsv_min_sat. altdeg=45.colors. alpha=None) Set color to be used for high out-of-range values.1. if arg is “none” (case-insensitive).Colormap(name. The color of the resulting image will be darkened by moving the (s.LightSource(azdeg=315. Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees. alpha will replace the original A. Same for an empty list. convert to HSV values in the given colormap. class matplotlib. cmap) Take the input data array. set_over(color=’k’. hsv_min_val) in the shaded regions.colors. Requires norm. alpha=None) Set color to be used for masked values.v) toward (hsv_max_sat hsv_max_val) in regions that are illuminated.1 For acceptable values of arg. (0.0.0). 1. For any input value z falling between x[i] and x[i+1]. with the 0-1 domain divided into any number of segments.0) Bases: matplotlib. 0.0. 0. makeMappingArray() For information about making a mapping array.0.0)].LinearSegmentedColormap(name.0. y0.0.75. 1.0)]. The lookup table is generated using linear interpolation for each primary color. green to do the same over the middle half. 1. (0. 1.5. elevation.0.0. ’blue’: [(0.0.0. N=256. class matplotlib.0). segmentdata. matplotlib colors . factory function for generating a smoothly-varying LinearSegmentedColormap. Then you would use: cdict = {’red’: [(0.0). Example: suppose you want red to increase from 0 to 1 over the bottom half. 0. 0. 0. 580 Chapter 42. y0. and blue over the top half. Each entry should be a list of x.25.0. (0. 0. (1. 1.0. ’green’: [(0.Colormap Colormap objects based on lookup tables using linear segments. which can then be used to plot the shaded image with imshow.0. x must increase monotonically from 0 to 1. 1. y1 tuples. 1. 0.5. 0. forming rows in a table. green and blue entries. 1.0.0.0. Create color map from linear mapping segments segmentdata argument is a dictionary with a red.0). 1.0.0)]} Each row in the table for a given color is a sequence of x.Matplotlib.0) Take the input RGB array (ny*nx*3) adjust their color values to given the impression of a shaded relief map with a specified light source using the elevation (ny*nx).1 values to given the impression of a shaded relief map with a specified light source.colors. gamma=1. 1.0). See Also: LinearSegmentedColormap.colors. (1.0).0). y1 tuples. A new RGB array ((ny*nx*3)) is returned. shade_rgb(rgb. fraction=1. In each sequence. 0. RGBA values are returned. 0. (0.0.from_list() Static method. Release 1. (1. the output value of a given color will be linearly interpolated between y1[i] and y0[i+1]: row i: x y0 y1 / row i+1: x / y0 y1 Hence y0 in the first row and y1 in the last row are never used. color) tuples can be given to divide the range unevenly. colors. If clip is True and the given value falls outside the range. gamma=1. class matplotlib. autoscale(A) Set vmin.1 static from_list(name. in which case there is one colormap entry for each element in the list of colors.LogNorm(vmin=None. autoscale_None(A) autoscale only None-valued vmin or vmax inverse(value) 42. name=’from_list’. If: N > len(colors) the list will be extended by repetition. Alternatively. whichever is closer. or an equivalent Nx3 floating point array (N rgb values) name a string to identify the colormap N the number of entries in the map. under.colors 581 .0) Make a linear segmented colormap with name from a sequence of colors which evenly transitions from colors[0] at val=0 to colors[-1] at val=1. including masked arrays. Clipping silently defeats the purpose of setting the over. the returned value will be 0 or 1. N=None) Bases: matplotlib. masked values are set to 1.colors. The default is None.Matplotlib. max of A.0. vmax to min.1. Release 1. so it is likely to lead to surprises.Colormap Colormap object generated from a list of colors. If: N < len(colors) the list will be truncated at N. N is the number of rgb quantization levels.ListedColormap(colors. vmax=None. N=256. a list of (value. and masked colors in the colormap. they are taken from the input’s minimum and maximum value respectively. matplotlib.colors.Normalize Normalize a given value to the 0-1 range on a log scale If vmin or vmax is not given. colors a list of matplotlib color specifications. otherwise they remain masked. Returns 0 if: vmin==vmax Works with scalars or arrays. class matplotlib. but it can also be used to generate special colormaps for ordinary mapping.colors. therefore the default is clip = False.colors. set_gamma(gamma) Set a new gamma value and regenerate color map. If clip is True. Make a colormap from a list of colors. clip=False) Bases: matplotlib. This may be most useful when indexing directly into a colormap. clip=False) Bases: matplotlib.NoNorm(vmin=None. vmax to min.1 class matplotlib.93725) matplotlib.colors. masked values are set to 1. and masked colors in the colormap. for the case where we want to use indices directly in a ScalarMappable . 0. including masked arrays. and masked colors in the colormap.colors.hsv_to_rgb(hsv) convert hsv values in a numpy array to rgb values both input and output arrays have shape (M.Normalize(vmin=None. therefore the default is clip = False. the returned value will be 0 or 1. therefore the default is clip = False. vmax=None.colors.0) Create an N -element 1-d lookup table 582 Chapter 42.makeMappingArray(N. If clip is True and the given value falls outside the range. whichever is closer. so it is likely to lead to surprises.is_color_like(c) Return True if c can be converted to RGB matplotlib. Release 1.Normalize Dummy replacement for Normalize. under. If clip is True and the given value falls outside the range. If clip is True. matplotlib colors . whichever is closer. Clipping silently defeats the purpose of setting the over.3) matplotlib. the returned value will be 0 or 1. including masked arrays.colors. gamma=1.0. autoscale_None(A) autoscale only None-valued vmin or vmax inverse(value) scaled() return true if vmin and vmax set matplotlib. otherwise they remain masked. max of A. autoscale(A) Set vmin.93725. vmax=None.hex2color(s) Take a hex string s and return the corresponding rgb 3-tuple Example: #efefef -> (0. If vmin or vmax is not given.colors. masked values are set to 1.N. otherwise they remain masked. Clipping silently defeats the purpose of setting the over.colors. inverse(value) class matplotlib.Matplotlib. If clip is True. data. they are taken from the input’s minimum and maximum value respectively. so it is likely to lead to surprises. they are taken from the input’s minimum and maximum value respectively.93725.colors. Returns 0 if: vmin==vmax Works with scalars or arrays. Returns 0 if: vmin==vmax Works with scalars or arrays. 0. clip=False) Normalize a given value to the 0-1 range If vmin or vmax is not given. under. colors.y0.no_norm alias of NoNorm matplotlib. Alternatively.colors 583 . and y1 is the value to be used for x > than that given).colors.1.0.rgb2hex(rgb) Given an rgb or rgba sequence of 0-1 floats. Release 1. Values between the given mapping points are determined by simple linear interpolation. data can be a function mapping values between 0 . The two values of y are to allow for discontinuous mapping functions (say as might be found in a sawtooth) where y0 represents the value of y for values of x <= to that given.1 to 0 . The list must start with x=0. matplotlib.1 data represented by a list of x. and all values of x must be in increasing order.1. The function returns an array “result” where result[x*(N-1)] gives the closest value for values of x between 0 and 1. end with x=1.normalize alias of Normalize matplotlib.rgb_to_hsv(arr) convert rgb values in a numpy array to hsv values input and output arrays should have shape (M.N.y1 mapping correspondences.Matplotlib. return the hex string matplotlib.3) 42. matplotlib. Each element in this list represents how a value between 0 and 1 (inclusive) represented by x is mapped to a corresponding value between 0 and 1 (inclusive).colors.colors. Release 1.Matplotlib. matplotlib colors .1 584 Chapter 42.0. dates Matplotlib provides sophisticated date plotting capabilities.toordinal() .1. the add-on modules pytz and dateutils. and calendar differences can cause confusing differences between what Python and mpl give as the number of days since 0001-01-01 and what other software and databases yield. standing on the shoulders of python datetime.date(1. 1582. plus 1.1).1). using their calculator.toordinal() Out[31]:732401 585 . Note: Like Python’s datetime. mpl uses the Gregorian calendar for all conversions between dates and floating point numbers. The helper functions date2num(). the number of days between 0001-01-01 and 2006-04-01 is 732403.CHAPTER FORTYTHREE MATPLOTLIB DATES strpdate2num ConversionInterface DateConverter IndexDateFormatter tzinfo _UTC DateFormatter W eekdayLocator rrulewrapper Formatter HourLocator AutoDateFormatter Y earLocator SecondLocator TickHelper Locator DateLocator RRuleLocator MonthLocator AutoDateLocator MinuteLocator DayLocator 43. num2date() and drange() are used to facilitate easy conversion to and from datetime and numeric ranges.25.1 matplotlib. For example. This practice is not universal.4. whereas using the Gregorian calendar via the datetime module we find: In [31]:date(2006. 0001-01-01. For example.25. not 0. 06:00 is 1. the US Naval Observatory uses a calendar that switches from Julian to Gregorian in October. Hence. datetime objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC. The rrulewrapper is a simple wrapper around a dateutils. and any custom date tickers or locators you create.dates. 586 Chapter 43. All the matplotlib date converters. Release 1. plot_date(). For example: # tick on mondays every week loc = WeekdayLocator(byweekday=MO.1. These are described below. the default from your rc file will be assumed.ticker for general information on tick locators and formatters. making it easy to place ticks on any kinds of dates. 43. See matplotlib. See examples below. See rrule example. interval=2) The rrule locator allows completely general date ticking: # tick every 5th easter rule = rrulewrapper(YEARLY. matplotlib dates .1 A wide range of specific and general purpose date tick locators and formatters are provided in this module.0. eg 7 for july • YearLocator: locate years that are multiples of base • RRuleLocator: locate using a matplotlib. If you leave out a tz timezone instance. TU • MonthLocator: locate months. interval=5) loc = RRuleLocator(rule) Here are all the date tickers: • MinuteLocator: locate minutes • HourLocator: locate hours • DayLocator: locate specifed days of the month • WeekdayLocator: Locate days of the week. SA)) In addition. eg MO. • AutoDateLocator: On autoscale. and the default timezone is given by the timezone parameter in your matplotlibrc file. tickers and formatters are timezone aware.1 Date tickers Most of the date tickers can locate single or multiple values.rrulewrapper. If you want to use a custom time zone. pass a pytz. The dateutil module provides additional code to handle date ticking. this class picks the best MultipleDateLocator to set the view limits and the tick locations. most of the constructors take an interval argument: # tick on mondays every second week loc = WeekdayLocator(byweekday=MO.Matplotlib. tz=tz) # tick on mondays and saturdays loc = WeekdayLocator(byweekday=(MO. byeaster=1.timezone instance with the tz keyword argument to num2date().rrule (dateutil) which allow almost arbitrary date tick specifications. See pytz for information on pytz and timezone handling. num2date(x. note that the Gregorian calendar is assumed. this is not universal practice. Use a strftime() format string.2 Date formatters Here all all the date formatters: • AutoDateFormatter: attempts to figure out the best format to use. Also.timedelta instance.dates.dates. note that the Gregorian calendar is assumed. For details. matplotlib.epoch2num(e) Convert an epoch or sequence of epochs to the new date format. Return value is a datetime instance in timezone tz (default to rcparams TZ value). Thanks to Andrew Dalke. d can be a number or sequence. see the module docstring.DateFormatter(fmt. tz=None) x is a float value which gives the number of days (fraction part represents hours.drange(dstart. matplotlib. that is days since 0001. fmt) 43.num2epoch(d) Convert days since 0001 to epoch. Also. Return value is a floating point number (or sequence of floats) which gives the number of days (fraction part represents hours.dates.1 43.dates. If x is a sequence. Dalke Scientific Software who contributed the strftime() code below to include dates earlier than this year. tz=None) Bases: matplotlib. matplotlib. dend. Release 1.dates.ticker. matplotlib.mx2num(mxdates) Convert mx datetime instance (or sequence of mx instances) to the new date format. seconds) since 0001-01-01 00:00:00 UTC plus one. This is most useful when used with the AutoDateLocator.dates. a sequence of datetime objects will be returned. this is not universal practice. set_tzinfo(tz) strftime(dt. tz is the tzinfo instance.Formatter Tick location is seconds since the epoch. minutes. class matplotlib.dates 587 . dstart and dend are datetime instances. seconds) since 0001-01-01 00:00:00 UTC. Python only supports datetime strftime() formatting for years greater than 1900. matplotlib. The addition of one here is a historical artifact. minutes. fmt is an strftime() format string. delta is a datetime. matplotlib. delta) Return a date range as float Gregorian ordinals.0.date2num(d) d is either a datetime instance or a sequence of datetimes. matplotlib. plus one.dates.1.Matplotlib. The addition of one here is a historical artifact.1. • DateFormatter: use strftime() format strings • IndexDateFormatter: date plots with implicit x indexing. see the module docstring. For details. dates. The algorithm picks the key in the dictionary that is >= the current scale and uses that format string. matplotlib dates . class matplotlib.ticker. 588 Chapter 43. vmax) set_tzinfo(tz) viewlim_to_dt() class matplotlib.)] = ’%M:%S’ # only show min and sec Autofmt the date labels.Formatter Use with IndexLocator to cycle format strings by index. datalim_to_dt() nonsingular(vmin. tz=None) Bases: matplotlib.0 : 30. ’%b %Y’. val_multiples=False) Bases: matplotlib. inter- On autoscale. static get_unit_generic(freq) class matplotlib. this class picks the best MultipleDateLocator to set the view limits and the tick locations.dates.dates.DateLocator autoscale() Set the view limits to include the data range. : } = { ’%Y’. tz=None) Bases: matplotlib.1 class matplotlib.scaled[1/(24. The default looks like this: self.AutoDateFormatter(locator.AutoDateLocator(tz=None. tz=None. ’%H:%M:%D’.dates. The default format is the one to use if none of the times in scaled match class matplotlib.0.IndexDateFormatter(t. fmt.Locator tz is a tzinfo instance. You can customize this dictionary by doing: formatter = AutoDateFormatter() formatter. : 1. fmt is a strftime() format string.scaled 365.DateLocator(tz=None) Bases: matplotlib. This is most useful when used with the AutoDateLocator./24. The AutoDateFormatter has a scale dictionary that maps the scale of the tick (the distance in days between one major tick) and a format string.RRuleLocator(o.ticker.ticker. t is a sequence of dates (floating point days). minticks=5.dates. defaultfmt=’%Y-%m-%d’) Bases: matplotlib.0 : 1.dates.Formatter This class attempts to figure out the best format to use.Matplotlib.dates. Release 1.*60. ’%b %d %Y’.DateLocator maxticks=None. 5.dates 589 . Release 1. interval_multiples is a boolean that indicates whether ticks should be chosen to be multiple of the interval. 10. which controls any interval between ticks (ticking every other. 15 or 30 make sense. dmax) Pick the best locator based on a distance. every 3. MONTHLY. DAILY : [1. month=1. The AutoDateLocator has an interval dictionary that maps the frequency of the tick (a constant from dateutil. get_locator(dmin. This can be used to keep the number of ticks appropriate to the format chosen in class:AutoDateFormatter. maxticks is the maximum number of ticks desired. The default looks like this: self. 30] The interval is used to specify multiples that are appropriate for the frequency of ticking. every 7 days is sensible for daily ticks. 5.12. 3. You can customize this dictionary by doing: locator = AutoDateLocator() locator. tz=None) Bases: matplotlib.1. refresh() Refresh internal information based on current limits. 2. 2.dates. etc. but for minutes/seconds. etc. SECONDLY: [1. MONTHLY : [1. day=1. For really fine-grained control. 6].YearLocator(base=1. 3. 2. 4. 12].dates.6. 14]. tz is a tzinfo instance. this can be a dictionary mapping individual rrule frequency constants (YEARLY.intervald[HOURLY] = [3] # only show every 3 hours autoscale() Try to choose the view limits intelligently. 5.Matplotlib. set_axis(axis) class matplotlib. MINUTELY: [1. this will force the ticks to be at hours 0. 15. For instance. This will lock ticks to ‘nicer’ locations. 7. 2. monthly. 6. HOURLY : [1. 10].). For example. Examples: # Tick every year on Jan 1st locator = YearLocator() 43.18 when hourly ticking is done at 6 hour intervals.1 minticks is the minimum number of ticks desired. 15.0. Any frequency not specified in this dictionary is given a default value. which is used to select the type of ticking (yearly.rrule) and a multiple allowed for that ticking.intervald = { YEARLY : [1. 4. } 4.). 30].DateLocator Make ticks on a given day of each year that is a multiple of base. etc. 10. matplotlib.) to their own maximum number of ticks. 3. interval=1. WE. 12. Default is to tick every day of the month: bymonthday=range(1. 3. interval=1.dates. Release 1.RRuleLocator Make ticks on occurances of each hour. Elements of byweekday must be one of MO. if interval=2. byhour can be an int or sequence. 15. day=4) Mark years that are multiple of base on a given month and day (default jan 1).dates. Default is to tick every hour: byhour=range(24) interval is the interval between each iteration. TH. SA. matplotlib dates . tz=None) Bases: matplotlib. TU. i. month=7.DayLocator(bymonthday=None.dates. 1.dates.13). tz=None) Bases: matplotlib. Default is range(1.MinuteLocator(byminute=None. class matplotlib.dates. every month. 30. interval specifies the number of weeks to skip.RRuleLocator Make ticks on occurances of each month month. Mark every minute in byminute.MonthLocator(bymonth=None. For example. interval is the interval between each iteration. interval=2 plots every second week. interval=1.RRuleLocator Make ticks on occurances of each day of the month. For example. bymonth can be an int or sequence.RRuleLocator Make ticks on occurances of each minute. byweekday can be a number or sequence. SU. byminute can be an int or sequence. tz=None) Bases: matplotlib. class matplotlib. mark every second occurance.WeekdayLocator(byweekday=1.HourLocator(byhour=None. bymonthday can be an int or sequence.dates.dates. Mark every hour in byhour. For example. tz=None) Bases: matplotlib.1 # Tick every 5 years on July 4th locator = YearLocator(5. For example. if interval=2.0.dates. class matplotlib. class matplotlib. Mark every month in bymonth.e.dates. the constants from dateutils. tz=None) Bases: matplotlib.rrule. interval=1. autoscale() Set the view limits to include the data range. Mark every weekday in byweekday. FR.dates. interval=1. Default is to tick every minute: byminute=range(60) 590 Chapter 43. eg 1. bymonthday=1.32) class matplotlib. mark every second occurrence.Matplotlib. Mark every day in bymonthday.RRuleLocator Make ticks on occurances of each weekday. Default is to tick every second: bysecond = range(60) interval is the interval between each iteration. day=None. interval=1. month=None. years=0. microseconds: Relative mation. weeks=0. class matplotlib. dt2=None. dtstart=None. byhour=None. seconds=0. month. bymonthday=None. matplotlib. You can also use an integer. These instances may receive a parameter N. weeks. byminute=None. second. until=None. Not specifying it is the same as specifying +1.dates.rrule. hours. The first one is passing it two date/datetime classes: relativedelta(datetime1. minutes=0. may be negative. Here is the behavior of operations with relativedelta: 43. yearday. day.1 interval is the interval between each iteration. bysecond=None. Mark every second in bysecond.rrule(freq. cache=False) Bases: dateutil. For example.dates.1. Lemburg in his mx. days=0. year=None. Do NOT expect it to behave like mx. datetime2) And the other way is to use the following keyword arguments: year. hours=0. mark every second occurrence. hour=None. microsecond: Absolute information. if year is a leap year. if interval=2.0. bysecond can be an int or sequence. byweekno=None. For example. seconds. microsecond=None) The relativedelta type is based on the specification of the excelent work done by M. yearday=None.SecondLocator(bysecond=None. nlyearday: Set the yearday or the non-leap year day (jump leap days). leapdays: Will add given days to the date found. hour. and the date found is post 28 of february. where 0=MO. minute=None. Release 1. months. if interval=2. These are converted to day/month/leapdays information. bymonth=None.-A. wkst=None.Matplotlib. byeaster=None. minutes.RRuleLocator Make ticks on occurances of each second. minute. notice that this type does NOT implement the same algorithm as his work.rrulebase class matplotlib. specifying the Nth weekday.relativedelta(dt1=None. class matplotlib. TU. There’s two different ways to build a relativedelta instance. weekday=None.dates.dates 591 . infor- weekday: One of the weekday instances (MO. tz=None) Bases: matplotlib. etc). However. days. which could be positive or negative (like MO(+1) or MO(-2).DateTime’s counterpart. interval=1. months=0. bysetpos=None. nlyearday=None. byweekday=None.dates. years. mark every second occurrence. byyearday=None. second=None. microseconds=0. leapdays=0. count=None.DateTime extension. if the argument is not present. 3. Notice that the ‘weeks’ argument is multiplied by 7 and added to ‘days’.Calculate the absolute year.Matplotlib.1 1.Do steps 1 and 2 for month/months. with the given (wday.Add the relative ‘years’ argument to the absolute year.minutes(m) Return minutes as days. using the ‘day’ argument. Release 1. 7. matplotlib. second/seconds.Do steps 1 and 2 for hour/hours.dates. -1) won’t change the day. and nth is the number of weeks to add forward or backward. or the original datetime year.dates.weeks(w) Return weeks as days. 4. Notice that if the calculated date is already Monday. for example.Add the relative ‘days’ argument to the absolute day. minute/minutes. wday is the index of the weekday (0-6. using (0.If the ‘weekday’ argument is present. 2. or the original datetime day. depending on its signal. 0=Mon). Then.dates. matplotlib. if the argument is not present. microsecond/microseconds.hours(h) Return hours as days. matplotlib. subtract from the day until it fits in the year and month found after their operations. using the ‘year’ argument. 1) or (0. nth) tuple.dates. 5. 592 Chapter 43.seconds(s) Return seconds as days. calculate the weekday.Calculate the absolute day. matplotlib dates . 6. matplotlib.0. facecolor=None. The figure patch is drawn by a the attribute patch a matplotlib. frameon=True. the default linewidth of the frame frameon if False.Figure(figsize=None.CHAPTER FORTYFOUR MATPLOTLIB FIGURE 44. and the callback will be called with func(fig) where fig is the Figure instance. edgecolor=None. **kwargs) Add an a axes with axes rect [left. height] where all quantities are in fractions of 593 . this will override the renderer figsize w.h tuple in inches dpi dots per inch facecolor the figure patch facecolor. subplotpars=None) Bases: matplotlib. The following classes are defined SubplotParams control the default spacing of the subplots Figure top level container for all plot elements class matplotlib.cbook. suppress drawing the figure frame subplotpars a SubplotParams instance.CallbackRegistry instance. defaults to rc figure. which contains all the plot elements. defaults to rc figure.edgecolor linewidth the figure patch edge linewidth. The events you can connect to are ‘dpi_changed’.patches. linewidth=1.Artist The Figure instance supports callbacks through a callbacks attribute which is a matplotlib. width.artist.0.1 matplotlib. bottom. defaults to rc add_axes(*args. the figure will make composite images depending on the renderer option_image_nocomposite function.figure.facecolor edgecolor the figure patch edge color. If suppressComposite is True|False.figure The figure module provides the top-level Artist.Rectangle instance suppressComposite for multiple figure images. dpi=None. the Figure. make sure you give them unique labels: fig.. you must use a unique set of args and kwargs. ‘hammer’. ‘mollweide’. eg. The following kwargs are supported: Property adjustable agg_filter alpha anchor animated aspect autoscale_on autoscalex_on autoscaley_on axes axes_locator axis_bgcolor axis_off axis_on axisbelow clip_box clip_on clip_path color_cycle contains cursor_props figure Description [ ‘box’ | ‘datalim’ | ‘box-forced’] unknown float (0.add_axes(rect.0 transparent through 1. fig. Transform) | Patch | None ] unknown a callable function a (float. Release 1.0 opaque) unknown [True | False] unknown unknown unknown unknown an Axes instance unknown any matplotlib color . Eg.add_axes(rect. Some of these projections support additional kwargs.add_axes(rect) fig.see colors() unknown unknown [ True | False ] a matplotlib. fig. label=’axes1’) fig. ‘lambert’. you want to force the creation of a new axes. ‘rectilinear’].w. fig.Bbox instance [True | False] [ (Path. (For backward compatibility. kwargs are legal Axes kwargs plus projection which sets the projection type of the axes. polar=True may also be provided.add_axes(rect.h fig. color) tuple unknown Continued on next page Chapter 44.add_axes(rect. which may be provided to add_axes(): rect = l.0. If you do not want this behavior.transforms. The axes label attribute has been exposed for this purpose. then it will simply make that axes current and return it. axisbg=’g’) polar=True) projection=’polar’) # add an Axes instance If the figure already has an axes with the same parameters. label=’axes2’) The Axes instance will be returned. if you want two axes that are otherwise identical to be added to the figure. Valid values for projection are: [’aitoff’.b. matplotlib figure 594 .Matplotlib.1 figure width and height. ‘polar’.add_axes(rect.add_axes(ax) frameon=False. which is equivalent to projection=’polar’). ‘polar’.figure 595 .1. which chooses a projection type for the axes. ‘hammer’. Examples: fig.add_subplot(111.add_subplot(212.add_subplot(111) fig. which is equivalent to projection=’polar’).1.1 – continued from previous page frame_on [ True | False ] gid an id string label any string lod [True | False] navigate [ True | False ] navigate_mode unknown picker [None|float|boolean|callable] position unknown rasterization_zorder unknown rasterized [True | False | None] snap unknown title str transform Transform instance url a url string visible [True | False] xbound unknown xlabel str xlim len(2) sequence of floats xmargin unknown xscale [’linear’ | ‘log’ | ‘symlog’] xticklabels sequence of strings xticks sequence of floats ybound unknown ylabel str ylim len(2) sequence of floats ymargin unknown yscale [’linear’ | ‘log’ | ‘symlog’] yticklabels sequence of strings yticks sequence of floats zorder any number add_axobserver(func) whenever the axes state change. **kwargs) Add a subplot. polar=True may also be provided. Some of these projections support additional kwargs.add_subplot(1. polar=True) # add a polar subplot fig. Valid values for projection are: [’aitoff’.add_subplot(sub) # add Subplot instance sub kwargs are legal matplotlib.0.Axes kwargs plus projection. func(self) will be called add_subplot(*args.Matplotlib. ‘rectilinear’]. which 44. ‘lambert’. matplotlib. Release 1. (For backward compatibility.1) # equivalent but more general fig.1 Table 44. axisbg=’r’) # add subplot with red background fig.axes. ‘mollweide’. Release 1.0 transparent through 1. The Axes instance will be returned. If the figure already has a subplot with key (args.0 opaque) unknown [True | False] unknown unknown unknown unknown an Axes instance unknown any matplotlib color .see colors() unknown unknown [ True | False ] a matplotlib. color) tuple unknown [ True | False ] an id string any string [True | False] [ True | False ] unknown [None|float|boolean|callable] unknown unknown [True | False | None] unknown str Transform instance a url string [True | False] unknown Continued on next page Chapter 44. matplotlib figure 596 .1 may be provided to add_axes().Matplotlib.0. The following kwargs are supported: Property adjustable agg_filter alpha anchor animated aspect autoscale_on autoscalex_on autoscaley_on axes axes_locator axis_bgcolor axis_off axis_on axisbelow clip_box clip_on clip_path color_cycle contains cursor_props figure frame_on gid label lod navigate navigate_mode picker position rasterization_zorder rasterized snap title transform url visible xbound Description [ ‘box’ | ‘datalim’ | ‘box-forced’] unknown float (0. kwargs) then it will simply make that subplot current and return it. Transform) | Patch | None ] unknown a callable function a (float.Bbox instance [True | False] [ (Path.transforms. 1 Table 44. Set keep_observers to True if. **kw) Create a colorbar for a ScalarMappable instance. a gui widget is tracking the axes in the figure. Release 1.2 – continued from previous page xlabel str xlim len(2) sequence of floats xmargin unknown xscale [’linear’ | ‘log’ | ‘symlog’] xticklabels sequence of strings xticks sequence of floats ybound unknown ylabel str ylim len(2) sequence of floats ymargin unknown yscale [’linear’ | ‘log’ | ‘symlog’] yticklabels sequence of strings yticks sequence of floats zorder any number autofmt_xdate(bottom=0. all but the first are also method signatures for the colorbar() method: colorbar(**kwargs) colorbar(mappable. cax=cax. **kwargs) arguments: 44. cax=None.0. ax=None. bottom the bottom of the subplots for subplots_adjust() rotation the rotation of the xtick labels ha the horizontal alignment of the xticklabels clear() Clear the figure – synonym for fig. a common use case is a number of subplots with shared xaxes where the x-axis is date data. **kwargs) colorbar(mappable. ax=ax. colorbar(mappable. **kwargs) colorbar(mappable.20000000000000001.1. so it is useful to rotate them and right align them. matplotlib. The ticklabels are often long. Function signatures for the pyplot interface. rotation=30.figure 597 . as well as turn off xlabels.clf clf(keep_observers=False) Clear the figure. and it helps to rotate them on the bottom subplot and turn them off on other subplots. ha=’right’) Date ticklabels often overlap. Also.Matplotlib. for example. Documentation for the pylab thin wrapper: Add a colorbar to a plot. g. fraction of original axes to use for colorbar 0. 598 Chapter 44.Description erty ex[ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] If not ‘neither’.[ None | format string | Formatter object ] If None. ratio of long to short dimensions colorbar properties: Prop.range values. drawedges [ False | True ] If true. the mat ScalarFormatter is used. to which the colorbar applies.15 if horizontal. Release 1.[ ‘uniform’ | ‘proportional’ ] Uniform spacing gives each discrete ing color the same space.Matplotlib. If a format string is given. ContourSet.0. The following will probably be useful only in the context of indexed colors (that is. that is used.05 if vertical. spac. ticks [ None | list of ticks | Locator object ] If None. when the mappable has norm=NoNorm()). e. or other unusual circumstances.3f’. An alternative Formatter object may be given instead. proportional makes the space proportional to the data interval. which sets the default to the current image. ‘%.0. fraction of original axes between colorbar and new image axes 1.15. keyword arguments: cax None | axes object into which the colorbar will be drawn ax None | parent axes object from which space for a new colorbar axes will be stolen Additional keyword arguments are of two kinds: axes properties: Property orientation fraction pad shrink aspect Description vertical or horizontal 0. etc. this argument is mandatory for the colorbar() method but optional for the colorbar() function. ticks are determined automatically from the input.1 mappable the Image. fraction by which to shrink the colorbar 20. make pointed tend end(s) for out-of. 0. for. These are set for a given colormap using the colormap set_under and set_over methods. matplotlib figure . draw lines at color boundaries. None or a sequence which must be of length 1 less than the ues sequence of boundaries. For more precise control. yo) with pixel offsets xo.{} delaxes(a) remove a from the figure and update the current axes dpi draw(artist.Matplotlib. but it is a manual method requiring some trial and error. yo. figimage(X. *args. origin=None.None or a sequence aries val.1. Release 1. vmin=None. Note that the shrink kwarg provides a simple way to keep a vertical colorbar. For each region delimited by adjacent entries in boundaries. from being taller than the axes of the mappable to which the colorbar is attached. its extend kwarg is included automatically. **kwargs) adds a non-resampled array X to the figure. **kwargs) call signatures: figimage(X. ColorbarBase. norm=None. cmap=None.RendererBase instance renderer draw_artist(a) draw matplotlib. do not use any of the axes properties kwargs. the color mapped to the corresponding value in values will be used. **kwargs) Render the figure using matplotlib. xo. returns: Colorbar instance. If the colorbar is too tall (or a horizontal colorbar is too wide) use a smaller value of shrink.artist. matplotlib. vmax=None. you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn.backend_bases. yo=0. xo=0. for example. contains(mouseevent) Test whether the mouse event occurred on the figure. If mappable is a ContourSet. renderer. see also its base class.1 Prop. alpha=None. Returns True.figure 599 .Description erty bound. In this case.Artist instance a only – this is available only after the figure is drawn figimage(X. X must be a float array: •If X is MxN. assume luminance (grayscale) •If X is MxNx3.0. Call the set_label() method to label the colorbar. assume RGB 44. see colors() unknown unknown [ True | False ] Continued on next page 600 Chapter 44. If None. default to the rc image.0 opaque) unknown [True | False] unknown unknown unknown unknown an Axes instance unknown any matplotlib color .0.0.image.FigureImage instance is returned.1]. If either is None. An matplotlib. althe alpha blending value. If you want a resampled image to fill the entire figure.0 transparent through 1. Release 1. Additional kwargs are Artist kwargs passed on to FigureImage gca(**kwargs) Return the current axes. Note if you pass a norm instance.colors. assume RGBA Optional keyword arguments: Keyword xo or yo cmap Description An integer. Defaults to the rc image.jet.cmap value norm a matplotlib. eg cm.origin value figimage complements the axes image (imshow()) which will be resampled to fit the current axes. the x and y image offset in pixels a matplotlib. matplotlib figure . the settings for vmin and vmax will be ignored. you can define an Axes with size [0. This scales luminance -> 0-1 vmin|vmax used to scale a luminance image to 0-1.0] index of the array is in the gin upper left or lower left corner of the axes. creating one if necessary The following kwargs are supported Property adjustable agg_filter alpha anchor animated aspect autoscale_on autoscalex_on autoscaley_on axes axes_locator axis_bgcolor axis_off axis_on axisbelow Description [ ‘box’ | ‘datalim’ | ‘box-forced’] unknown float (0. The default is normalization(). default is None pha ori[ ‘upper’ | ‘lower’ ] Indicates where the [0.Normalize instance.ColorMap instance.cm.1. the min and are max of the luminance values will be used.1 •If X is MxNx4.Matplotlib. 1 Table 44. Transform) | Patch | None ] color_cycle unknown contains a callable function cursor_props a (float.1.transforms. Release 1.Bbox instance clip_on [True | False] clip_path [ (Path.3 – continued from previous page clip_box a matplotlib.Matplotlib.0. matplotlib. color) tuple figure unknown frame_on [ True | False ] gid an id string label any string lod [True | False] navigate [ True | False ] navigate_mode unknown picker [None|float|boolean|callable] position unknown rasterization_zorder unknown rasterized [True | False | None] snap unknown title str transform Transform instance url a url string visible [True | False] xbound unknown xlabel str xlim len(2) sequence of floats xmargin unknown xscale [’linear’ | ‘log’ | ‘symlog’] xticklabels sequence of strings xticks sequence of floats ybound unknown ylabel str ylim len(2) sequence of floats ymargin unknown yscale [’linear’ | ‘log’ | ‘symlog’] yticklabels sequence of strings yticks sequence of floats zorder any number get_axes() get_children() get a list of artists contained in the figure get_dpi() Return the dpi as a float 44.figure 601 . mouse_pop=3.1 get_edgecolor() Get the edge color of the Figure rectangle get_facecolor() Get the face color of the Figure rectangle get_figheight() Return the figheight as a float get_figwidth() Return the figwidth as a float get_frameon() get the boolean indicating frameon get_size_inches() get_tightbbox(renderer) Return a (tight) bounding box of the figure in inches. It only accounts axes title. axis labels. kwargs are void ginput(n=1. and axis ticklabels.0. Release 1. get_window_extent(*args.Matplotlib. show_clicks=True. mouse_add=1. mouse_stop=2) call signature: 602 Chapter 44. **kwargs) get the figure bounding box in display space. Needs improvement. matplotlib figure . timeout=30. toggle the hold state.figure 603 . does not timeout. timeout=30. Right clicking cancels last input. n=1. terminating the inputs) can be overriden via the arguments mouse_add. mouse_add=1. ’label2’. hold(b=None) Set the hold state. and loc can be a string or an integer specifying the legend location USAGE: legend( (line1. the enter key terminates input and any other key (not already used by the window manager) selects a point. remove last point).. The buttons used for the various actions (adding points.0. labels. Eg: hold() # toggle hold hold(True) # hold is on hold(False) # hold is off legend(handles. line2.1. ’upper right’) The loc location codes are: ’best’ : 0. Release 1. The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. that give the associated mouse button: 1 for left. show_clicks=True. **kwargs) Place a legend in the figure. handles is a sequence of Line2D or Patch instances. 3.1 ginput(self. 44. 2. matplotlib. 7. Labels are a sequence of strings. If timeout is zero or negative. removing points. ’upper right’ ’upper left’ ’lower left’ ’lower right’ ’right’ ’center left’ ’center right’ ’lower center’ (currently not supported for figure legends) : : : : : : : : 1. 3 for right. 5. mouse_pop=3. mouse_pop and mouse_stop. If hold is None (default). 4. 8.Matplotlib. accumulate clicks until a middle click (or potentially both mouse buttons at once) terminates the input. This will wait for n clicks from the user and return a list of the coordinates of each click. Else set the hold state to boolean value b.e. *args. ’label3’). 2 for middle. line3). mouse_stop=2) Blocking call to interact with the figure. (’label1’. 6. The delete and backspace keys act like right clicking (i. If n is zero or negative. default is 4 scatterpoints: integer The number of points in the legend line. ’center’ : 10. edgecolor=’w’.1 ’upper center’ : 9. If None. transparent=False. original. use rc settings. figure coords are (0. dpi=None. ncol [integer] number of columns. Keyword borderpad labelspacing handlelength handletextpad borderaxespad columnspacing Example: savefig(*args.1 is the right.font_manager. the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor) title [string] the legend title Padding and spacing between various elements use following keywords parameters. default is 1 mode [[ “expand” | None ]] if mode is “expand”. Release 1.FontProperties instance. papertype=None. loc can also be an (x. Keyword arguments: prop: [ None | FontProperties | dict ] A matplotlib. facecolor=’w’. **kwargs) call signature: savefig(fname. If None. pad_inches=0. orientation=’portrait’. 604 Chapter 44. fancybox: [ None | False | True ] if True.0) is the left. a new instance will be created with prop. The dimensions of these values are given as a fraction of the fontsize. draw a frame with a round fancybox. matplotlib figure . bbox_inches=None.Matplotlib. If None. top. use rc settings. If None. numpoints: integer The number of points in the legend line. draw a shadow behind legend.0. use rc settings. format=None. use rc shadow: [ None | False | True ] If True. Values from rcParams will be used if None. default is 4 scatteroffsets: list of floats a list of yoffsets for scatter symbols in legend markerscale: [ None | scalar ] The relative size of legend markers vs. If prop is a dictionary.1): Description the fractional whitespace inside the legend border the vertical space between the legend entries the length of the legend handles the pad between the legend handle and text the pad between the axes and legend border the spacing between columns Save the current figure. bottom of the figure and 1.y) tuple in figure coords. which specifies the lower left of the legend box. 5 1.0 0.5 2. facecolor.0 0. ‘executive’.0 0.0 Line 3 Line 4 1.1. If that value is ‘auto’.extension is used. Arguments: fname: A string containing a path to a filename. If fname is not a string.0 0.0 0. or a Python file-like object. or possibly some backend-dependent object such as PdfPages. edgecolor: the colors of the figure rectangle orientation: [ ‘landscape’ | ‘portrait’ ] not supported on all backends. Keyword arguments: dpi: [ None | scalar > 0 ] The resolution in dots per inch.Matplotlib.5 0. Release 1.dpi in the matplotlibrc file.figure 605 .5 1. remember to specify format to ensure that the correct backend is used. ‘b0’ through ‘b10’.0.0 The output formats available depend on the backend being used.0 1.1 Line 1 Line 2 1. If format is None and fname is a string.0 0. If None it will default to the value savefig.5 0. matplotlib.5 1. currently only on postscript output papertype: One of ‘letter’. the backend determines the extension. ‘a0’ through ‘a10’.5 1. Only supported for postscript output. the value of the rc parameter savefig.5 1. If the filename has no extension. ‘ledger’.0 0.0 0. the output format is deduced from the extension of the filename. 44. ‘legal’.0 2. eps and svg. bbox_extra_artists: A list of extra artists that will be considered when the tight bbox is calculated. Release 1. ps. transparent: If True. the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. If ‘tight’. The transparency of these patches will be restored to their original values upon exit of this function.1 format: One of the file extensions supported by the active backend. matplotlib figure . bbox_inches: Bbox in inches. pdf. pad_inches: Amount of padding around the figure when bbox_inches is ‘tight’. Only the given portion of the figure is saved.see help(colors) set_figheight(val) Set the height of the figure in inches ACCEPTS: float set_figwidth(val) Set the width of the figure in inches ACCEPTS: float set_frameon(b) Set whether the figure frame (background) is displayed or invisible ACCEPTS: boolean set_size_inches(*args. This is useful. try to figure out the tight bbox of the figure. sca(a) Set the current axes to be a and return a set_canvas(canvas) Set the canvas the contains the figure ACCEPTS: a FigureCanvas instance set_dpi(val) Set the dots-per-inch of the figure ACCEPTS: float set_edgecolor(color) Set the edge color of the Figure rectangle ACCEPTS: any matplotlib color .h. for example. **kwargs) set_size_inches(w. the axes patches will all be transparent.0. forward=False) 606 Chapter 44. Most backends support png.Matplotlib. for displaying a plot on top of a colored background on a web page.see help(colors) set_facecolor(color) Set the face color of the Figure rectangle ACCEPTS: any matplotlib color . set_size_inches((w. y. Release 1. fontdict=None.1 Set the figure size in inches Usage: fig. See text() for the meaning of the other arguments.set_size_inches(w. **kwargs) Call signature: figtext(x.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict 44. matplotlib.0 transparent through 1. **kwargs) fig. eg you can resize the figure window from the shell ACCEPTS: a w. top=None. kwargs control the Text properties: Property agg_filter alpha animated axes backgroundcolor bbox Description unknown float (0.Text instance is returned.h in inches subplots_adjust(*args.Matplotlib.text.Text properties. s. y. kwargs are matplotlib. Using figure coordinates. **kwargs) Add text to figure at location x. s.98 the y location of the text in figure coords •horizontalalignment = ‘center’ the horizontal alignment of the text •verticalalignment = ‘top’ the vertical alignment of the text A matplotlib.suptitle(’this is the figure title’. *args. right=None. **kwargs) Add a centered title to the figure.subplots_adjust(left=None.figure 607 .0. y (relative 0-1 coords).h) # OR fig.h) ) optional kwarg forward=True will cause the canvas size to be automatically updated. hspace=None) Update the SubplotParams with kwargs (defaulting to rc where None) and update the subplot locations suptitle(t. fontsize=12) text(x.1.h tuple with w. Example: fig.5 the x location of text in figure coords •y = 0.text. wspace=None. the defaults are: •x = 0. bottom=None. If timeout is negative.font_manager. 608 Chapter 44.Matplotlib.Bbox instance [True | False] [ (Path. matplotlib figure .1 Table 44. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number waitforbuttonpress(timeout=-1) call signature: waitforbuttonpress(self.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.figure.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. This will return True is a key was pressed. False if a mouse button was pressed and None if timeout was reached without either being pressed. Release 1. does not timeout.Figure instance a matplotlib.0. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.transforms.4 – continued from clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder a matplotlib. timeout=-1) Blocking call to interact with the figure. 0. If any kwarg is None.1. height in inches are returned. top=None. 0.figure.8.1.8]) ax. right=None. h = figaspect(2. **kwargs) # make a figure with the proper aspect for an array A = rand(5. if set. etc) update(left=None.8]) ax. 0. If arg is a number.h)) ax = fig. right=None. **kwargs) Thanks to Fernando Perez for this function 44. hspace=None) A class to hold the parameters for a subplot All dimensions are fraction of the figure width or height. 0. otherwise to rc matplotlib.1.2 the amount of width reserved for blank space between subplots hspace = 0.add_axes([0. matplotlib. Release 1.figaspect(arg) Create a figure with specified aspect ratio. All values default to their rc params The following attributes are available left = 0.9 the right side of the subplots of the figure bottom = 0.1 the bottom of the subplots of the figure top = 0. hspace=None) Update the current values.1.add_axes([0. use that aspect ratio. 0. 0.imshow(A.8. default to the current value. wspace=None. top=None.0.SubplotParams(left=None. wspace=None. If arg is an array. figaspect will determine the width and height for a figure that would fit array preserving aspect ratio.1. h = figaspect(A) fig = Figure(figsize=(w.figure.125 the left side of the subplots of the figure right = 0.) fig = Figure(figsize=(w.9 the top of the subplots of the figure wspace = 0. The figure width.figure 609 .3) w.h)) ax = fig. eg Example usage: # make a figure twice as tall as it is wide w.Matplotlib.imshow(A.1 class matplotlib. Be sure to create an axes with equal with and height. bottom=None. bottom=None.2 the amount of height reserved for white space between subplots validate make sure the params are in a legal state (left*<*right. Release 1.1 610 Chapter 44.0.Matplotlib. matplotlib figure . is specified. directory. Fontconfig has the advantage that it is the standard way to look up fonts on X11 platforms.font_manager. The FontManager also handles Adobe Font Metrics (AFM) font files for use by the PostScript backend. findfont() performs a nearest neighbor search. If no matches below a certain threshold are found. Each font is given a similarity score to the target font properties.1 matplotlib. name=’‘. class matplotlib. findfont(prop. style. weight=’normal’) On import. It is used when populating the font lookup dictionary. variant=’normal’. class matplotlib. managing. weight=’normal’.font_manager A module for finding.1 specifications.CHAPTER FORTYFIVE MATPLOTLIB FONT_MANAGER 45. Experimental support is included for using fontconfig on Unix variant platforms (Linux. Solaris). The first font with the highest score is returned. stretch=’normal’. This module provides a single FontManager instance that can be shared across backends and platforms. stretch. 611 . the FontManager singleton instance creates a list of TrueType fonts based on the font properties: name.font_manager. size=’medium’) Bases: object A class for storing Font properties. fallback_to_default=True. it is much more likely to be found. will only return fonts from the given directory (or subdirectory of that directory). OS X. directory=None. variant. the default font (usually Vera Sans) is returned. Level 1 (CSS1) font specification. The design is based on the W3C Cascading Style Sheet. fontext=’ttf’. weight. set the constant USE_FONTCONFIG in this file to True. To enable it. The findfont() function returns the best TrueType (TTF) font file in the local or system font path that matches the specified FontProperties instance. and size. and using fonts across platforms. The findfont() method does a nearest neighbor search to find the font that most closely matches the specification. rebuild_if_missing=True) Search the font list for the font that most closely matches the FontProperties prop. If no good enough match is found. style=’normal’.FontManager(size=None.FontEntry(fname=’‘. a default font is returned. Future versions may implement the Level 2 or 2. so if a font is installed. An exact match returns 0.Matplotlib. Level 1 documentation for a description of the font finding algorithm.0.1. normalized between 0. get_default_size() Return the default font size. variant2) Returns a match score between variant1 and variant2. Release 1. normalized so that the usual range of font sizes (6pt . An exact match returns 0. If fallback_to_default is True.0.0.0 and 1. stretch2) Returns a match score between stretch1 and stretch2. If size2 (the size specified in the font file) is ‘scalable’. will fallback to the default font family (usually “Bitstream Vera Sans” or “Helvetica”) if the first lookup hard-fails.1. score_family(families. A match between ‘italic’ and ‘oblique’ returns 0.0.0. score_style(style1. A match by generic font name will return 0. style2) Returns a match score between style1 and style2.0. score_size(size1. otherwise 1. The result is the absolute value of the difference between the CSS numeric values of stretch1 and stretch2. this function always returns 0. 612 Chapter 45. No match will return 1.0. An exact match anywhere in the list returns 0. score_weight(weight1. so subsequent lookups don’t have to perform the O(n) nearest neighbor search. since any font size can be generated.0 and 1. No match returns 1. weight2) Returns a match score between weight1 and weight2. the result is the absolute distance between size1 and size2. See the W3C Cascading Style Sheet. family2) Returns a match score between the list of font families in families and the font family name family2. score_stretch(stretch1. matplotlib font_manager . Otherwise.1 The result is cached.0. size2) Returns a match score between size1 and size2. get_default_weight() Return the default font weight.72pt) will lie between 0.0.0. score_variant(variant1. See the documentation on fontconfig patterns. •variant: Either ‘normal’ or ‘small-caps’.g. matplotlib. ‘bold’. In that case. ‘semibold’. ‘extra-condensed’. ‘xxlarge’ or an absolute font size. •stretch: A numeric value in the range 0-1000 or one of ‘ultra-condensed’. fname=None. Release 1.g.0. ‘x-small’. Note that matplotlib’s internal font manager and fontconfig use a different algorithm to lookup fonts. e. ‘x-large’. ‘expanded’. _init=None) Bases: object A class for storing and manipulating font properties. Level 1 font specification. weight=None. 12.ttf file. ‘black’ •size: Either an relative value of ‘xx-small’. ‘large’. The preferred usage of font sizes is to use the relative values. instead of absolute font sizes. 45. e. We are merely borrowing its pattern syntax for use here.font_manager. if it is the only argument provided. the actual font to be used will be looked up from the associated rcParam in matplotlibrc. ‘cursive’. 12 The default font property for TrueType fonts (as specified in the default matplotlibrc file) is: sans-serif. ‘small’. normal. ‘semi-condensed’. ‘condensed’. a font may be specified using an absolute path to a . ‘roman’.font_manager 613 . either ‘serif’.1. This class will also accept a fontconfig pattern. size=None.1 The result is the absolute value of the difference between the CSS numeric values of weight1 and weight2. Alternatively. The initial value is ‘normal’.g. ‘medium’. ‘fantasy’. ‘regular’. ‘extra bold’. ‘medium’. ‘light’. by using the fname kwarg. variant=None. ‘demibold’. ‘italic’ or ‘oblique’. Currently not implemented. normal. scalable. ‘large’. e. The six properties are: •family: A list of font names in decreasing order of priority. The font properties are those described in the W3C Cascading Style Sheet.FontProperties(family=None. class matplotlib. ‘normal’. ‘semi-expanded’. or ‘monospace’. update_fonts(filenames) Update the font dictionary with new font files. ‘sans-serif’.0. stretch=None.0 and 1. normal. normalized between 0. style=None. ‘heavy’.Matplotlib. ‘book’. normal. ‘demi’. This support does not require fontconfig to be installed. ‘extra-expanded’ or ‘ultra-expanded’ •weight: A numeric value in the range 0-1000 or one of ‘ultralight’. so the results of the same pattern may be different in matplotlib than in other applications that use fontconfig. •style: Either ‘normal’. set_default_weight(weight) Set the default font weight. ‘normal’. The items may include a generic font family name. This approach allows all text sizes to be made larger or smaller based on the font manager’s default font size. ‘extra bold’. get_file() Return the filename of the associated font. ‘book’. Values are: ‘normal’ or ‘small-caps’. all other properties will be ignored. We are merely borrowing its pattern syntax for use here. get_size() Return the font size. get_style() Return the font style. ‘demibold’. get_stretch() Return the font stretch or width. ‘expanded’. ‘italic’ or ‘oblique’. get_weight() Set the font weight. get_fontconfig_pattern() Get a fontconfig pattern suitable for looking up the font as specified with fontconfig’s fc-match utility. ‘extra-condensed’. ‘bold’.0. Options are: A numeric value in the range 0-1000 or one of ‘light’. matplotlib font_manager . ‘cursive’. set_fontconfig_pattern(pattern) Set the properties by parsing a fontconfig pattern. ‘black’ set_family(family) Change the font family. Options are: ‘ultra-condensed’. ‘semi-condensed’. See the documentation on fontconfig patterns. ‘normal’. ‘italic’ or ‘oblique’. In this case. See the documentation on fontconfig patterns. ‘sans-serif’. get_variant() Return the font variant. get_size_in_points() get_slant() Return the font style. This support does not require fontconfig to be installed or support for it to be enabled. ‘condensed’. ‘roman’. ‘regular’. ‘extra-expanded’. set_file(file) Set the filename of the fontfile to use. ‘ultraexpanded’. ‘semibold’. Release 1. or a real font name. ‘heavy’. 614 Chapter 45. Values are: ‘normal’. ‘semi-expanded’. Values are: ‘normal’. such as: ‘serif’.1 copy() Return a deep copy of self get_family() Return a list of font names that comprise the font family. ‘normal’. ‘fantasy’. ‘demi’. May be either an alias (generic name is CSS parlance). or ‘monospace’.Matplotlib. ‘medium’. get_name() Return the name of the font that best matches the font properties. matplotlib.OSXInstalledFonts(directory=None. ‘medium’. or a real font name. or ‘monospace’. set_slant(style) Set the font style. matplotlib.font_manager. A list of TrueType fonts are returned by default with AFM fonts as an option. such as: ‘serif’. ‘italic’ or ‘oblique’. ‘italic’ or ‘oblique’.0. The default is to create a list of TrueType fonts. ‘demibold’. matplotlib. ‘sans-serif’. ‘normal’.findSystemFonts(fontpaths=None.font_manager. We are merely borrowing its pattern syntax for use here. ‘book’. ‘medium’. matplotlib. ‘large’. font is a class:AFM instance. This is done by starting at the list of hardcoded paths in OSXFontDirectories and returning all nested directories within them. ‘roman’.font_manager. ‘fantasy’.1.Matplotlib. ‘semibold’. set_size(size) Set the font size. ‘regular’. ‘bold’. Values are: ‘normal’ or ‘small-caps’.font_manager 615 . ‘extra bold’. Values are: ‘normal’. ‘semi-condensed’. fontext=’ttf’) Search for fonts in the specified font paths.get_fontconfig_fonts(fontext=’ttf’) Grab a list of all the fonts that are being tracked by fontconfig by making a system call to fc-list. Either an relative value of ‘xx-small’.font_manager.g. ‘condensed’. Release 1. ‘extra-expanded’ or ‘ultraexpanded’.afmFontProperty(fontpath. matplotlib. ‘expanded’. ‘small’. ‘normal’. ‘x-large’. ‘xx-large’ or an absolute font size. fontext=’ttf’) A function to create a font lookup list. ‘black’ matplotlib. matplotlib. ‘extra-condensed’.createFontList(fontfiles. or a numeric value in the range 0-1000. e.font_manager. set_stretch(stretch) Set the font stretch or width. ‘semi-expanded’. set_name(family) Change the font family. 45. set_weight(weight) Set the font weight.ignores font suffix by default. as well as the list of fonts tracked by fontconfig if fontconfig is installed and available. set_variant(variant) Set the font variant. Values are: ‘normal’.font_manager. ‘heavy’.findfont(prop. ‘cursive’. ‘x-small’. If no paths are given.OSXFontDirectory() Return the system font directories for OS X. font) A function for populating a FontKey instance by extracting information from the AFM font file. set_style(style) Set the font style. May be either a numeric value in the range 0-1000 or one of ‘ultralight’. **kw) matplotlib. ‘light’. Options are: ‘ultra-condensed’. May be either an alias (generic name is CSS parlance). An AFM font list can optionally be created. fontext=’ttf’) Get list of font files on OS X . will use a standard set of system paths.1 This support does not require fontconfig to be installed or support for it to be enabled.font_manager. ‘demi’. 12. ‘w’)) but closes the file to prevent filehandle leakage. matplotlib.1 This is an easy way to grab all of the fonts the user wants to be made available to applications.font_manager.font_manager. font is a FT2Font instance. matplotlib.fontconfig_pattern A module for parsing and generating fontconfig patterns. See the fontconfig pattern specification for more information.load(open(filename. fontext=’ttf’) Search for fonts in the specified font directory.get_fontext_synonyms(fontext) Return a list of file extensions extensions that are synonyms for the given file extension fileext.font_manager.font_manager. ‘r’)) but closes the file to prevent filehandle leakage.font_manager. This is done by starting at the list of hardcoded paths in X11FontDirectories and returning all nested directories within them. 45. matplotlib. A list of TrueType font filenames are returned by default.pickle_dump(data.ttfdict_to_fnames(d) flatten a ttfdict to all the filenames it contains matplotlib. String values are converted to their corresponding numeric value.pickle_load(filename) Equivalent to pickle.font_manager. matplotlib font_manager . without needing knowing where all of them reside. or use the system directories if none given.is_opentype_cff_font(filename) Returns True if the given font is a Postscript Compact Font Format Font embedded in an OpenType wrapper. filename) Equivalent to pickle. Release 1.x11FontDirectory() Return the system font directories for X11.2 matplotlib.FontconfigPatternParser A simple pyparsing-based parser for fontconfig-style patterns. open(filename.0. $WINDIR/Fonts will be returned.dump(data. matplotlib. Used by the PostScript and PDF backends that can not subset these fonts. See the fontconfig pattern specification for more information. or AFM fonts if fontext == ‘afm’. This is looked up from the registry key: \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts If the key is not found. matplotlib.font_manager.weight_as_number(weight) Return the weight property as a numeric value.font_manager.font_manager. matplotlib.fontconfig_pattern.win32FontDirectory() Return the user-specified font directory for Win32.ttfFontProperty(font) A function for populating the FontKey by extracting information from the TrueType font file. matplotlib.win32InstalledFonts(directory=None.font_manager. matplotlib. 616 Chapter 45. class matplotlib.Matplotlib. matplotlib. fontconfig_pattern. matplotlib.family_unescape() sub(repl. Release 1. string[.generate_fontconfig_pattern(d) Given a dictionary of key/value pairs.value_unescape() sub(repl.fontconfig_pattern. generates a fontconfig pattern string.0. count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl. count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl.fontconfig_pattern. string[. count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl.fontconfig_pattern 617 .fontconfig_pattern. matplotlib. matplotlib. 45. string[. matplotlib.value_escape() sub(repl.Matplotlib.2. string[.1 parse(pattern) Parse the given fontconfig pattern and return a dictionary of key/value pairs useful for initializing a font_manager. matplotlib.family_escape() sub(repl. count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl.FontProperties object. matplotlib.fontconfig_pattern. Release 1.1 618 Chapter 45. matplotlib font_manager .0.Matplotlib. g. ncols..GridSpecBase(nrows. If any kwarg is None. top=None. The location of grid is determined by similar way as the SubplotParams.1 matplotlib. Optionally. The number of rows and number of columns of the grid need to be set. eg 2.gridspec.g.gridspec gridspec is a module which specifies the location of the subplot in the figure. default to the current value. wspace=None. etc. if set. SubplotSpec specifies the location of the subplot in the given GridSpec. right. class matplotlib. left.) can be tuned.. width_ratios=None) Bases: object height_ratios=None.CHAPTER FORTYSIX MATPLOTLIB GRIDSPEC 46. right=None. hspace=None. left=None. The number of rows and number of columns of the grid need to be set. bottom=None.gridspec.) can be tuned. ncols. the ratio of heights and widths of ros and columns can be specified. The default parameters are from rcParams unless a figure attribute is set. width_ratios=None. class matplotlib. GridSpec specifies the geometry of the grid that a subplot will be placed. A base class of GridSpec that specifies the geometry of the grid that a subplot will be placed.3 619 .gridspec.GridSpecBase A class that specifies the geometry of the grid that a subplot will be placed. right. height_ratios=None) Bases: matplotlib. Optionally. left. otherwise to rc. The number of rows and number of columns of the grid need to be set. update(**kwargs) Update the current values. the subplot layout parameters (e.GridSpec(nrows. get_geometry() get the geometry of the grid. Optionally. the subplot layout parameters (e. get_subplot_params(fig=None) return a dictionary of subplot layout parameters. etc. An instance of SubplotSpec is also needed to be set from which the layout parameters will be inheirted. The number of rows and number of columns of the grid need to be set. The index stars from 0. subplot_spec. set_height_ratios(height_ratios) set_width_ratios(width_ratios) class matplotlib. left and right positions of columns. Release 1.3. width_ratios=None) Bases: matplotlib. num1. index is 0-based get_gridspec() get_position(fig. matplotlib gridspec . ncols. Unlike SuplorParams. num2=None) Bases: object specifies the location of the subplot in the given GridSpec. eg 2. wspace=None. return_all=False) update the subplot position from fig. hspace=None.Matplotlib. The subplot will occupy the num1-th cell of the given gridspec. If num2 is provided.SubplotSpec(gridspec. rowspan=1.gridspec. colspan=1) create and return a SuplotSpec instance.1 get_grid_positions(fig) return lists of bottom and top position of rows.subplotpars 620 Chapter 46. height_ratios=None. get_subplot_params(fig=None) return a dictionary of subplot layout parameters. the subplot will span between num1-th cell and num2-th cell. get_height_ratios() get_subplot_params(fig=None) get_width_ratios() new_subplotspec(loc. class matplotlib.GridSpecBase GridSpec whose subplot layout parameters are inherited from the location specified by a given SubplotSpec.GridSpecFromSubplotSpec(nrows.gridspec.0.gridspec. get_geometry() get the subplot geometry. The wspace and hspace of the layout can be optionally specified or the default values (from the figure or rcParams) will be used.2. 621 . matplotlib mathtext .0.Matplotlib.1 CHAPTER FORTYSEVEN MATPLOTLIB MATHTEXT Ship GlueSpec MathT extW arning Parser MathT extParser T ruetypeFonts Fonts StandardPsFonts UnicodeFonts StixFonts StixSansFonts BakomaFonts MathtextBackendPs MathtextBackendAggRender MathtextBackendBitmapRender MathtextBackendPath MathtextBackend MathtextBackendCairo NegFil MathtextBackendPdf SsGlue MathtextBackendSvg NegFill MathtextBackendBbox NegFilll Glue Fil Filll Fill Hrule AutoHeightChar Rule Vrule SubSuperCluster List Box Node Char Vbox Kern Accent Hbox Hlist AutoWidthChar Vlist HCentered VCentered 622 Chapter 47. Release 1. mathtext. Release 1. width. state.1 matplotlib. If you find TeX expressions that don’t parse or render properly. otherwise this will always just return a scaled version of the glyph.1. **kwargs) Bases: matplotlib. y) Render the character to the canvas.mathtext.Char’>) Bases: matplotlib. The Bakoma distribution of the TeX Computer Modern fonts.Matplotlib. sym) 47. The module uses pyparsing to parse the TeX expression. grow() render(x. There is experimental support for using arbitrary fonts.mathtext 623 .mathtext. the correct glyph will be selected. class matplotlib.Char The font metrics need to be dealt with differently for accents.AutoHeightChar(c. matplotlib.0. Symbols are strewn about a number of font files.edu.mathtext.mathtext.mathtext. but results may vary without proper tweaking and metrics for those fonts.TruetypeFonts Use the Bakoma TrueType fonts for rendering.Hlist AutoWidthChar will create a character as close to the given width as possible. but please check KNOWN ISSUES below first. state. state) Bases: matplotlib. height. please email
[email protected] AutoHeightChar will create a character as close to the given height and depth as possible. always=False) Bases: matplotlib. class matplotlib. class matplotlib. For a tutorial of its usage see Writing mathematical expressions. char_class=<class ‘matplotlib.BakomaFonts(*args.mathtext mathtext is a module for parsing a subset of the TeX math syntax and drawing them to a matplotlib backend. When using a font with multiple height versions of some characters (such as the BaKoMa fonts).Accent(c. the correct glyph will be selected. get_sized_alternatives_for_symbol(fontname. depth.1 47. shrink() class matplotlib.mathtext.AutoWidthChar(c. and STIX fonts are supported. otherwise this will always just return a scaled version of the glyph. each of which has its own proprietary 8-bit encoding. since they are already offset correctly from the baseline in TrueType fonts. always=False. When using a font with multiple width versions of some characters (such as the BaKoMa fonts).mathtext.mathtext. This document is primarily concerned with implementation details. mathtext. Note that TeX boxes have a width. depth) Bases: matplotlib.Error(msg) Helper class to raise parser errors. get_kerning(next) Return the amount of kerning between this and the given character.Matplotlib.1 class matplotlib. height. y2) shrink() class matplotlib.Glue class matplotlib. the font information and metrics are stored with each Char to make it easier to lookup the font metrics when needed.mathtext.Box(width.mathtext.mathtext. 624 Chapter 47. y) Render the character to the canvas shrink() matplotlib. state) Bases: matplotlib.Fonts(default_font_prop.mathtext.mathtext. x2.Filll Bases: matplotlib.Fill Bases: matplotlib. The class must be able to take symbol keys and font file names and return the character metrics. and depth.Node Represents a single character.FT2Font() FT2Font matplotlib.mathtext.Node Represents any node with a physical location.Char(c. y1.Glue class matplotlib.mathtext. mathtext_backend) Bases: object An abstract base class for a system of fonts to use for mathtext. height. grow() render(x1.0.mathtext.mathtext. and the advance (if different from width) must be converted into a Kern node when the Char is added to its parent Hlist. Release 1.mathtext. unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction.FT2Image() FT2Image class matplotlib.mathtext. matplotlib. The metrics must be converted to the TeX way. It also delegates to a backend class to do the actual drawing.Glue class matplotlib.mathtext. matplotlib mathtext .mathtext.Fil Bases: matplotlib. grow() is_slanted() render(x. Unlike TeX. Called when characters are strung together into Hlist to create Kern nodes. font2. •height: The height of the glyph in points. cal. fontsize2.Matplotlib. sf. ‘1’. bf or default/regular (non-math) fontclassX: TODO symX: a symbol in raw TeX form.mathtext 625 . 47. e. •width: The width of the glyph in points. rm. fontclass2. fontclass1. This corresponds to TeX’s definition of “height”. or the base font for Unicode (generic) font rendering. cal. ‘x’ or ‘sigma’ fontsize: font size in points dpi: current dots-per-inch Returns an object with the following attributes: •advance: The advance distance (in points) of the glyph. e. matplotlib. get_results(box) Get the data needed by the backend to render the math expression. sym. it. ymin. dpi) font: one of the TeX font names: tt. Release 1. fontsize. sym) Override if your font provides multiple sizes of the same symbol. The return value is backendspecific. sym1. destroy() Fix any cyclical references before the object is about to be destroyed. The expression renderer will select the most appropriate size for a given situation from this list.1. •xmin. xmax. fontsize1. sym2.the ink rectangle of the glyph •iceberg . sf. bf or default/regular (non-math) font_class: TODO sym: a symbol in raw TeX form. rm.1 default_font_prop: A FontProperties object to use for the default non-math font. get_kern(font1. ymax . Should return a list of symbols matching sym in various sizes. fontX: one of the TeX font names: tt. font_class.0. dpi) Get the kerning distance for font between sym1 and sym2. ‘1’. mathtext_backend: A subclass of MathTextBackend used to delegate the actual rendering. get_sized_alternatives_for_symbol(fontname.g. ‘x’ or ‘sigma’ fontsizeX: the fontsize in points dpi: the current dots-per-inch get_metrics(font.g.the distance from the baseline to the top of the glyph. it. mathtext.mathtext. shrink=0.0. stretch_order=0. y1. oy: position •facename: One of the TeX face names •font_class: •sym: TeX symbol name or single character •fontsize: fontsize in points •dpi: The dpi to draw at. facename. render_rect_filled(x1.Matplotlib.0. matplotlib mathtext . stretch=0. dpi) Get the xheight for the given font and fontsize.Node Most of the information in this object is stored in the underlying GlueSpec class. fontsize. d) Set the size of the buffer used to render the math expression.GlueSpec(width=0. y1) to (x2.Hlist A convenience class to create an Hlist whose contents are centered within its enclosing box.mathtext. copy=False) Bases: matplotlib. Used as a base unit for drawing lines such as in a fraction or radical. fontsize.mathtext. render_glyph(ox. get_xheight(font. shrink_order=0) Bases: object See Glue.0.0. copy() classmethod factory(glue_type) class matplotlib. Used by backends that need to subset fonts so they know which glyphs to include. y2) Draw a filled rectangle from (x1. oy. dpi) Draw a glyph at •ox. class matplotlib.Glue(glue_type.) grow() shrink() class matplotlib. font_class.1 get_underline_thickness(font. fontsize. h. Only really necessary for the bitmap backends. set_canvas_size(w. 626 Chapter 47.HCentered(elements) Bases: matplotlib. dpi) Get the line thickness that matches the given font. sym. which is shared between multiple glue objects.mathtext. but it’s easier to stick to what TeX does. Release 1. (This is a memory optimization which probably doesn’t matter anymore. get_used_characters() Get the set of characters that were used in the math expression. x2. y2). Hrule(state. The default values produce a box with the natural width.mathtext. class matplotlib.0.mathtext. m=’additional’.mathtext 627 .mathtext. grow() shrink() class matplotlib. •w: specifies a width •m: is either ‘exactly’ or ‘additional’. hpack(w. class matplotlib.Box A list of nodes (either horizontal or vertical).1. if the box is overfull.Node A Kern node has a width field to specify a (normally negative) amount of spacing. Release 1. Thus.List A horizontal list of boxes.Box A box with only width (zero height and depth).Kern(width) Bases: matplotlib. thickness=None) Bases: matplotlib.Matplotlib. This spacing correction appears in horizontal lists between letters like A and V when the font designer said that it looks better to move them closer together or further apart. do_kern=True) Bases: matplotlib. or if a \vbox includes other boxes that have been shifted left.0. ’exactly’) produces a box whose width is exactly w.mathtext. m=’additional’) The main duty of hpack() is to compute the dimensions of the resulting boxes.mathtext.0.mathtext.mathtext. A kern node can also appear in a vertical list. w=0. ’additional’) yields a box whose width is the natural width plus w. and to adjust the glue if one of those dimensions is pre-specified. while hpack(w.mathtext. class matplotlib. The computed sizes normally enclose all of the material inside the new box.MathTextParser(output) Bases: object 47. but some items may stick out if negative glue is used. when its width denotes additional spacing in the vertical direction. kern() Insert Kern nodes between Char nodes to set kerning. hpack(w=0.Rule Convenience class to create a horizontal rule.mathtext.mathtext.Hbox(width) Bases: matplotlib.Hlist(elements. grow() shrink() class matplotlib. The Char nodes themselves determine the amount of kerning they need (in get_kerning()). matplotlib. and this function just creates the linked list in the correct way.mathtext.List(elements) Bases: matplotlib.1 class matplotlib. to_rgba(texstr. dpi=72. Returns the offset of the baseline from the bottom of the image in pixels. to_mask(texstr. eg r’IQ: $sigma_i=15$’ dpi The dots-per-inch to render the text fontsize The font size in points Returns a tuple (array. depth) •array is an NxM uint8 alpha ubyte mask array of rasterized tex. filename A writable filename or fileobject texstr A valid mathtext string. get_depth(texstr. dpi=120. color=’black’. used for all non-math text. dpi=120. If prop is provided. to_png(filename.1 Create a MathTextParser for the given backend output. color=’black’. texstr. fontsize=14) Writes a tex expression to a PNG file. •depth is the offset of the baseline from the bottom of the image in pixels. texstr A valid mathtext string. dpi=120. eg r’IQ: $sigma_i=15$’ color A valid matplotlib color argument dpi The dots-per-inch to render the text fontsize The font size in points Returns the offset of the baseline from the bottom of the image in pixels. fontsize=14) Returns the offset of the baseline from the bottom of the image in pixels. The results are cached.Matplotlib. fontsize=14) texstr A valid mathtext string. depth) •array is an NxM uint8 alpha ubyte mask array of rasterized tex. prop=None) Parse the given math expression s at the given dpi.0. matplotlib mathtext . fontsize=14) texstr A valid mathtext string. so multiple calls to parse() with the same expression should be fast. eg r’IQ: $sigma_i=15$’ color Any matplotlib color argument dpi The dots-per-inch to render the text fontsize The font size in points Returns a tuple (array. it is a FontProperties object specifying the “default” font to use in the math expression. eg r’IQ: $sigma_i=15$’ dpi The dots-per-inch to render the text fontsize The font size in points parse(s. dpi=120. Release 1. 628 Chapter 47. render_glyph(ox.MathtextBackend Render glyphs and rectangles to an FTImage buffer. matplotlib. x2. y2) Draw a filled black rectangle from (x1. y1. y2). h. get_results(box) Return a backend-specific tuple to return to the backend after all processing is done. The purpose of MathtextBackend subclasses is to interface between mathtext and a specific matplotlib graphics backend. x2. get_hinting_type() get_results(box) render_glyph(ox. exception matplotlib. which is later transferred to the Agg image by the Agg backend.MathtextBackendAgg() class matplotlib.MathTextWarning Bases: exceptions. Release 1.0.Warning class matplotlib.mathtext. d) class matplotlib.1 •depth is the offset of the baseline from the bottom of the image in pixels. oy.mathtext.mathtext.Matplotlib. y2) set_canvas_size(w.mathtext. Only required for the Agg backend.mathtext. y1. render_filled_rect(x1.1. info) Draw a glyph described by info to the reference point (ox. h. oy.MathtextBackendBbox(real_backend) Bases: matplotlib.mathtext. set_canvas_size(w. info) render_rect_filled(x1. Subclasses need to override the following: •render_glyph() •render_filled_rect() •get_results() And optionally. oy).MathtextBackend Bases: object The base class for the mathtext backend-specific code.mathtext 629 . if you need to use a Freetype hinting style: •get_hinting_type() get_hinting_type() Get the Freetype hinting type to use with this particular backend.MathtextBackend A backend whose only purpose is to get a precise bounding box.MathtextBackendAggRender Bases: matplotlib. 47.mathtext. y1) to (x2. d) Dimension the drawing canvas matplotlib. MathtextBackend Store information to write a mathtext rendering to the Cairo backend. x2.mathtext. y2) class matplotlib.mathtext. get_results(box) render_glyph(ox. get_results(box) render_glyph(ox. info) render_rect_filled(x1. y2) matplotlib. class matplotlib. get_results(box) render_glyph(ox.MathtextBackendPs Bases: matplotlib. y1. oy. y1.mathtext. info) render_rect_filled(x1. y1.MathtextBackend Store information to write a mathtext rendering to the Cairo backend. info) render_rect_filled(x1. x2.mathtext.mathtext.mathtext.mathtext.mathtext.Matplotlib.1 get_hinting_type() get_results(box) render_glyph(ox.MathtextBackendBitmapRender Bases: matplotlib. No additional matplotlib backend is required. y1. matplotlib mathtext . Release 1. x2. y2) class matplotlib. get_results(box) render_glyph(ox. info) render_rect_filled(x1.MathtextBackend Store information to write a mathtext rendering to the PDF backend.mathtext.MathtextBackendPdf Bases: matplotlib.MathtextBackendBitmap() A backend to generate standalone mathtext images. oy.MathtextBackendPath Bases: matplotlib.mathtext. y2) 630 Chapter 47.mathtext.MathtextBackend Store information to write a mathtext rendering to the PostScript backend.MathtextBackendCairo Bases: matplotlib. x2. y1. oy. x2. oy.MathtextBackendAggRender get_results(box) class matplotlib.0. y2) class matplotlib. oy. info) render_rect_filled(x1. 1 class matplotlib. copy() font Parser.mathtext. toks) 47. y1. The grammar is based directly on that in TeX.0.mathtext. fontsize.mathtext.accent(s. There are only three levels of sizes. loc.Glue class matplotlib.mathtext.mathtext. though it cuts a few corners.Node Bases: object A node in the TeX box model get_kerning(next) grow() Grows one level larger.NegFill Bases: matplotlib.1.MathtextBackend Store information to write a mathtext rendering to the SVG backend.mathtext. x2. class State(font_output.mathtext.mathtext. loc.NegFilll Bases: matplotlib. oy. info) render_rect_filled(x1. It actually parses full strings containing math expressions. toks) Parser.NegFil Bases: matplotlib. and the “current” state is always at the top of the stack. class matplotlib. font.mathtext 631 .Glue class matplotlib. get_results(box) render_glyph(ox.auto_sized_delimiter(s. States are pushed and popped from a stack as necessary.mathtext. render(x. font_class. There is no limit to how big something can get. matplotlib.Matplotlib. after which things will no longer get smaller. Release 1.mathtext.MathtextBackendSvg Bases: matplotlib.Parser Bases: object This is the pyparsing-based parser for math expressions. y) shrink() Shrinks one level smaller.Glue class matplotlib. y2) class matplotlib. in that raw text may also appear outside of pairs of $. dpi) Bases: object Stores the state of the parser. genfrac(s. Parser.is_slanted(nucleus) Parser.frac(s. loc. loc. Parser.binom(s.customspace(s.group(s.sqrt(s.stackrel(s. loc. toks) Parser.function(s. toks) Parser.symbol(s.Matplotlib. toks) Parser. toks) Parser.1 Parser. loc.math(s. toks) Parser.end_group(s. loc. toks) Parser. fontsize. toks) Parser. Parser.space(s.is_dropsub(nucleus) Parser. loc. Returns the parse tree of Node instances. loc.is_overunder(nucleus) Parser. at the given fontsize and dpi.parse(s.pop_state() Pop a State off of the stack. toks) 632 Chapter 47. loc. matplotlib mathtext . toks) Parser. Release 1. toks) Parser. dpi) Parse expression s using the given fonts_object for output. toks) Parser. fonts_object. loc.finish(s. toks) Parser. toks) Parser.start_group(s. loc. Parser. loc. loc.clear() Clear any state before parsing. loc.non_math(s.push_state() Push a new State onto the stack which is just a copy of the current state. toks) Parser. toks) Parser. loc. loc. loc.0.char_over_chars(s.get_state() Get the current State of the parser. Parser. toks) Parser. toks) Parser. toks) Parser.subsuperscript(s. loc. loc.font(s. mathtext 633 . dpi) get_underline_thickness(font.Glue class matplotlib. dpi) get_xheight(font. and height fields just as in an Hlist. the height and depth are never running in a Vlist. **kwargs) Bases: matplotlib.1.Rule(width.mathtext. which traverse the Hlist nodes and Vlist nodes inside of horizontal and vertical boxes.Box A Rule node stands for a solid black rectangle. fontsize. •handles sized alternative characters for the STIXSizeX fonts.mathtext. sym1. state) Bases: matplotlib. depth.SsGlue Bases: matplotlib. static clamp(value) hlist_out(box) vlist_out(box) class matplotlib. BakomaFont and UnicodeFont. fontsize.mathtext. However. matplotlib. Since boxes can be inside of boxes inside of boxes. this one requires the Ps backend. this class: •supports “virtual fonts” which are complete alpha numeric character sets with different font styles at special Unicode code points. fontclass1. height. The global variables used in TeX to store state as it processes have become member variables here. get_kern(font1. This is called a “running dimension. if any of these dimensions is inf.mathtext.mathtext.StixSansFonts(*args. dpi) class matplotlib. sym) class matplotlib.Ship Bases: object Once the boxes have been set up. get_sized_alternatives_for_symbol(fontname. w.StixFonts(*args.UnicodeFonts A font handling class for the STIX fonts.” The width is never running in an Hlist. render(x.0.mathtext.Matplotlib. it has width. sym2. fontsize1. **kwargs) Bases: matplotlib. 47.StandardPsFonts(default_font_prop) Bases: matplotlib.Fonts Use the standard postscript fonts for rendering to backend_ps Unlike the other font classes. font2. depth. In addition to what UnicodeFonts provides. fontclass2. hlist_out() and vlist_out().mathtext.mathtext.mathtext.mathtext.StixFonts A font handling class for the STIX fonts (that uses sans-serif characters by default). Release 1.1 class matplotlib.mathtext. fontsize2. such as “Blackboard”. this sends them to output. the actual value will be determined by running the rule up to the boundary of the innermost enclosing box. y. the main work of Ship is done by two mutually recursive routines. h) class matplotlib. 1 class matplotlib. l=inf ) The main duty of vpack() is to compute the dimensions of the resulting boxes.0. sub.mathtext. fontsize1.get_xheight(font.TruetypeFonts An abstract base class for handling Unicode fonts. sym2.Hlist SubSuperCluster is a sort of hack to get around that fact that this code do a two-pass parse like TeX.mathtext.Vbox(height.mathtext. dpi) TruetypeFonts. dpi) class matplotlib.destroy() TruetypeFonts.mathtext. m=’additional’.0. class matplotlib. fontclass1. namely the nucleus. dpi) TruetypeFonts. class CachedFont(font) TruetypeFonts. sym1. matplotlib mathtext .get_kern(font1.mathtext.get_underline_thickness(font. class matplotlib. This class will “fallback” on the Bakoma fonts when a required symbol can not be found in the font. vpack(h=0.mathtext.Vlist(elements.Hlist A convenience class to create a Vlist whose contents are centered within its enclosing box. **kwargs) Bases: matplotlib.UnicodeFonts(*args.mathtext.mathtext.mathtext. fontclass2.0. the only Unicode font I’m aware of with a complete set of math symbols is STIX.mathtext. fontsize. such that if another script follows that needs to be attached. it can be reconfigured on the fly. depth) Bases: matplotlib. Release 1. sym) class matplotlib. fontsize2. m=’additional’) Bases: matplotlib. class matplotlib.SubSuperCluster Bases: matplotlib. h=0. and to adjust the glue if one of those dimensions is pre-specified.Box A box with only height (zero width). font2. get_sized_alternatives_for_symbol(fontname. While some reasonably complete Unicode fonts (such as DejaVu) may work in some situations. This lets us store enough information in the hlist itself.Fonts A generic base class for all font setups that use Truetype fonts (through FT2Font). fontsize. •h: specifies a height •m: is either ‘exactly’ or ‘additional’.mathtext.List A vertical list of boxes.Matplotlib.VCentered(elements) Bases: matplotlib.mathtext.and super-script. •l: a maximum height 634 Chapter 47.TruetypeFonts(default_font_prop. mathtext_backend) Bases: matplotlib. Matplotlib. or a Type1 symbol name (i.e. or the replacement character if this is a narrow build of Python and the requested character is outside the BMP. The default values produce a box with the natural width.mathtext. matplotlib.mathtext 635 .1 Thus. a TeX command (i. vpack(h. class matplotlib. matplotlib. ’exactly’) produces a box whose height is exactly h.e. ’additional’) yields a box whose height is the natural height plus h. matplotlib. while vpack(h.mathtext.0.1.Rule Convenience class to create a vertical rule. 47. r’pi’).mathtext.get_unicode_index(symbol) get_unicode_index(symbol) -> integer Return the integer index (from the Unicode table) of symbol. ‘phi’). Release 1.Vrule(state) Bases: matplotlib.mathtext.unichr_safe(index) Return the Unicode character corresponding to the index. symbol can be a single unicode character. matplotlib mathtext .0. Release 1.1 636 Chapter 47.Matplotlib. numpy.1 MATLAB compatible functions cohere() Coherence (normalized cross spectral density) csd() Cross spectral density uing Welch’s average periodogram detrend() Remove the mean or best fit line from an array find() Return the indices where some condition is true. This function is optimized to do this efficiently by caching the direct FFTs.1. prctile() find the percentiles of a sequence prepca() Principal Component Analysis psd() Power spectral density uing Welch’s average periodogram rk4() A 4th order runge kutta integrator for 1D or ND systems specgram() Spectrogram (power spectral density over segments of time) 48.CHAPTER FORTYEIGHT MATPLOTLIB MLAB 48. griddata() interpolate irregularly distributed data to a regular grid. 48.1.nonzero is similar but more general. This is not a MATLAB function.mlab Numerical python functions written for compatability with MATLAB commands with the same names. but we compute coherence a lot in my lab.2 Miscellaneous functions Functions that don’t exist in MATLAB.1 matplotlib. 637 . but are useful anyway: cohere_pairs() Coherence over all pairs. and we compute it for a lot of pairs. Window() win. formatd=formatd) rec2csv(r.xls’. change = FormatPercent(2).integrate tools) contiguous_regions() return the indices of the regions spanned by some logical mask cross_from_below() return the indices where a 1D array crosses a threshold from below cross_from_above() return the indices where a 1D array crosses a threshold from above 48.set_size_request(600.csv’.csv’.1 rk4() A 4th order Runge-Kutta ODE integrator in case you ever find yourself stranded without scipy (and the far superior scipy. ’test.3 record array helper functions A collection of helper methods for numpyrecord arrays See misc-examples-index rec2txt() pretty print a record array rec2csv() store record array in CSV file csv2rec() import record array from CSV file with type inspection rec_append_fields() adds field(s)/array(s) to record array rec_drop_fields() drop fields from record array rec_join() join two record arrays on sequence of fields recs_join() a simple join of multiple recarrays using a single column as a key rec_groupby() summarize data by groups (similar to SQL GROUP BY) rec_summarize() helper code to filter rec array fields into new fields For the rec viewer functions(e rec2csv).add(scroll) win. there are a bunch of Format objects you can pass into the functions that will do things like color negative values red. set percent formatting and scaling.Matplotlib. formatd=formatd) scroll = rec2gtk(r. formatd=formatd) win = gtk. checkrows=0) formatd = dict( weight = FormatFloat(2).main() 638 Chapter 48. etc. ) rec2excel(r. cost = FormatThousands(2).show_all() gtk.0. matplotlib mlab . Example usage: r = csv2rec(’somefile.800) win. ’test. Release 1.1. FormatObj fromstr(s) toval(x) class matplotlib.mlab.FormatDate fromstr(x) 48.mlab. the dataLim will be updated as new data come in.savetxt class matplotlib.loadtxt save() save ASCII file .mlab.4 Deprecated functions The following are deprecated.use numpy.1 48. update_datalim_to_current() Update the datalim in the current data in the fifo. please import directly from numpy (with care–function signatures may differ): load() load ASCII file . TODO: add a grow method that will extend nmax Note: mlab seems like the wrong place for this class. y data in a rotating buffer using numpy arrays under the hood. It is assumed that you will call asarrays much less frequently than you add data to the queue – otherwise another data structure will be faster.mlab. Buffer up to nmax points.Axes.1. N) Call func every time N events are passed.1. their length will be the len of data added or nmax. If you set the dataLim attr to BBox (eg matplotlib.dataLim). y or None. This can be used to support plots where data is added from a real time feed and the plot object wants to grab data from the buffer and plot it to screen less freqeuently than the incoming.FormatDate(fmt) Bases: matplotlib. None if no data set. Release 1.FormatBool Bases: matplotlib.mlab. class matplotlib. add(x. register(func.use numpy.0.mlab 639 .mlab. y) Add scalar x and y to the queue. last() Get the last x.mlab. func signature is func(fifo).FormatObj fromstr(x) toval(x) class matplotlib.FIFOBuffer(nmax) A FIFO queue to hold incoming x. matplotlib. asarrays() Return x and y as arrays.Matplotlib.FormatDatetime(fmt=’%Y-%m-%d %H:%M:%S’) Bases: matplotlib. FormatString Bases: matplotlib.mlab.mlab.mlab.mlab.FormatObj tostr(x) class matplotlib.FormatThousands(precision=4) Bases: matplotlib.mlab. Release 1.0.FormatFormatStr fromstr(s) toval(x) class matplotlib.mlab.1 class matplotlib.FormatFloat class matplotlib.FormatObj tostr(x) class matplotlib.FormatMillions(precision=4) Bases: matplotlib.mlab.FormatInt Bases: matplotlib.FormatObj fromstr(s) tostr(x) toval(x) class matplotlib. Use project to project the data onto a reduced set of dimensions Inputs: a: a numobservations x numdims array Attrs: a a centered unit sigma version of input a numrows.FormatFloat class matplotlib.mlab.mlab. scale=1.FormatFloat class matplotlib. matplotlib mlab .mlab. numcols: the dimensions of a mu : a numdims array of means of a 640 Chapter 48.PCA(a) compute the SVD of a and store data for PCA.mlab.mlab.0) Bases: matplotlib.FormatFormatStr(fmt) Bases: matplotlib.mlab.FormatFloat(precision=4.FormatObj fromstr(s) tostr(x) toval(x) class matplotlib.mlab.Matplotlib.FormatPercent(precision=4) Bases: matplotlib.mlab.mlab. max_length=1025) Return the binary representation of the input number as a string.. Increase the value of max_length for very large numbers. (dim is opposite to the numpy axis kwarg. Y. base=2.array(map(.mlab 641 .0. sequence.Matplotlib. sigmax=1. See bivariate normal at mathworld. dropping any axes where fraction of variance<minfrac matplotlib.mlab. y. sigmay=1.center_matrix(M. window=<function window_hanning at 0x3a178c0>.1. pad_to=None. but it returns an array.. sides=’default’.. y Array or sequence containing the data Keyword arguments: |P xy |2 P xx Pyy (48.bivariate_normal(X.0.mlab. Coherence is the normalized cross spectral density: C xy = x. mux=0. Works like map().1 sigma : a numdims array of atandard deviation of a fracs : the proportion of variance of each of the principal components Wt : the weight vector for projecting a numdims point or array into PCA space Y : a projected into PCA space The factor loadings are in the Wt factor. matplotlib. scale_by_freq=None) The coherence between x and y.1) 48. This is more efficient than using base_repr() with base 2.base_repr(number.amap(fn. detrend=<function detrend_none at 0x3a1c668>. This is just a convenient shorthand for matplotlib. If dim = 1 operate on columns instead of rows. Y..mlab. ie the factor loadings for the 1st principal component are given by Wt[0] center(x) center the data using the mean and sigma from training set a project(x. Fs=2. matplotlib. matplotlib.) matplotlib. dim=0) Return the matrix M with each row having zero mean and unit std.)). NFFT=256. *args) amap(function.mlab. numpy. .0.]) -> array. muy=0. sigmaxy=0. padding=0) Return the representation of a number in any given base. matplotlib. Release 1. minfrac=0.0.binary_repr(number.cohere(x.mlab. noverlap=0.0. sequence[.0) Bivariate Gaussian distribution for equal shape X.mlab. Note that on 32-bit machines.0) project x onto the principle axes. 2**1023 is the largest integer power of 2 which can be converted to a Python float. It is used to calculate the Fourier frequencies. window=<function window_hanning at 0x3a178c0>. noverlap=0. Fs: scalar The sampling frequency (samples per time unit).Matplotlib. while ‘twosided’ forces two-sided. detrend=<function detrend_none at 0x3a1c668>. where f are the frequencies of the coherence vector. numpy. scaling the individual densities by the sampling frequency has no effect. See Also: psd() and csd() For information about the methods used to compute P xy . numpy. but you can use a custom function as well. it must take a data segment as an argument and return the windowed version of the segment. The default value is 0 (no overlap). which gives density in units of Hz^-1.0. matplotlib mlab . matplotlib. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. scipy. preferSpeedOverMemory=True. a power 2 is most efficient. f ). The default is None. numpy.signal. For cohere.hamming(). returnPxx=False) Call signature: 642 Chapter 48. freqs. This allows for integration over the returned frequency values. NFFT=256. Release 1. ij.1 NFFT: integer The number of data points used in each block for the FFT. in matplotlib is it a function. detrend_mean().signal(). and detrend_linear(). pad_to: integer The number of points to which the data segment is padded when performing the FFT. window: callable or ndarray A function or a vector of length NFFT.blackman(). window_none(). scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. Unlike in MATLAB. allowing for more detail. which specifies the number of data points used. To create window vectors see window_hanning(). P xx and Pyy .mlab. This corresponds to the n parameter in the call to fft(). detrend: callable The function applied to each segment before fft-ing. in cycles per time unit. etc. The default value is 256. Must be even. If a function is passed as the argument. where the detrend parameter is a vector. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). This can be different from NFFT. which returns one-sided for real data and both for complex data. this can give more points in the plot. The default is True for MATLAB compatibility. The default value is 2. ‘onesided’ forces the return of a one-sided PSD. Default gives the default behavior. noverlap: integer The number of points of overlap between blocks.bartlett(). Fs=2.cohere_pairs(X. scipy. The return value is the tuple (Cxy. designed to remove the mean or linear trend. The default is window_hanning(). since the factors cancel out. The pylab module defines detrend_none().get_window(). progressCallback=<function donothing_callback at 0x3a21500>. because it caches most of the intensive computations.0..py in the src tree for an example script that shows that this cohere_pairs() and cohere() give the same results for a given pair.19)]) subplot(212) plot( freqs. Returns: (Cxy. For example.j) = •Phase: dictionary of phases of the cross spectral density at each frequency for each pair. If False. If N is the number of pairs. I. Phase.7GHZ Athlon with 512MB RAM compared with preferSpeedOverMemory = False. if X has 64 columns. But both solutions were more than 10x faster than naively crunching all possible pairs through cohere(). This is useful if memory becomes critical. See test/cohere_pairs_test.j) ) preferSpeedOverMemory is an optional bool. and you want to compute all nonredundant pairs. . Number of dictionary keys is len(ij).64 array over all nonredundant pairs. j). cohere(X[:. cohere_pairs() will still give significant performace gains over calling cohere() for each pair. Defaults to true. this function is O(N) for most of the heavy lifting. •freqs: vector of frequencies. whereas calling cohere for each pair is O(N 2 ). Even when preferSpeedOverMemory is False. equal in length to either the coherence or phase vectors for any (i.64): ij. to make a coherence Bode plot: subplot(211) plot( freqs. making 2 additional complex arrays with approximately the same number of elements as X. in X. Phase. Phase[(12. 48. j) key.. Each tuple is a pair of indexes into the columns of X for which you want to compute coherence..e. ij. preferSpeedOverMemory = True delivered a 33% performance boost on a 1. Release 1..mlab 643 . However. because of the caching. it is also more memory intensive. limits the caching by only making one.) Compute the coherence and phase for all pairs ij.i].append( (i. cohere_pairs() can be much more efficient than just calling cohere() for each pair. Cxy[(12. Keys are (i. X is a numSamples * numCols array ij is a list of tuples. Eg. complex cache arrays. In my tests with a 43000. Cxy[(i.19)]) For a large number of pairs. freqs = cohere_pairs( X. X[:.1. and will use subtantially less memory than if preferSpeedOverMemory is True. define ij as: ij = [] for i in range(64): for j in range(i+1.Matplotlib. rather than two. freqs) where: •Cxy: dictionary of (i.1 Cxy. matplotlib. j) tuples -> coherence vector for that pair.j]). 0. threshold) return the indices into x where x crosses some threshold from below. -0.mlab. noverlap gives the length of the overlap between blocks. 0. y.1 See Also: psd() For information about the methods used to compute P xy . noverlap=0.mlab.cross_from_above(x.0. Fs=2. detrend=<function detrend_none at 0x3a1c668>.mlab. ind1) such that mask[ind0:ind1].axhline(0.vlines(t[ind]. P xx and Pyy . eg the i’s where: x[i-1]<threshold and x[i]>=threshold Example code: import matplotlib. The vectors x and y are divided into NFFT length blocks.figure() ax = fig.5) ind = cross_from_below(s. window=<function window_hanning at 0x3a178c0>.pyplot as plt t = np. matplotlib mlab . ’-o’) ax.mlab.pi*t) fig = plt.show() See Also: cross_from_above() and contiguous_regions() matplotlib.add_subplot(111) ax. eg the i’s where: x[i-1]>threshold and x[i]<=threshold See Also: cross_from_below() and contiguous_regions() matplotlib.1) s = np. Each block is detrended by the function detrend and windowed by the function window.Matplotlib.arange(0.5) ax.5) ax.cross_from_below(x. pad_to=None.5) ax.csd(x. threshold) return the indices into x where x crosses some threshold from below. 1) plt. -1.all() is True and we cover all such regions TODO: this is a pure python implementation which probably has a much faster numpy impl matplotlib.sin(2*np. 1) ind = cross_from_above(s. sides=’default’. 0. s. -1. matplotlib.contiguous_regions(mask) return a list of (ind0. NFFT=256. The product of the 644 Chapter 48.plot(t. 2.axhline(-0.vlines(t[ind]. Release 1. scale_by_freq=None) The cross power spectral density by Welch’s average periodogram method.0. Must be even.signal(). John Wiley & Sons (1986) 48. numpy. while ‘twosided’ forces two-sided. This can be different from NFFT. matplotlib. The default is window_hanning(). pad_to: integer The number of points to which the data segment is padded when performing the FFT.1 direct FFTs of x and y are averaged over each segment to compute Pxy. designed to remove the mean or linear trend.hamming(). which gives density in units of Hz^-1. This allows for integration over the returned frequency values. freqs). Refs: Bendat & Piersol – Random Data: Analysis and Measurement Procedures. numpy.signal.mlab 645 . allowing for more detail.get_window().blackman(). detrend_mean(). and detrend_linear().0. freqs. The default is None. Default gives the default behavior. scipy. with a scaling to correct for power loss due to windowing. Release 1. The default value is 2. noverlap: integer The number of points of overlap between blocks. in cycles per time unit. where the detrend parameter is a vector. If a function is passed as the argument. The pylab module defines detrend_none(). which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. Returns the tuple (Pxy. which specifies the number of data points used.bartlett(). this can give more points in the plot. window_none(). a power 2 is most efficient. which returns one-sided for real data and both for complex data. The default value is 0 (no overlap). scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. window: callable or ndarray A function or a vector of length NFFT. It is used to calculate the Fourier frequencies.Matplotlib. x. it must take a data segment as an argument and return the windowed version of the segment. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). Fs: scalar The sampling frequency (samples per time unit). numpy. etc. but you can use a custom function as well. Unlike in MATLAB. y Array or sequence containing the data Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. ‘onesided’ forces the return of a one-sided PSD. The default value is 256. This corresponds to the n parameter in the call to fft(). To create window vectors see window_hanning(). If len(x) < NFFT or len(y) < NFFT. in matplotlib is it a function. they will be zero padded to NFFT. detrend: callable The function applied to each segment before fft-ing. scipy. The default is True for MATLAB compatibility.1. skiprows=0. is a list of header names. it is a sequence of names to use for the column names. no header will be read from the file •missingd is a dictionary mapping munged column names to field values which signify that the field does not contain actual data and should be masked. ‘0000-00-00’ or ‘unused’ •missing: a string whose value signals a missing field regardless of the column it appears in •use_mrecords: if True.dist(x.mlab. axis=0) Return x minus its mean along the specified axis matplotlib.py matplotlib.mlab. spaces will be converted to underscores. a header row is required to automatically assign the recarray names.0. e. •fname: can be a filename or a file handle.mlab. missing=’‘.csv2rec(fname. If names is None. •converterd: if not None. y) Return the distance between two points. If names is not None. Release 1.mlab. converterd=None.csvformat_factory(format) matplotlib. and illegal attribute name characters removed. •names: if not None. When set to zero all rows are validated.mlab.detrend_linear(y) Return y minus best fit line. return an mrecords.detrend(x. s0. In this case. ‘. delimiter=’. s1) Get the distance of a point to a segment. s0.detrend_none(x) Return x: no detrending matplotlib.Matplotlib. In this case. The headers will be lower cased.g.dist_point_to_segment(p.demean(x. s1 are xy sequences 646 Chapter 48. if the filename ends in ‘. names=None. matplotlib.gz’ •comments: the character used to indicate the start of a comment in the file •skiprows: is the number of rows from the top to skip •checkrows: is the number of rows to check to validate the column data type. it is assumed there is no header row. matplotlib mlab . p. checkrows=0.fromrecords record array if any of the data are missing If no rows are found. None is returned – see examples/loadrec. missingd=None. Support for gzipped files is automatic.1 matplotlib.mlab. comments=’#’. key=None) matplotlib. use_mrecords=False) Load data from comma/space/tab delimited file in fname into a numpy record array and return the record array. is a dictionary mapping column number or munged column name to a converter function.detrend_mean(x) Return x minus the mean(x) matplotlib.mlab.mlab. ‘linear’ detrending matplotlib.mlab. entropy(y. frange() basically becomes :func:numpy. step.x0+d. but defaults to a closed interval. x1]. x0+2.exp_safe(x) Compute exponentials which safely underflow to zero.arange().fftsurr(x.0 + log(2*pi*sigma**2..mlab. Where X is an M x N array or matrix. frange() can also be called with the keyword npts. matplotlib.d) returns [x0. This sets the number of points the list should contain (and overrides the value step might have been given). The usual behavior of range() can be obtained by setting the keyword closed = 0. bins can be a number of bins or a range of bins.0.] stop[.mlab 647 .. Slow. frange(x0. but convenient to use. start defaults to 0.mlab.Matplotlib. and endpoints are often desired in this use. numpy. Similar to numpy. Distance is the standard Euclidean distance. since frange() will probably be more useful for generating lists of points for function evaluation.mlab. When step is given.mlab. frange(x0. dow=<function window_none at 0x3a17cf8>) Compute an FFT phase randomized surrogate of x. The distances between successive rows is computed.0) ) matplotlib. and the endpoint is included.mlab.mlab. x1) returns [x0. matplotlib. Note that numpy provides proper floating point exception handling with access to the underlying hardware. it specifies the increment (or decrement)..x1.donothing_callback(*args) matplotlib. xfin=None.xfin] where xfin <= x1.com/Archive/algorithm_0102/algorithm_0102. in this case. This behavior is different from that of range() and numpy. Compare S with analytic calculation for a Gaussian: x = mu + sigma * randn(200000) Sanalytic = 0. matplotlib.1.1 This algorithm from http://softsurfer. All arguments can be floating point numbers. This is deliberate.distances_along_curve(X) Computes the distance between a set of successive points in N dimensions.find(condition) Return the indices where ravel(condition) is true matplotlib..mlab..arange(). win- 48. detrend=<function detrend_none at 0x3a1c668>. Release 1.5 * ( 1. bins) Return the entropy of the data in y.arange() doesn’t offer this option.x0+2d. x0+1.frange(xini.histogram(). keywords]) -> array of floats Return a numpy ndarray containing a progression of floats.htm#Distance%20to%20Ray%20o matplotlib. matplotlib...2) where pi is the probability of observing y in the ith bin of bins. **kw) frange([start. see numpy.arange‘. delta=None. pi log2 (pi ) (48. . 3.delaunay package.net/project/showfiles. which contains code that is not redistributable under a BSD-compatible license.2) array([1. and z are 1D arrays. x. The triangulation algorithm in this package is known to fail on some nearly pathological cases. 2.125. 3.yi) fits a surface of the form z = f*(*x. z) where x and y are the indices into Z and z are the values of Z at those indices. 2.7. In this case.get_sparse_matrix(M. Release 1. formatd=None) build a formatd guaranteed to have a key for every dtype name matplotlib.z.3. Cond) Z and Cond are M x N matrices. This toolkit is based on the NCAR natgrid library. If the interp keyword is set to ‘linear‘. y. then linear interpolation is used instead of natural neighbor. y) to the data in the (usually) nonuniformly spaced vectors (x..npts=5) array([ 1.]) >>> frange(3. interp=’nn’) zi = griddata(x.. can be either 1D or 2D. dtype=’l’...]) >>> frange(1.identity(n. 6.xi. 3.mlab. When installed. Return value is (x. matplotlib.5. otherwise it will use the built-in matplotlib. but must be monotonically increasing.5. 5.get_xyz_where(Z. written by Robert Kern.y. 1. y. xi and yi must describe a regular grid.mlab. 1. z). this algorithm is provided by the matplotlib. z. n. a separate toolkit (mpl_tookits. typecode=None) Returns the identity matrix of shape (n.php?group_id=80706& matplotlib. griddata() interpolates this surface at the points specified by (xi. For ranks higher than 2. frac=0.mlab. the output grid is assumed to be regular with a constant grid spacing in both the x and y directions. For this reason. yi) to produce zi.375. Z are data and Cond is a boolean matrix where some condition is satisfied. uses natural neighbor interpolation based on Delaunay triangulation.mlab. A masked array is returned if any grid points are outside convex hull defined by input data (no extrapolation is done). The natgrid matplotlib toolkit can be downloaded from http://sourceforge.6.. N. If interp keyword is set to ‘nn‘ (default). y.0. you must use natural neighbor interpolation. Linear interpolation is only valid if matplotlib.. y.griddata(x.get_formatd(r. For regular grids with nonconstant grid spacing. 2.Matplotlib.delaunay package is used mpl_tookits..10000000000000001) Return a M x N sparse matrix with frac elements randomly filled. depending on floating point vagueries >>> frange(1.delaunay package. rank=2.mlab..closed=0) array([ 0.natgrid) has been created that provides a more robust algorithm fof triangulation and interpolation.6. yi. matplotlib. xi. . matplotlib mlab . this object is simply a multi-index Kronecker delta: 648 Chapter 48.natgrid only provides natural neighbor interpolation. By default. 5]) or 1. n) (rank r). .1 Examples: >>> frange(3) array([ 0.natgrid algorithm.5 ]) matplotlib. this function will use the mpl_toolkits.75 . .. it can have multiple axes. matplotlib.1.1 / id[i0. it is much faster. matplotlib. matplotlib. otherwise. Return value is a sequence of indices into points for the points that are inside the polygon. returns True if the supplied numpy array or matrix X looks like a vector.identity(n) – but surprisingly.Matplotlib. alpha) Returm the levy pdf evaluated at x for params gamma. while this does true linear interpolation at an arbitrary set of points.. matplotlib.mlab.i1. Optionally a dtype (or typecode) may be given (it defaults to ‘l’). This is very inefficient linear interpolation meant to be used only for a small number of points in relatively non-intensive use cases. except for one of them). flattened out. verts) points is a sequence of x. fprime) x is a very long trajectory from a map. verts is a sequence of x. matplotlib. zero otherwise.. meaning it has a one non-singleton axis (i. matplotlib. Since rank defaults to 2.l1norm(a) Return the l1 norm of a. For real linear interpolation. and fprime returns the derivative of x.ispower2(n) Returns the log base 2 of n if n is a power of 2. simple_linear_interpolation() will give a list of point between a start and an end.isvector(X) Like the MATLAB function with the same name.less_simple_linear_interpolation(x.=iR.is_closed_polygon(X) Tests whether first and last object in a sequence are the same.mlab. These are presumably coordinates on a polygonal curve. gamma.0..mlab.mlab. interpret accordingly. use X..mlab. y points. matplotlib.levypdf(x. matplotlib. This function will be removed from matplotlib.e.simple_linear_interpolation()) linear interpolation. If you just want to see if the array has 1 axis. Implemented as a separate function (not a call to norm() for speed).mlab 649 . flattened out. y vertices of a polygon. use scipy. but all must have length 1.liaupunov(x. this function behaves in the default case (when only n is given) like numpy.ndim == 1.mlab..mlab. alpha matplotlib.mlab.mlab. Implemented as a separate function (not a call to norm() for speed). in which case this function tests if that curve is closed.l2norm(a) Return the l2 norm of a. Release 1. Note the potential ambiguity if n == 1: 2**0 == 1.inside_poly(points. matplotlib.iR] = -| \ 1 0 if i0=i1=. 48. y. extrap=False) This function provides simple (but somewhat less so than cbook. xi. dtype=<type ‘numpy. see below: X = load(’test. •converters. caveat emptor.0] y = X[:. eg usecols=[1.mio module. usecols=None. Note: What the function here calculates may not be what you really want. matplotlib. Eg.5 Strogatz (1994) “Nonlinear Dynamics and Chaos”.mlab. Release 1. is a dictionary mapping column number to a function that will convert that column to a float (or the optional dtype if specified). if column 0 is a date string: converters = {0:datestr2num} •skiprows is the number of rows from the top to skip. if not None.0. matplotlib mlab .1 Returns : . converters=None. comments=’#’. is a sequence of integer column indexes to extract where 0 is the first column.. use scipy. It also seems that this function’s name is badly misspelled.gz’. matfile data is not supported. for that. The data must be regular. if the filename ends in ‘. any whitespace string is a separator.Matplotlib. Wikipedia article on Lyapunov Exponent.dat’) x = load(’test. same number of values in every row fname can be a filename or a file handle. If delimiter is unspecified or None.io. 5th and 6th columns •unpack.loadtxt.load(fname. unpack=False. skiprows=0.float64’>) Load ASCII data from fname into an array and return the array.4. if True.dat’) # a matrix of data # a single column of data •comments: the character used to indicate the start of a comment in the file •delimiter is a string-like character used to seperate values in the file. Support for gzipped files is automatic.1] # data in two columns Alternatively. Deprecated: use numpy. •usecols. you can do the same with “unpack”. will transpose the matrix allowing you to unpack into named arguments on the left hand side: 650 Chapter 48.dat’) t = X[:.5] to extract just the 2nd. if not None. math: \lambda = \frac{1}{n}\sum \ln|f^’(x_i)| See Also: Lyapunov Exponent Sec 10. delimiter=None. Example usage: X = load(’test. This is NOT a true matrix norm.z = load(’somefile.0. sigma matplotlib.Axes.longest_contiguous_ones(x) Return the indices of the longest stretch of contiguous ones in x.mlab.mlab. since arrays of arbitrary rank are always flattened. p=2) norm(a. matplotlib.norm_flat(a.mlab.movavg(x. x. pick the first. If there are two equally long stretches. return the vertices of a polygon that has a horizontal base at xmin and an upper bound at the ys. eg: xv.y. xmax.1 t.mlab 651 . xmin is a scalar.longest_ones(x) alias for longest_contiguous_ones matplotlib.mlab.mlab. *args) Return the normal pdf evaluated at x. matplotlib.p=2) -> l-p norm of a.log2(x.logspace(xmin. matplotlib.mlab. p can be a number or the string ‘Infinity’ to get the L-infinity norm.path_length(X) Computes the distance travelled along a polygonal curve in N dimensions. the rows of X).fill(). matplotlib.Matplotlib. xs. n) Compute the len(n) moving average of x. ys) Given a sequence of xs and ys.flat Return the l-p norm of a. matplotlib. yv = poly_below(0.e. y) ax. This is a _slow_ function but which is guaranteed to return the correct integer value if the input is an integer exact power of 2. N) matplotlib.poly_below(xmin. Intended for use with matplotlib. assuming x is a vector of zeros and ones. Where X is an M x N array or matrix.float_ See Also: See examples/pylab_examples/load_converter.y = load(’test. default: numpy.fill(xv. usecols=[3. matplotlib.normpdf(x. args provides mu. ln2=0.1. Returns an array of length M consisting of the distance along the curve at each point (i.5.mlab.7].mlab. unpack=True) # for two column data x.dat’. matplotlib. Release 1.mlab.axes.69314718055994529) Return the log(x) in base 2.py in the source tree Exercises these options.dat’. yv) many of 48.. considered as a flat array. unpack=True) •dtype: the array will have this dtype. noverlap gives the length of the overlap between blocks.0. ie. Fs=2. x Array or sequence containing the data Keyword arguments: NFFT: integer The number of data points used in each block for the FFT.fill(). NFFT=256. detrend=<function detrend_none at 0x3a1c668>. Fs: scalar The sampling frequency (samples per time unit). 100. 50.psd(x. Trans.0)) Return the percentiles of x.. and 3 indicates the value is above the 75th percentile cutoff.mlab.Matplotlib.poly_between(x. with a scaling to correct for power loss due to windowing. 1 indicates the value is >= the 25th and < 50th percentile. 75. y arrays for use with matplotlib. p=(0. Pcomponents = Trans *] P •fracVar [the fraction of the variance accounted for by each] component returned A similar function of the same name was in the MATLAB R13 Neural Network Toolbox but is not found in later versions. P is a (numVars. Must be even. it will be zero padded to NFFT. ylower and yupper.1 matplotlib.prctile_rank(x. the ith element of the return sequence is the p*(i)-th percentile of *x. .100] or a scalar which indicates how many quantiles of data you want ranked. If p is a sequence.2. return the polygon that fills the regions between them.mlab. 652 Chapter 48.0.0. fracVar) where: •Pcomponents : a (numVars. frac is the minimum fraction of variance that a component must contain to be included.len(p). numObs) array •Trans [the weights matrix. The default value is 256.0..prctile(x.axes. matplotlib.mlab. matplotlib mlab .1. yupper) Given a sequence of x. numObs) array. Eg if p = (25.mlab.. ylower. Release 1. they must be equal in length to x.Axes. 25. p) Return the rank for each element in x. matplotlib. sides=’default’. window=<function window_hanning at 0x3a178c0>.. The vector x is divided into NFFT length blocks. in cycles per time unit. The default value is 2. 75). ylower or yupper can be scalar or iterable. Each block is detrended by the function detrend and windowed by the function window. matplotlib. matplotlib. If len(x) < NFFT.mlab. Return value is a tuple of the form (Pcomponents.3] where 0 indicates the value is less than the 25th percentile. frac=0) WARNING: this function is deprecated – please see class PCA instead Compute the principal components of P. The absolute(fft(block))**2 of each segment are averaged to compute Pxx. freqs.0. the return value will be a len(x) array with values in [0. p is either an array of percentiles in [0. 50. Return value is x. It is used to calculate the Fourier frequencies.prepca(P. scale_by_freq=None) The power spectral density by Welch’s average periodogram method. a power 2 is most efficient. return the rank 0. If they are iterable. its successor seems to be called “processpcs”. noverlap=0. p can either be a sequence of percentile values or a scalar. the largest value of x less than or equal to the p percentage point in the sequence is returned. pad_to=None. If p is a scalar. Default gives the default behavior. Release 1. scipy. withheader=True) Save the data from numpy recarray r into a comma-/space-/tab-delimited file. The default value is 0 (no overlap).mlab. delimiter=’. detrend_mean(). numpy. pad_to: integer The number of points to which the data segment is padded when performing the FFT. numpy. John Wiley & Sons (1986) matplotlib. which specifies the number of data points used. which gives density in units of Hz^-1.hamming(). it must take a data segment as an argument and return the windowed version of the segment. q2x.signal(). ‘. missingd=None. if the filename ends in ‘. which returns one-sided for real data and both for complex data.gz’ 48.blackman(). fname. matplotlib. this can give more points in the plot.get_window().0. etc. Support for gzipped files is automatic. formatd=None. allowing for more detail.1 detrend: callable The function applied to each segment before fft-ing. and detrend_linear().signal. numpy. The inputs are the x and y coordinates of the three control points of a quadratic curve. and the output is a tuple of x and y coordinates of the four control points of the cubic curve.rec2csv(r. This allows for integration over the returned frequency values.Matplotlib. window_none(). q0y. This corresponds to the n parameter in the call to fft(). If a function is passed as the argument. Unlike in MATLAB.quad2cubic(q0x. Refs: Bendat & Piersol – Random Data: Analysis and Measurement Procedures.mlab 653 . missing=’‘.1. but you can use a custom function as well.bartlett(). The default is None. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. The record array dtype names will be used for column headers. noverlap: integer The number of points of overlap between blocks. Returns the tuple (Pxx.mlab. q2y) Converts a quadratic Bezier curve to a cubic approximation. where the detrend parameter is a vector. scipy. q1y. in matplotlib is it a function. This can be different from NFFT. The default is True for MATLAB compatibility. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). while ‘twosided’ forces two-sided. window: callable or ndarray A function or a vector of length NFFT. q1x. fname: can be a filename or a file handle. freqs). which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. The pylab module defines detrend_none(). matplotlib. ‘onesided’ forces the return of a one-sided PSD. designed to remove the mean or linear trend. To create window vectors see window_hanning(). The default is window_hanning(). then names.076 matplotlib. with the associated stat summary output. names. arrs and dtypes do not have to be lists.32 Return 0.field2’ Example: precision=[0. matplotlib.Matplotlib. header=None. names) Return a new numpy record array with fields in names dropped.mlab. outname) tuples which will call x = func(attr) and assign x to the record array output with attribute outname.0. Set to a list of integers to apply precision individually.3] Output: ID ABC XYZ Price 12. with the associated group values. fields : if not None. Precision for non-floats is simply ignored. fields=None) Returns a textual representation of a record array.mlab. a list of field names to print.rec_drop_fields(rec. ‘field2’] or a single comma separated string like ‘field1. precision=3. and for each outname name in the stats argument.rec_groupby(r.234 -0. For example: stats = ( (’sales’.2. ’avgsale’) ) Return record array has dtype names for each attribute name in the the groupby argument. ‘productcode’) stats is a sequence of (attr. arrs. Set to an integer to apply to all floats. matplotlib. ’numsales’). dtypes=None) Return a new record array with field names populated with data from arrays in arrs. (’sales’. do not write the attribute names in the first row for formatd type FormatFloat.54 6. np. we override the precision to store full precision floats in the CSV file See Also: csv2rec() For information about missing and missingd. 654 Chapter 48.1 withheader: if withheader is False. matplotlib mlab . which can be used to fill in masked values into your CSV file. len. If appending a single field. func.rec2txt(r.rec_append_fields(rec. eg (‘date’. stats) r is a numpy record array groupby is a sequence of record array attribute names that together form the grouping key. matplotlib. They can just be the values themselves. r: numpy recarray header: list of column headers padding: space between each column precision: number of decimal places to use for floats.mlab. Release 1.mean.mlab. fields can be a list of strings like [’field1’. padding=3. groupby. namePFN-1].mlab. r1]. r1 (also r2) must not have any duplicate keys. jointype=’outer’. [rowkey.rec_keep_fields(rec. If r1 and r2 have equal values on all the keys in the key tuple...) matplotlib. defaults=None. matplotlib. r2postfix=‘2’) Join record arrays r1 and r2 on key... PFN-1] are supplied. names) Return a new numpy record array with only fields listed in names matplotlib.0. with extra arrays for each element in summaryfuncs. The jointype keyword can be ‘inner’. This function only joins a single column of the multiple record arrays key is the column name that acts as a key name is the name of the column that we want to join recs is a list of record arrays to join jointype is a string ‘inner’ or ‘outer’ missing is what any missing field is replaced by postfixes if not None. The keywords r1postfix and r2postfix are postfixed to column names (other than keys) that are both in r1 and r2. ‘outer’. then their fields will be merged into a new record array containing the intersection of the fields of r1 and r2.. Release 1. name0.mlab. r1postfix=‘1’. a len recs sequence of postfixes returns a record array with columns [rowkey. postfixes=None) Join a sequence of record arrays on single column key.integrate().recs_join(key.rec_summarize(r. y0.rk4(derivs. y0 initial state vector 48. name1.. outname) tuples which will apply func to the the array r*[attr] and assign the output to a new attribute name *outname. key is a tuple of field names – if key is a string it is assumed to be a single attribute name. func. or if postfixes [PF0. missing=0. "close". summaryfuncs) r is a numpy record array summaryfuncs is a list of (attr. The returned record array is identical to r. Otherwise use scipy. t) Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.mlab. jointype=’inner’. .mlab.1 matplotlib. namePF1. This is a toy implementation which may be useful if you find yourself stranded on a system w/o scipy. To do a rightouter join just reverse r1 and r2.mlab. matplotlib. matplotlib. r1. recs. recs=[r0. . PF1. namePF0.1.. r2. missing=0.0.Matplotlib.rec_join(key. Example: r = recs_join("date". The defaults keyword is a dictionary filled with {column_name:default_value} pairs. name. ‘leftouter’. .mlab 655 . namen-1]. x) # x is 1D save(’test3.savetxt.safe_isinf(x) numpy.18e’. Release 1. fname can be a filename or a file handle. X. If the filename ends in ‘. t) Example 2: ## 1D system alpha = 2 def derivs(x. delimiter=’ ‘) Save the data in X to file fname using fmt string to convert the data to strings.0. X) # X is an array save(’test1.z)) # x. x. matplotlib.1 t sample times derivs returns the derivative of the system and has the signature dy = derivs(yi.0. matplotlib. Example usage: save(’test.y.out’.2) yout = rk4(derivs6. matplotlib mlab . fmt=’%1.isinf() for arbitrary types matplotlib. 656 Chapter 48.out’.t): return -alpha*x + exp(-t) y0 = 1 yout = rk4(derivs.y. eg. t) If you have access to scipy. dt) y0 = (1. The load() function understands gzipped files transparently. flattened out.4e’) # use exponential notation delimiter is used to separate the fields. Deprecated. you should probably be using the scipy. y0.t): d1 = x[0] + 2*x[1] d2 = -3*x[0] + 4*x[1] return (d1.out’.mlab. delimiter ‘. 2. the file is automatically saved in compressed gzip format. y0.0.out’.save(fname.mlab.mlab.rms_flat(a) Return the root mean square of all the elements of a.z equal sized 1D arrays save(’test2.0005 t = arange(0.safe_isnan(x) numpy. (x. ti) Example 1 ## 2D system def derivs6(x. fmt=’%.integrate tools rather than this function.’ for comma-separated values. d2) dt = 0.Matplotlib. Use numpy.isnan() for arbitrary types matplotlib.gz’.mlab. Must be even. The parabola method gives very similar results to the circle method for most regular cases but behaves much better in special cases. Fs: scalar The sampling frequency (samples per time unit). designed to remove the mean or linear trend.mlab. If x is real (i. (x4. a power 2 is most efficient. Norbert Nemec.1 matplotlib. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT.e. The windowing function window is applied to each segment. Institute of Theoretical Physics.uni-regensburg. s2) Return True if s1 and s2 intersect. Unlike in MATLAB. pad_to=None. in cycles per time unit. so an aspect ratio is completely arbitrary. sides=’default’. detrend: callable The function applied to each segment before fft-ing. and detrend_linear(). y3). Fs=2. y4) matplotlib.mlab 657 . detrend_mean(). non-complex) only the spectrum of the positive frequencie is returned. This method should be superior to that described in the appendix of A CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russel W. and the amount of overlap of each segment is specified with noverlap. the abscissa are given in different dimensions. For many functions. March 2006 halldor at vedur. in matplotlib is it a function. scale_by_freq=None) Compute a spectrogram of data in x.and y-values.segments_intersect(s1. s1 and s2 are defined as: s1: (x1. The default value is 256.Matplotlib. (x2.1. y) slopes() calculates the slope y‘(x) The slope is estimated using the slope obtained from that of a parabola through any three consecutive points. It is used to calculate the Fourier frequencies.slopes(x. y1). detrend=<function detrend_none at 0x3a1c668>. Stineman (Creative Computing July 1980) in at least one aspect: Circles for interpolation demand a known aspect ratio between x.is) matplotlib.0. window=<function window_hanning at 0x3a178c0>. April 2006 Norbert. If x is complex then the complete spectrum is returned. University or Regensburg.Nemec at physik.mlab. Release 1. freqs. 48. Data are split into NFFT length segements and the PSD of each section is computed. however. Icelandic Meteorological Office.specgram(x.de (inspired by a original implementation by Halldor Bjornsson. but you can use a custom function as well. The default value is 2. y2) s2: (x3. matplotlib. noverlap=128. The pylab module defines detrend_none(). NFFT=256. where the detrend parameter is a vector.mlab. plot(x. Returns a tuple (Pxx.signal. y.get_window(). freqs.Matplotlib.20). scipy. y = sin(x). then interpolates over a finer abscissa: x = linspace(0. If a function is passed as the argument.2*pi. which returns one-sided for real data and both for complex data. scipy. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. Here’s an example that generates a coarse sine curve. numpy. while ‘twosided’ forces two-sided. noverlap: integer The number of points of overlap between blocks. and in not returning times. x. which gives density in units of Hz^-1.2*pi.mlab.bartlett(). The default value is 0 (no overlap).yi) The interpolation method is described in the article A CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russell W. Release 1. See Also: psd() psd() differs in the default overlap.hamming(). etc. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). window_none(). To create window vectors see window_hanning(). The default is window_hanning(). it must take a data segment as an argument and return the windowed version of the segment. numpy.y.blackman(). The default is True for MATLAB compatibility. This allows for integration over the returned frequency values.’o’.0. The default is None. this can give more points in the plot.yp). yp = cos(x) xi = linspace(0. allowing for more detail. Stineman. matplotlib. yi = stineman_interp(xi.y. which specifies the number of data points used. columns are the periodograms of successive segments •freqs: 1-D array of frequencies corresponding to the rows in Pxx •t: 1-D array of times corresponding to midpoints of segments. pad_to: integer The number of points to which the data segment is padded when performing the FFT. yp=None) Given data vectors x and y. in returning the mean of the segment periodograms. the function stineman_interp() uses Stineman interpolation to calculate a vector yi corresponding to xi. Default gives the default behavior. numpy. The article appeared in the July 1980 issue of Creative Computing with a note from the editor stating that while they were: 658 Chapter 48.xi.1 window: callable or ndarray A function or a vector of length NFFT. the slope vector yp and a new abscissa vector xi. This can be different from NFFT. matplotlib mlab .signal(). ‘onesided’ forces the return of a one-sided PSD.x. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. t): •Pxx: 2-D array.40). This corresponds to the n parameter in the call to fft().stineman_interp(xi. If axis is None. University or Regensburg.uni-regensburg.1 not an academic journal but once in a while something serious and original comes in adding that this was “apparently a real solution” to a well known problem.window_none(x) No window function.1.window_hanning(x) return x times the hanning window of len(x) matplotlib. April 2006 Norbert.is Completely reworked and optimized for Python by Norbert Nemec.norm() function for vectors.. matplotlib. For yp = None.mlab. compute over all elements of X. This is like the numpy.mlab.mlab..Matplotlib. but has the ability to work over a particular axis of the supplied array or matrix. Institute of Theoretical Physics.Nemec at physik. x is assumed to be sorted in increasing order. Release 1. simply return x 48. Computes (sum((x_i)^P))^(1/P) for each {x_i} being the elements of X along the given axis. Icelandic Meteorolocial Office. axis=None) Finds the length of a set of vectors in n dimensions.mlab 659 . the routine tries an extrapolation. matplotlib. is questionable. For values xi[j] < x[0] or xi[j] > x[-1].de matplotlib.vector_lengths(X. of course. the routine automatically determines the slopes using the slopes() routine. March 2006 halldor at vedur.0. P=2.0. Original implementation by Halldor Bjornsson. The relevance of the data obtained from this. 1 660 Chapter 48.Matplotlib. Release 1.0. matplotlib mlab . they should use iter_segments() to get the vertex/code pairs. •CLOSEPOLY [1 vertex (ignored)] Draw a line segment to the start point of the current polyline. with the given control points. possibly closed. The underlying storage is made up of two parallel numpy arrays: • vertices: an Nx2 float array of vertices • codes: an N-length uint8 array of vertex types These two arrays always have the same length in the first dimension.path. do not store a codes at all. 1 endpoint] Draw a quadratic Bezier curve from the current position. class matplotlib. _interpolation_steps=1) Bases: object Path represents a series of possibly disconnected.CHAPTER FORTYNINE MATPLOTLIB PATH 49. to represent a cubic curve. with the given control point. Instead. For example. •CURVE3 [1 control point. codes=None. 1 endpoint] Draw a cubic Bezier curve from the current position. as an optimization. •LINETO [1 vertex] Draw a line from the current position to the given vertex.path Contains a class for managing paths (polylines). to the given end point. to the given end point. since many Path objects. This is important. The code types are: •STOP [1 vertex (ignored)] A marker for the end of the entire path (currently not required and ignored) •MOVETO [1 vertex] Pick up the pen and move to the given vertex. you must provide three vertices as well as three codes CURVE3. Users of Path objects should not access the vertices and codes arrays directly. Note also that the vertices and codes arrays should be treated as immutable – there are a number of optimizations and assumptions made up front in the constructor that will not change when the data changes.1 matplotlib. line and curve segments. but have a default one provided for them by iter_segments(). •CURVE4 [2 control points. 661 .Path(vertices. If transform is not None. interpolated(steps) Returns a new path resampled to length N x steps. transform=None) Returns True if this path completely contains the given path. ymax) of the path. quadratic or cubic Bezier curves. ymin. Release 1. such as iter_segments(). is_wedge=False) (staticmethod) Returns an arc on the unit circle from angle theta1 to angle theta2 (in degrees). 2003. codes is an N-length numpy array or Python sequence of type matplotlib.Path. intersects_bbox(bbox. If vertices contains masked values.code_type. interpolation_steps is used as a hint to certain projections. hatchpattern. contains_point(point. generates a Path that can be used in a repeated hatching pattern.path. That is. Masionobe. if one path completely encloses the other. If codes is None. that this path should be linearly interpolated immediately before drawing. masked array or Python sequence. density=6) Given a hatch specifier. This attribute is primarily an implementation detail and is not intended for public use. theta2. the path will be transformed before performing the test. it is the number of spline segments to make. density is the number of lines per unit square. classmethod arc(theta1.1 Create a new path with the given vertices and codes. If n is provided. classmethod hatch(hatchpattern. xmax. n=None. code_type alias of uint8 contains_path(path.Matplotlib. Drawing an elliptical arc using polylines. the path will be transformed before performing the test. get_extents(transform=None) Returns the extents (xmin. when True. 662 Chapter 49. If transform is not None. matplotlib path . These two arrays must have the same length in the first dimension. they will be converted to NaNs which are then handled correctly by the Agg PathIterator and other consumers of path data. If n is not provided. Unlike computing the extents on the vertices alone. treats the path as if it was filled. vertices will be treated as a series of line segments.0. filled=True) Returns True if this path intersects a given Bbox. filled. such as Polar. L. this algorithm will take into account the curves and deal with control points appropriately. vertices is an Nx2 numpy float array. Does not currently handle interpolating curves. the number of spline segments is determined based on the delta between theta1 and theta2. intersects_path() will return True. transform=None) Returns True if the path contains the given point. clip=None. Needed as a hint for the snapping algorithm. intersects_path() will return True. perform simplification. Additionally. each polygon has no MOVETO instructions or curves. code). y2) defining a rectangle in which to clip the path. If width and height are both non-zero then the lines will be simplified so that vertices outside of (0. iter_segments(transform=None. use the should_simplify member variable.1. See Also: 49. treats the paths as if they were filled. this method can provide a number of standard cleanups and conversions to the path. y1.1 intersects_path(other. Release 1. classmethod make_compound_path(*args) (staticmethod) Make a compound path from a list of Path objects. simplify=None. auto-snap to pixels. transformed(transform) Return a transformed copy of the path. Each polygon is an Nx2 array of vertices. snapping. height) will be clipped. where vertices is a sequence of 1 . and if False. snap=False. curve segments will be returned as curve segments. matplotlib. In other words. force stroke_width: the width of the stroke being drawn. transform: if not None. snap: if None.path 663 . That is. filled. to reduce fuzziness of rectilinear lines. the given affine transformation will be applied to the path. This is useful for displaying in backends that do not support compound paths or Bezier curves. will remove all NaNs from the path and insert MOVETO commands to skip over them. clip: if not None. If False. and code is one of the Path codes. if one path completely encloses the other. 0). x2. Return object is a Path to_polygons(transform=None. to remove vertices that do not affect the appearance of the path. remove_nans: if True.0. don’t snap. perform no simplification. height=0) Convert this path to a list of polygons. remove_nans=True. If True. classmethod make_compound_path_from_polys(XY) (static method) Make a compound path object to draw a number of polygons with equal numbers of sides XY is a (numpolys x numsides x 2) numpy array of vertices. Each iteration returns a 2-tuple (vertices.3 coordinate pairs. If None. all curves will be converted to line segments. Only polygons (not curves) are supported. filled=True) Returns True if this path intersects another given path. width=0. If False. such as GDK. stroke_width=1. curves: If True.0. (width.Matplotlib. curves=True) Iterates over all of the curve segments in the path. simplify: if True. when True. must be a four-tuple (x1. Don. classmethod unit_regular_asterisk(numVertices) (staticmethod) Returns a Path for a unit regular asterisk with the given numVertices and radius of 1.TransformedPath A specialized path class that will cache the transformed result and automatically update when the transform changes. This uses 4 splines around the circle using the approach presented here: Lancaster. classmethod unit_circle() (staticmethod) Returns a Path of the unit circle. classmethod unit_rectangle() (staticmethod) Returns a Path of the unit rectangle from (0. Don.0. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines. classmethod unit_regular_polygon(numVertices) 664 Chapter 49. 0) to (1. 1). This uses 8 splines around the circle using the approach presented here: Lancaster. The circle is approximated using cubic Bezier curves.0.Matplotlib. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines. Release 1.transforms. matplotlib path . centered at (0. 0). classmethod unit_circle_righthalf() (staticmethod) Returns a Path of the right half of a unit circle.1 40 30 20 10 0 2 1 0 1 2 matplotlib. The circle is approximated using cubic Bezier curves. 0. trans) matplotlib.path. y. Release 1. n=None) (staticmethod) Returns a wedge of the unit circle from angle theta1 to angle theta2 (in degrees).1.0. trans.path_in_path() path_in_path(a.path. classmethod unit_regular_star(numVertices.1 (staticmethod) Returns a Path for a unit regular polygon with the given numVertices and radius of 1. filled) 49. simplify. matplotlib. atrans.path 665 . innerCircle=0. path. y. it is the number of spline segments to make. matplotlib.path. matplotlib.convert_path_to_polygons() convert_path_to_polygons(path. snap. b. trans. trans) matplotlib.5) (staticmethod) Returns a Path for a unit regular star with the given numVertices and radius of 1. paths.path. offsets. centered at (0. If n is provided.Matplotlib. classmethod wedge(theta1. r.path. btrans) matplotlib. If n is not provided. clip. returns the bounding box that encapsulates all of them.path.path_intersects_path() path_intersects_path(p1. centered at (0. height) matplotlib.cleanup_path() cleanup_path(path. remove_nans. 0). width. theta2. 0). curves) matplotlib.get_path_collection_extents(*args) Given a sequence of Path objects.get_path_extents() get_path_extents(path. transforms. offsetTrans. p2) matplotlib.point_in_path() point_in_path(x. trans.point_in_path_collection() point_in_path_collection(x. the number of spline segments is determined based on the delta between theta1 and theta2.path.0.path. Release 1.0.Matplotlib. matplotlib path .1 666 Chapter 49. though these can be overridden with keyword args.acorr(x.arange(0. **kwargs) call signature: acorr(x. maxlags is a positive integer detailing the number of lags to show. y = np. detrend=mlab. If normed = True. **kwargs) Return value is a tuple (lags. vlines() rather than plot() is used to draw vertical lines from the origin to the acorr. The default value of None will return all 2imeslen(x) − 1 lags.sin(x) plt.pyplot as plt x = np. pylab combines pyplot with numpy into a single namespace. c. If usevlines is True. which are Line2D properties.detrend_none. the plot style is determined by the kwargs. line) where: •lags are a length 2*maxlags+1 lag vector •c is the 2*maxlags+1 auto correlation vector •line is a Line2D instance returned by plot() The default linestyle is None and the default marker is ’o’. e. normalize the data by the autocorrelation at 0-th lag.CHAPTER FIFTY MATPLOTLIB PYPLOT 50.pyplot Provides a MATLAB-like plotting framework.correlate() with mode = 2. c. **kwargs) Plot the autocorrelation of x. 0.: import numpy as np import matplotlib. This is convenient for interactive work.g. but for programming it is recommended that the namespaces be kept separate.1). normed=True. y) matplotlib. usevlines=True. hold=None. Data are plotted as plot(lags. Otherwise. x is detrended by the detrend callable (default no normalization). maxlags=10. The cross correlation is performed with numpy.plot(x. 667 . 5.pyplot.1 matplotlib. 6 0.0.0 0. **kwargs) Keyword arguments: 668 Chapter 50.Matplotlib. Release 1.4 0. textcoords=’data’.00 0. matplotlib pyplot . xy.15 0. Example: 0.10 0. and acorr() below. b) where •linecol is the LineCollection •b is the x-axis.15 0.annotate(*args.05 0. xytext=None.8 0.2060 1. c.2 0. Example: xcorr() above. arrowprops=None.0 0.20 0.05 0.1 The return value is a tuple (lags.10 0.260 40 20 0 20 40 60 40 20 0 20 40 60 Additional kwargs: hold = [True|False] overrides default hold state matplotlib.pyplot. See Also: plot() or vlines() For documentation on valid kwargs. linecol. xycoords=’data’. **kwargs) call signature: annotate(s. any key for matplotlib. y location xytext. (If xytext = None. Otherwise.Matplotlib.05 is 5% any key for matplotlib.5) default is bounding box of the text default is None default is 2 points default is 2 points default is text size (in points) default is 1. defaults to xy. and if textcoords = None. Release 1. shrink=0. 0. If the dictionary has a key arrowstyle.0. matplotlib.5.1. a FancyArrowPatch instance is created with the given dictionary and is drawn. defaults to xycoords). a YAArow patch instance is created and drawn.pyplot 669 . shrink will shorten the arrow so the tip and base are shink percent of the distance d away from the endpoints. Valid keys for YAArow are Key width frac headwidth shrink Description the width of the arrow in points the fraction of the arrow length occupied by the head the width of the base of the arrow head in points oftentimes it is convenient to have the arrowtip and base a bit away from the text and point being annotated.patches. arrowprops.1 Annotate the x. if not None.PathPatch xycoords and textcoords are strings that indicate the coordinates of xy and xytext. If d is the distance between the text and annotated point. ie. y point xy with text s at x.lines.Line2D) for the arrow that connects annotation to the point. 50.polygon ? Valid keys for FancyArrowPatch are Key arrowstyle connectionstyle relpos patchA patchB shrinkA shrinkB mutation_scale mutation_aspect ? Description the arrow style the connection style default is (0.patches. is a dictionary of line properties (see matplotlib. Matplotlib. If False.1 is upper. the annotation will always be drawn regardless of its position. matplotlib pyplot .1 is lower left of axes and 1. values will be added to the bottom-left and if negative. even in cartesian plots.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. Transform) | Patch | None ] 670 Chapter 50. The default is None. the annotation will only be drawn when the xy is inside the axes.0 is lower left of figure and 1. xycoords=’axes points’ You may use an instance of Transform or Artist. which behave as True only if xycoords is”data”. See Annotating Axes for more details. If True. Additional kwargs are Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path Description unknown float (0. right points from lower left corner of axes pixels from lower left corner of axes 0. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system. Release 1. The annotation_clip attribute contols the visibility of the annotation when it goes outside the axes area.1 Property ‘figure points’ ‘figure pixels’ ‘figure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘offset points’ ‘polar’ Description points from the lower left corner of the figure pixels from the lower left corner of the figure 0.Bbox instance [True | False] [ (Path. If a ‘points’ or ‘pixels’ option is specified.transforms.0. r for the annotation. Note that if you are using a polar axes. values will be subtracted from the top-right.0 transparent through 1.-5).1 is upper right use the coordinate system of the object being annotated (default) Specify an offset (in points) from the xy value you can specify theta. Eg: # 10 points to the right of the left border of the axes and # 5 points below the top border xy=(10. y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion.1. y.Figure instance a matplotlib. dy.Matplotlib.pyplot 671 . Optional kwargs control the arrow properties: 50. dx. y. **kwargs) call signature: arrow(x. dy. dx.font_manager. hold=None. Release 1. y) to (x + dx.pyplot. y + dy). matplotlib.0.1 Table 50. **kwargs) Draws arrow on specified axis from (x.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.arrow(x.1 – continued from color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.figure. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number matplotlib. 1 3 2 1 0 1 2 3 41 0 1 2 3 4 5 arc3 arc angle3 arrowstyle arc angle angle angle angle 3 2 1 0 1 2 3 4 51> − 672 fancy simple wedge wedge wedge 0 1 2 3 4 5 Chapter 50. matplotlib pyplot . Release 1.Matplotlib.0. otherwise treat tight as False.pyplot. use tight scaling if the only artist is an image. Additional kwargs: hold = [True|False] overrides default hold state matplotlib. or ‘none’ for no color a matplotlib. or None for default. axis=’both’. let the locator and margins expand the view limits. or ‘none’ for no color mpl color spec.0. False turns it off. matplotlib. it performs the autoscaling on the specified axis or axes. if autoscaling for either axis is on.figure. The tight setting is retained for future autoscaling until it is explicitly changed.1. enable: [True | False | None] True (default) turns autoscaling on. axis: [’x’ | ‘y’ | ‘both’] which axis to operate on. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Matplotlib. 50.autogen_docstring(base) Autogenerated wrappers will get their docstring from a base function with an addendum.Bbox instance [True | False] [ (Path. None leaves the autoscaling state unchanged. tight=None) Convenience method for simple axis view autoscaling. set view limits to data limits. and then.pyplot 673 .’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Exception occurred rendering plot.transforms. default is ‘both’ tight: [True | False | None] If True. Release 1. matplotlib.pyplot.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Example: Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. if False. if None.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. It turns autoscaling on or off.autoscale(enable=True. or None for default. See help(colormaps) for more information matplotlib. 1) units. this line will always span the horizontal extent of the axes.75) Valid kwargs are Line2D properties.. •axes(h) where h is an axes instance makes h the current axis. hold=None. Return value is the Line2D instance.0. kwarg axisbg frameon sharex sharey polar Examples: •examples/pylab_examples/axes_demo.25. eg.py uses sharex and sharey. **kwargs) Add an axes at position rect specified by: •axes() by itself creates a default full subplot(111) window axis.0=right but the y location is in data coordinates. 0.axhline(y=0. **kwargs) Accepts color [True|False] otherax otherax [True|False] Desctiption the axes background color display the frame? current axes shares xaxis attribute with otherax current axes shares yaxis attribute with otherax use a polar axes? Axis Horizontal Line Draw a horizontal line at y from xmin to xmax. width. matplotlib pyplot . the horizontal extent is in axes coords: 0=left.py places custom axes. matplotlib.5=middle. xmin=0. •draw a thick red hline at y = 0 that spans the xrange >>> axhline(linewidth=4.5 that spans the the middle half of the xrange >>> axhline(y=. Release 1. xmin=0.pyplot. •examples/pylab_examples/shared_axis_demo.pyplot. even if you change them. With the default values of xmin = 0 and xmax = 1. •axes(rect. and can be used to control the line properties. bottom. color=’r’) •draw a default hline at y = 1 that spans the xrange >>> axhline(y=1) •draw a default hline at y = . kwargs are the same as kwargs to plot. regardless of the xlim settings. xmax=1. xmax=1. **kwargs) call signature: axhline(y=0. xmin=0.1 Returns None. matplotlib. An Axes instance is returned. default white.autumn() set the default colormap to autumn and apply to current image if any. xmax=0. with the exception of ‘transform’: 674 Chapter 50.Matplotlib. axisbg is the background color for the axis. 1. height] in normalized (0.pyplot. with the set_xlim() command. That is. Eg.5. axisbg=’w’) where rect = [left.axes(*args. 0.figure. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.1. stride) float distance in points or callable pick function fn(artist. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x. matplotlib.Matplotlib.Bbox instance [True | False] [ (Path.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder Description unknown float (0. Release 1.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.transforms.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.Transform instance a url string [True | False] 1D array 1D array any number See Also: 50.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.transforms.’ | ’.0 transparent through 1.pyplot 675 . Draw a horizontal span (rectangle) from ymin to ymax. **kwargs) Axis Horizontal Span. regardless of the xlim settings.patches.1 axhspan() for example plot and source code Additional kwargs: hold = [True|False] overrides default hold state matplotlib. facecolor=’0. xmin=0.Polygon instance. That is. eg.0. matplotlib pyplot . this always spans the xrange.25.0=right but the y location is in data coordinates. 1.75 that spans the horizontal extent of the axes >>> axhspan(0. ymax. 0.5=middle. the horizontal extent is in axes coords: 0=left.75. xmax=1.pyplot. alpha=0. with the set_xlim() command. 0. xmax=1. Examples: •draw a gray rectangle from y = 0.5) Valid kwargs are Polygon properties: 676 Chapter 50. xmin=0.25-0.axhspan(ymin. ymax.5’. **kwargs) call signature: axhspan(ymin.Matplotlib. Release 1. With the default values of xmin = 0 and xmax = 1. hold=None. even if you change them. Return value is a matplotlib. y coords are in data units and x coords are in axes (relative 0-1) units. 0.figure. xmax.Bbox instance [True | False] [ (Path.transforms.1. xmax. matplotlib. ymax].Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.axis(*v. ymin. **kwargs) Set/Get the axis properties: >>> axis() returns the current axes limits [xmin. Release 1.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Additional kwargs: hold = [True|False] overrides default hold state matplotlib. >>> axis(v) sets the min and max of the x and y axes. >>> axis(’off’) turns off the axis lines and labels. >>> axis(’equal’) 50. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. with v = [xmin.Matplotlib.pyplot 677 . or None for default. or ‘none’ for no color mpl color spec. ymin. or None for default. or ‘none’ for no color a matplotlib. ymax].pyplot.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Example: Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. 5 1.0.0 0.Matplotlib.xmin) or (ymax .5 1. matplotlib pyplot .0 0. >>> axis(’auto’) and >>> axis(’normal’) are deprecated.0 changes limits of x or y axis so that equal increments of x and y have the same length. >>> axis(’scaled’) achieves the same result by changing the dimensions of the plot box instead of the axis data limits.0 0. Release 1.0 1.01. They restore default behavior. Note this is slightly different than in MATLAB.5 0. axis limits are automatically scaled to make the data fit comfortably within the plot box.5 0. >>> axis(’tight’) changes x and y axis limits such that all data is shown.5 2.0 1.1 2.0 0. a circle is circular.5 1. If all data is already shown. 678 Chapter 50.ymin). it will move it to the center of the figure without modifying (xmax . >>> axis(’image’) is ‘scaled’ with the axis limits equal to the data limits. ymax=1. with the exception of ‘transform’: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes Description unknown float (0. and can be used to control the line properties. with the set_ylim() command.1 if len(*v)==0. kwargs are the same as kwargs to plot. ymin=0. Return value is the Line2D instance. Eg.pyplot 679 . xmax. regardless of the ylim settings. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 50. •draw a thick red vline at x = 0 that spans the yrange >>> axvline(linewidth=4. 0.transforms. matplotlib. ymin=0..0 opaque) [True | False] [True | False] an Axes instance a matplotlib. ymin=0. ymax=1. **kwargs) call signature: axvline(x=0. you can pass in xmin. the vertical extent is in axes coords: 0=bottom. **kwargs) Axis Vertical Line Draw a vertical line at x from ymin to ymax. xmax.5.25.Bbox instance [True | False] [ (Path.0 transparent through 1. That is.5=middle. Release 1.0.0=top but the x location is in data coordinates. matplotlib. The xmin. 1.1. ymin. color=’r’) •draw a default vline at x = 1 that spans the yrange >>> axvline(x=1) •draw a default vline at x = . even if you change them. ymax as kwargs selectively to alter just those limits without changing the others. this line will always span the vertical extent of the axes. ymax tuple is returned See Also: xlim(). ymax=0.75) Valid kwargs are Line2D properties.and y-limits individually.pyplot. hold=None. ymin.axvline(x=0.5 that spans the the middle half of the yrange >>> axvline(x=. With the default values of ymin = 0 and ymax = 1.Matplotlib. eg. ylim() For setting the x. with the 680 Chapter 50. stride) float distance in points or callable pick function fn(artist.transforms.’ | ’.pyplot.Matplotlib. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. Draw a vertical span (rectangle) from xmin to xmax. regardless of the ylim settings. Release 1. eg.0. ymax=1. xmax.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. ymax=1.Transform instance a url string [True | False] 1D array 1D array any number See Also: axhspan() for example plot and source code Additional kwargs: hold = [True|False] overrides default hold state matplotlib.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.figure.1 data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder 2D array (rows are x. ymin=0. even if you change them. **kwargs) Axis Vertical Span. With the default values of ymin = 0 and ymax = 1. hold=None.axvspan(xmin. x coords are in data units and y coords are in axes (relative 0-1) units. ymin=0. this always spans the yrange. matplotlib pyplot . xmax. **kwargs) call signature: axvspan(xmin. 0=top but the y location is in data coordinates.5) Valid kwargs are Polygon properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder See Also: axhspan() for example plot and source code Additional kwargs: hold = [True|False] overrides default hold state matplotlib.55. 1.Bbox instance [True | False] [ (Path.patches.figure. or ‘none’ for no color mpl color spec. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or ‘none’ for no color a matplotlib.25 to 1. bottom=None. That is.1. hold=None.25.Polygon instance. Return value is the matplotlib.pyplot. or None for default.55 that spans the yrange of the axes >>> axvspan(1. width=0.80000000000000004. Release 1.Matplotlib. the vertical extent is in axes coords: 0=bottom. facecolor=’g’.5=middle.0. **kwargs) 50. or None for default. Examples: •draw a vertical green translucent rectangle from x=1.1 set_ylim() command. alpha=0. height.bar(left. matplotlib. 1.transforms. 0.pyplot 681 Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number .Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. while align = ‘center’ interprets these values as the y coordinates of the bar centers. height. bottom and top edges) left. True sets it to log scale For vertical bars.‘vertical’ | ‘horizontal’ tation log [False|True] False (default) leaves the orientation axis as-is. ecolor and capsize may ror_kw be specified here rather than as independent kwargs. For horizontal bars. linewidth. so they can also have shape 2xN for independent specification of lower and upper errors. None means use default linewidth. bottom. right. **kwargs) Make a bar plot with rectangles bounded by: left. bottom=0. or candlestick plots. edgecolor. align = ‘edge’ aligns bars by their left edges in left. The optional arguments color. will be used to generate errorbars on the bar chart yerr if not None. bottom + height (left. and yerr can be either scalars or sequences of length equal to the number of bars. height.0. Required arguments: Argument left height Description the x coordinates of the left sides of the bars the heights of the bars Optional keyword arguments: KeyDescription word width the widths of the bars botthe y coordinates of the bottom edges of the bars tom color the colors of the bars edgethe colors of the bar edges color linewidthwidth of bar edges. width=0. left + width.patches. Detail: xerr and yerr are passed directly to errorbar(). will be used to generate errorbars on the bar chart ecolor specifies the color of any errorbar cap(default 3) determines the length in points of the error bar caps size erdictionary of kwargs to be passed to errorbar method. xerr if not None. Release 1. align ‘edge’ (default) | ‘center’ orien. xerr. matplotlib pyplot . align = ‘edge’ aligns bars by their bottom edges in bottom. and bottom can be either scalars or sequences Return value is a list of matplotlib. width. while align = ‘center’ interprets these values as the x coordinates of the bar centers.Matplotlib.1 call signature: bar(left.8.Rectangle instances. 0 means don’t draw edges. 682 Chapter 50. This enables you to use bar as the basis for stacked bar charts. barbs(*args. **kw) Plot a 2-D field of barbs.1 Other optional kwargs: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Example: A stacked bar chart. **kw) Arguments: X. or None for default. barb(X. see pivot kwarg) U. **kw) U. call signatures: barb(U.Bbox instance [True | False] [ (Path.Matplotlib. C. or None for default. barb(X. or ‘none’ for no color a matplotlib. V. V. V. Y: The x and y coordinates of the barb locations (default is head of barb. Y. barb(U.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.1. Y. matplotlib.pyplot 683 .pyplot.0. **kw) C.figure. or ‘none’ for no color mpl color spec. V: give the x and y components of the barb shaft 50. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. Release 1. Additional kwargs: hold = [True|False] overrides default hold state matplotlib.transforms. **kw) U. V. V. However this parameter will override facecolor. 684 Chapter 50. Keyword arguments: length: Length of the barb in points. Default is 9 pivot: [ ‘tip’ | ‘middle’ ] The part of the arrow that is at the grid point. then X and Y will be expanded with numpy. flagcolor: [ color | color sequence ] Specifies the color of any flags on the barb. flagcolor has no effect. Default is ‘tip’ barbcolor: [ color | color sequence ] Specifies the color all parts of the barb except any flags. This parameter is analagous to the edgecolor parameter for polygons. U. which can be used instead. However this parameter will override facecolor.meshgrid(). the arrow rotates about this point. If C has been set. If X and Y are absent. C may be masked arrays. which can be used instead. This parameter is analagous to the facecolor parameter for polygons. Y are not supported at present. but masked X.Matplotlib.1 80 70 60 50 Scores 40 30 20 10 0 G1 Scores by group and gender Men Women G2 G3 G4 G5 C: an optional array used to map colors to the barbs All arguments may be 1-D or 2-D arrays or sequences. If this is not set (and C has not either) then flagcolor will be set to match barbcolor so that the barb has a uniform color. matplotlib pyplot . they will be generated as a uniform grid. the other parts of the barb are scaled against this. Release 1.0. and if len(X) and len(Y) match the column and row dimensions of U. If U and V are 2-D arrays but X and Y are 1-D. hence the name pivot. • ‘half’ .) Default is False Barbs are traditionally used in meteorology as a way to plot the speed and direction of wind observations.pyplot 685 . the barbs give more quantitative information about the vector magnitude by putting slanted lines or a triangle for various increments in magnitude.1 sizes: A dictionary of coefficients specifying the ratio of a given feature to the length of the barb.half barbs (Default is 5) • ‘full’ .width of a flag. Default is True barb_increments: A dictionary of increments specifying values to associate with different parts of the barb. If True. If False. but can technically be used to plot any two dimensional vector quantity. 50. the half-line is offset from the end of the barb so that it can be easily distinguished from barbs with a single full line.radius of the circle used for low magnitudes fill_empty: A flag on whether the empty barbs (circles) that are drawn should be filled with the flag color. the magnitude is rounded to the nearest multiple of the half-barb increment.full barbs (Default is 10) • ‘flag’ . 10. There is only.Matplotlib. After those come full lines (barbs).height (distance from shaft to top) of a flag or full barb • ‘width’ .0.flags (default is 50) flip_barb: Either a single boolean flag or an array of booleans.1. using the standard increments of 50. An array (which should be the same size as the other data arrays) indicates whether to flip for each individual barb. the magnitude is simply truncated to the next lowest multiple. ever at most 1 half line. full/half barbs) • ‘height’ . These features include: • ‘spacing’ . The smallest increment is a half line. as show schematically below: : /\ \ : / \ \ : / \ \ \ : / \ \ \ : ------------------------------ The largest increment is given by a triangle (or “flag”). matplotlib. Release 1. The magnitude for the barb shown above would nominally be 65. of course. If they are not filled. Single boolean indicates whether the lines and flags should point opposite to normal for all barbs. As opposed to arrows.space between features (flags. which give vector magnitude by the length of the arrow. Normal behavior is for the barbs and lines to point right (comes from wind barbs having these features point towards low pressure in the Northern Hemisphere. Default is False rounding: A flag to indicate whether the vector magnitude should be rounded when allocating barb components. they will be drawn such that no color is applied to the center. If the magnitude is small and only needs a single half-line and no full lines or triangles. twice the width of a full barb • ‘emptybarb’ . Only those values one wishes to override need to be included. and 5. Only those values one wishes to override need to be included. **kwargs) call signature: 686 Chapter 50.Figure instance an id string any string [’solid’ | ‘dashed’. matplotlib pyplot . Additional PolyCollection keyword arguments: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized snap transform url urls visible zorder Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. height=0. hold=None.Bbox instance [True | False] [ (Path.pyplot. ‘dashdot’.1 linewidths and edgecolors can be used to customize the barb. width. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib.transforms. left=None. ‘dotted’ | (offset.figure. Release 1. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib.0.Matplotlib.barh(bottom.80000000000000004. 0 2 0. bottom and top edges) bottom. Required arguments: Argument bottom width Description the vertical positions of the bottom edges of the bars the lengths of the bars Optional keyword arguments: 50.0 0. left=0. left + width.Rectangle instances.pyplot 687 . width.0 1.5 2 1. matplotlib.5 6 1.patches.5 4 3 2 1 0 1 2 barh(bottom.0 2 0.5 0 0. height.5 4 1.5 4 1. Release 1. bottom + height (left.5 4 3 2 1 0 1 2 1. bottom. height=0.1 6 2.1.0 4 6 6 4 2 0 2 4 6 1.8.0 6 6 4 2 0 2 4 6 1.5 2 0 0.0 4 0. width. right.0. **kwargs) Make a horizontal bar plot with rectangles bounded by: left. and left can be either scalars or sequences Return value is a list of matplotlib.Matplotlib. or candlestick plots. while align = ‘center’ interprets these values as the y coordinates of the bar centers.1 2.0 0.0 1.0 0.5 0. if not None.5 4 Keyword height left color edgecolor linewidth xerr yerr ecolor capsize align log 3 Description 2 1 0 1 2 the heights (thicknesses) of the bars the x coordinates of the left edges of the bars the colors of the bars the colors of the bar edges width of bar edges. matplotlib pyplot . True sets it to log scale Setting align = ‘edge’ aligns bars by their bottom edges in bottom. Release 1. will be used to generate errorbars on the bar chart specifies the color of any errorbar (default 3) determines the length in points of the error bar caps ‘edge’ (default) | ‘center’ [False|True] False (default) leaves the horizontal axis as-is. The optional arguments color.Matplotlib. 0 means don’t draw edges.0. and yerr can be either scalars or sequences of length equal to the number of bars.5 1. xerr. linewidth. None means use default linewidth. 688 Chapter 50. This enables you to use barh as the basis for stacked bar charts.5 1. will be used to generate errorbars on the bar chart if not None.0 1. edgecolor. pyplot. sym=’b+’.5.pyplot.Bbox instance [True | False] [ (Path.boxplot(x. The whiskers extend 50.1 other optional kwargs: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib.5. whis=1. widths=None. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or ‘none’ for no color mpl color spec. whis=1. toggle state. patch_artist=False) Make a box and whisker plot for each column of x or each vector in sequence x. Release 1.box(on=None) Turn the axes box on or off according to on.pyplot 689 . matplotlib.Matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Additional kwargs: hold = [True|False] overrides default hold state matplotlib. vert=1. widths=None. with a line at the median. or None for default. notch=0. The box extends from the lower to upper quartile values of the data. or ‘none’ for no color a matplotlib.1. See help(colormaps) for more information matplotlib. If on is None. matplotlib.bone() set the default colormap to bone and apply to current image if any. positions=None.figure.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. patch_artist=False. vert=1. on may be a boolean or a string. sym=’+’.transforms.pyplot. bootstrap=None. notch=0. ‘on’ or ‘off’. positions=None. hold=None) call signature: boxplot(x. or None for default.0. bootstrap (default None) specifies whether to bootstrap the confidence intervals around the median for notched boxplots.2.broken_barh(xranges.BrokenBarHCollection properties: 690 Chapter 50.. •vert = 1 (default) makes the boxes vertical. ywidth) kwargs are matplotlib. •patch_artist = False (default) produces boxes with the Line2D artist •patch_artist = True produces boxes with the Patch artist Returns a dictionary mapping each component matplotlib.. x is an array or a sequence of vectors. R. matplotlib pyplot . If bootstrap==None. widths is either a scalar or a vector and sets the width of each box. 1967)..Matplotlib.W. W.. no bootstrapping is performed. whis (default 1. xranges. Flier points are those past the end of the whiskers. **kwargs) call signature: broken_barh(self...A. •notch = 0 (default) produces a rectangular box plot.0. 0.1 from the box to show the range of the data. They extend to the most extreme data point within ( whis*(75%-25%) ) data range. and Larsen. hold=None.collections. Values between 1000 and 10000 are recommended. yrange. Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. and notches are calculated using a Gaussian-based asymptotic approximation (see McGill. bootstrap specifies the number of times to bootstrap the median to determine it’s 95% confidence intervals.lines. yrange. Release 1. **kwargs) The default is 0. xwidth) sequence of (ymin. positions (default 1. The ticks and limits are automatically set to match the positions. This seems goofy. but that’s how MATLAB did it.5) defines the length of the whiskers as a function of the inner quartile range. J.n) sets the horizontal positions of the boxes. or of the boxplot to a list of the A collection of horizontal bars spanning yrange with a sequence of xranges.. •notch = 1 will produce a notched box plot sym (default ‘b+’) is the default symbol for flier points. Required arguments: Argument xranges yrange Description sequence of (xmin.Line2D instances created. •vert = 0 makes horizontal boxes. Tukey.pyplot. Enter an empty string (‘’) if you don’t want to show fliers.5.15*(distance between extreme positions) if that is smaller. 1978. Otherwise. and Kendall and Stuart. Bbox instance [True | False] [ (Path.Figure instance an id string any string Continued on next page Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label 50.Matplotlib. Release 1.0. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib. matplotlib.pyplot 691 .1 200 150 100 50 0 50 100 1 Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.transforms.1.figure. ’green’) Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. ’red’. where cs is a ContourSet object returned by contour.clabel(CS.html colors: • if None. the color of each label matches the color of the corresponding contour 692 Chapter 50. matplotlib pyplot .Matplotlib. **kwargs) adds labels to line contours in cs. *args. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number these can either be a single argument.cla() Clear the current axes matplotlib. ‘dashdot’. Optional keyword arguments: fontsize: See http://matplotlib. **kwargs) only labels contours listed in v. ie: facecolors = ’black’ or a sequence of arguments for the various bars. **kwargs) call signature: clabel(cs.5 – continued from previous page linestyle or linestyles or dashes [’solid’ | ‘dashed’. ie: facecolors = (’black’.sf. v.net/fonts. clabel(cs.1 Table 50. Release 1.pyplot.pyplot.0. ‘dotted’ | (offset. Default is ‘%1.Matplotlib.pyplot 693 . all labels will be plotted in this color • if a tuple of matplotlib color args (string. and any other key will select a label location). colors = ‘r’ or colors = ‘red’.0. label rotations will always be plus or minus 90 degrees from level. Click the first button near a contour to add a label. but only if labels are not inline. inline_spacing: space in pixels to leave on each side of label when placing inline. the keyboard can be used to select label locations (enter to end label placement. contour labels will be placed manually using mouse clicks.1. This spacing will be exact for labels at locations where the contour is straight. less so for labels on curved contours. fmt[level]=string) manual: if True.g. matplotlib. this can be a dictionary matching contour levels with arbitrary strings to use for each contour level (i. 50. click the second button (or potentially both mouse buttons at once) to finish adding labels. rgb. The third button can be used to remove the last label added. Default is True.e.. e. Release 1. different labels will be plotted in different colors in the order specified inline: controls whether the underlying contour is removed or not. etc). rightside_up: if True (default). fmt: a format string for the label. Defaults to 5. delete or backspace act like the third mouse button. Alternatively.3f’ Alternatively. float.1 200 150 100 50 0 50 100 1 • if one string color. therefore this can be used if aspect of the axes changes. use. If you want to set the clim of multiple images. ClabelText recalculates rotation angles of texts during the drawing time.get_images(): im.pyplot.clim(vmin=None. the image min/max respectively will be used for color scaling. 0.clf() Clear the current figure matplotlib. vmax=None) Set the color limits of the current image To apply clim to all axes images do: clim(0.5) If either vmin or vmax is None.close(*args) Close a figure window close() by itself closes the current figure 694 Chapter 50. ClabelText class (instead of matplotlib.0. for example: for im in gca().1 200 150 100 50 0 50 100 1 use_clabeltext: if True (default is False). 0.Matplotlib. Additional kwargs: hold = [True|False] overrides default hold state matplotlib.set_clim(0. matplotlib pyplot .05) matplotlib.Text) is used to create labels.pyplot. Release 1.pyplot. Release 1. pad_to=None.1. sides=’default’. sides=’default’. a power 2 is most efficient. Fc=0. noverlap=0. NFFT=256. Fs=2. The default value is 256. matplotlib. Fc=0. |P xy |2 P xx Pyy (50.1 120 100 80 60 40 20 0 20 close(num) closes figure number num close(h) where h is a Figure instance.Matplotlib. **kwargs) 1 cohere() the coherence between x and y. scale_by_freq=None.cohere(x. hold=None. pad_to=None. detrend = mlab.0. Fs=2. Coherence is the normalized cross spectral density: C xy = Keyword arguments: NFFT: integer The number of data points used in each block for the FFT.1) 50. closes that figure close(’all’) closes all the figure windows matplotlib. y. window=<function window_hanning at 0x3a178c0>. **kwargs) call signature: cohere(x. Must be even.pyplot. NFFT=256. y. noverlap=0.window_hanning. detrend=<function detrend_none at 0x3a1c668>.pyplot 695 . scale_by_freq=None.detrend_none. window = mlab. matplotlib pyplot .get_window(). etc. scipy. allowing for more detail. To create window vectors see window_hanning(). window: callable or ndarray A function or a vector of length NFFT. The default is window_hanning(). freqs.1 1 100 50 0 50 100 150 200 Fs: scalar The sampling frequency (samples per time unit). While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). noverlap: integer The number of points of overlap between blocks. window_none().signal(). and detrend_linear(). It is used to calculate the Fourier frequencies.bartlett(). in cycles per time unit. which specifies the number of data points used. detrend_mean(). The default value is 0 (no overlap). scipy. The default is 696 Chapter 50.signal. If a function is passed as the argument. in matplotlib is it a function. The default value is 2. This can be different from NFFT. pad_to: integer The number of points to which the data segment is padded when performing the FFT.hamming().0. Release 1. where the detrend parameter is a vector.Matplotlib. detrend: callable The function applied to each segment before fft-ing. but you can use a custom function as well. This corresponds to the n parameter in the call to fft(). this can give more points in the plot. numpy. numpy. The pylab module defines detrend_none(). numpy. designed to remove the mean or linear trend.blackman(). Unlike in MATLAB. it must take a data segment as an argument and return the windowed version of the segment. f ). which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.0.1 1 100 50 0 50 100 150 200 None. This allows for integration over the returned frequency values. where f are the frequencies of the coherence vector. kwargs are applied to the lines. References: •Bendat & Piersol – Random Data: Analysis and Measurement Procedures. Fc: integer The center frequency of x (defaults to 0). The return value is a tuple (Cxy.1. John Wiley & Sons (1986) kwargs control the Line2D properties of the coherence plot: 50. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. ‘onesided’ forces the return of a one-sided PSD. which gives density in units of Hz^-1. while ‘twosided’ forces two-sided. Release 1. matplotlib. which returns one-sided for real data and both for complex data. Default gives the default behavior. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. The default is True for MATLAB compatibility.pyplot 697 .Matplotlib. Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string 698 Chapter 50.1 200 150 100 50 0 50 100 1 2 3 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label Description unknown float (0. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.0 transparent through 1.Matplotlib.0. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. matplotlib pyplot .figure. Release 1.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.Bbox instance [True | False] [ (Path.transforms. 0. to which the colorbar applies. which sets the default to the current image. ax=None. stride) float distance in points or callable pick function fn(artist. cax=None.transforms. etc. all but the first are also method signatures for the colorbar() method: colorbar(**kwargs) colorbar(mappable. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. Function signatures for the pyplot interface.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.pyplot 699 . this argument is mandatory for the colorbar() method but optional for the colorbar() function. cax=cax.1. **kw) Add a colorbar to a plot. Release 1.1 linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [ ’-’ | ’--’ | ’-. keyword arguments: cax None | axes object into which the colorbar will be drawn ax None | parent axes object from which space for a new colorbar axes will be stolen 50.Matplotlib. ax=ax. **kwargs) arguments: mappable the Image.colorbar(mappable=None.Transform instance a url string [True | False] 1D array 1D array any number Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. matplotlib.’ | ’. ContourSet. **kwargs) colorbar(mappable.pyplot. **kwargs) colorbar(mappable.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. 0.15 if horizontal.05 if vertical.15. fraction of original axes between colorbar and new image axes 1. fraction of original axes to use for colorbar 0. ratio of long to short dimensions colorbar properties: 700 Chapter 50.Matplotlib.0. Release 1.1 race interrupted Jim Bill 0 50 100 150 seconds since start 200 Additional keyword arguments are of two kinds: axes properties: Property orientation fraction pad shrink aspect Description vertical or horizontal 0. fraction by which to shrink the colorbar 20. matplotlib pyplot .0. 50.50 0 -0.5 1.0 3 2 1 0 1 2 0. draw lines at color boundaries.Description erty ex[ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] If not ‘neither’.g.000 0.range values. matplotlib.500 0 1.5 0.5 1. ‘%.1. for[ None | format string | Formatter object ] If None.50 1. drawedges [ False | True ] If true. that is used.0 0. Release 1.0 0. spac. e. The following will probably be useful only in the context of indexed colors (that is.0.3f’.0 1. when the mappable has norm=NoNorm()).00 0 00 -1.0 Prop. the mat ScalarFormatter is used. If a format string is given.5 2. An alternative Formatter object may be given instead. ticks [ None | list of ticks | Locator object ] If None.[ ‘uniform’ | ‘proportional’ ] Uniform spacing gives each discrete ing color the same space.pyplot 701 .Matplotlib. or other unusual circumstances. make pointed tend end(s) for out-of. ticks are determined automatically from the input.1 Simplest default with labels 1. These are set for a given colormap using the colormap set_under and set_over methods. proportional makes the space proportional to the data interval. If the colorbar is too tall (or a horizontal colorbar is too wide) use a smaller value of shrink.500 0. For each region delimited by adjacent entries in boundaries. for example. If mappable is a ContourSet. do not use any of the axes properties kwargs.Matplotlib. Note that the shrink kwarg provides a simple way to keep a vertical colorbar.1 Single color -0.0.Description erty bound. returns: Colorbar instance. For more precise control.5 1.5 1.colormaps() matplotlib provides the following colormaps. In this case.5 00 -1.0 1. you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn.000 negative contours dashed 1.0 0. ColorbarBase.0 3 2 -0.pyplot. see also its base class.5 2.000 1.00 0 1 0 1 2 Prop. Call the set_label() method to label the colorbar. but it is a manual method requiring some trial and error.500 1.0 00 0. matplotlib. from being taller than the axes of the mappable to which the colorbar is attached.None or a sequence aries valNone or a sequence which must be of length 1 less than the sequence ues of boundaries.5 0. Release 1. its extend kwarg is included automatically. matplotlib pyplot . 702 Chapter 50. the color mapped to the corresponding value in values will be used.0 0. 1.5 1.0 0.0 1. matplotlib.5 00 3 2 1 0 1 2 .5 2.000 .negative contours solid 1.500 -1.5 0.0 •autumn •bone •cool •copper •flag •gray •hot •hsv •jet •pink •prism •spring •summer •winter •spectral 50.000 1.1 Single color0.0 0.0.0 00 0.00 0 -0.500 1.5 1.Matplotlib.pyplot 703 0. Release 1. 5 1.pyplot.1 0.5 0.0 00 0.hot) or post-hoc using the corresponding pylab interface function: imshow(X) hot() jet() In interactive mode. this will update the colormap allowing you to see which one works best for your data.0 0.colors() This is a do-nothing function to provide you with help on how matplotlib handles colors. cmap=cm.000 Crazy lines 0. Commands which take color arguments can use several formats to specify the colors.0 0.0 3 2 -0. you can use a single letter 704 Chapter 50. pcolor.0 1. matplotlib pyplot . either as a keyword argument: imshow(X.000 1. matplotlib.5 1.500 -1. scatter.5 2. etc.5 00 1.00 0 1 0 1 2 You can set the colormap for an image.500 1.0. Release 1. For the basic builtin colors.Matplotlib. 3098.4 0.G.2 2 3 1 1. matplotlib.40.6 1. for example: color = ’red’. 0.4 0.6 Alias ‘b’ ‘g’ ‘r’ ‘c’ ‘m’ ‘y’ ‘k’ ‘w’ Color blue green red cyan magenta yellow black white For a greater range of colors. where each of R.0 1.B tuple.2 0.2 1. You can also use any legal html name for a color.5 1.G.0 0.2 0.B are in the range [0.8 1. color = ’burlywood’ color = ’chartreuse’ The example below creates a subplot with a dark slate gray background subplot(111.1.2 0.4 1.0 0.0 0.2 -0. Release 1.pyplot 705 .3098)) 50.1843.8 0.0 1.6 3 2 1 0 1.5 0.5 2.5 1.8 1.0 Lines with colorbar 0. 0.0 -1.Matplotlib.1]. You can specify the color using an html hex string.1 2. axisbg=(0. as in: color = ’#eeefff’ or you can pass an R.4 0.0 -0.8 0. you have two options.0.0 0. 4 0. matplotlib pyplot .Event.1 0. Release 1.02 0.04 0.06 0.8 0.backend_bases.0 0. The following events are recognized •‘button_press_event’ •‘button_release_event’ •‘draw_event’ •‘key_press_event’ •‘key_release_event’ •‘motion_notify_event’ •‘pick_event’ •‘resize_event’ •‘scroll_event’ 706 Chapter 50. color=’#afeeee’) matplotlib.6 0.060 1.2 0.0.00 s1 and s2 1 2 time 3 4 5 coherence 10 20 30 Frequency 40 50 Here is an example that creates a pale turqoise title: title(’Is this the best color?’.connect(s.00 0.04 0.08 0. The signature of func is: def func(event) where event is a matplotlib.pyplot.Matplotlib.02 0. func) Connect event with string s to func. y) coordinates of the surface contour(Z.N) contour N automatically-chosen levels.Y. on_press) matplotlib. the variables event. event. Return value is a connection id that can be used with mpl_disconnect(). Example usage: def on_press(event): print ’you pressed’. contourf() differs from the MATLAB version in that it does not draw the polygon edges.button. contour(Z.Z) X. call signatures: contour(Z) make a contour plot of an array Z.contour(*args.1. and additionally.pyplot 707 . add line contours with calls to contour(). V) fill the (len(V)-1) regions between the values in V contour(Z. the variable event.pyplot.inaxes will be set to the Axes the event occurs is over. See KeyEvent and MouseEvent for more info. To draw edges. •‘axes_leave_event’ •‘close_event’ For the location events (button and key press/release).Y.ydata will be defined.ydata cid = canvas.1 •‘figure_enter_event’.Z. respectively. Y specify the (x.Y. **kwargs) 50.V) contour(X. event. function signatures and return values are the same for both versions.Matplotlib..Z. contour(X. event. Release 1.N) contour(X.mpl_connect(’button_press_event’. matplotlib. •‘axes_enter_event’.xdata. •‘figure_leave_event’. The level values are chosen automatically..xdata and event.0.. Except as noted.V) draw contour lines at the values specified in sequence V contourf(. This is the mouse location in data coords. **kwargs) contour() and contourf() draw contour lines and filled contours. if the mouse is over the axes. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range.0] is the center of the pixel. The locator is used to determine the contour levels if they are not given explicitly via the V argument. the colormap specified by cmap will be used.Normalize instance for scaling data values to colors. the position of Z[0. rgb. the default MaxNLocator is used. and Z must be arrays with the same dimensions. levels [level0. locator: [ None | ticker.Matplotlib.-1]. location (0.origin will be used. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None.) returns a QuadContourSet object.imshow(): it gives the outer pixel boundaries.set_over() methods. see below for more details. level1.Locator subclass ] If locator is None. If a tuple of matplotlib color args (string.. 708 Chapter 50. Y.0].colors. contour levels are automatically added to one or both ends of the range so that all data are included. If a string. a default Colormap is used. norm: [ None | Normalize ] A matplotlib. Release 1. not a corner.set_under() and matplotlib.. y1) is the position of Z[-1.. float. different levels will be plotted in different colors in the order specified. In this case. linewidth. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’.0. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None.0).colors. the first value of Z will correspond to the lower left corner. and (x1. matplotlib pyplot .colors. but can be set via matplotlib. This keyword is not active if X and Y are specified in the call to contour.1 Use keyword args to control colors..y0.y1) ] If origin is not None. y0) is the position of Z[0. extent: [ None | (x0. C = contour(. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None. then (x0.Colormap. like ‘r’ or ‘red’. leveln] A list of floating point numbers indicating the level curves to draw. cmap .x1.. If ‘image’.. Z may be a masked array. the rc value for image. all levels will be plotted in this color..pyplot. If norm is None and colors is None. origin. then extent is interpreted as in matplotlib. This keyword is not active if X and Y are specified in the call to contour. the default linear scaling is used. If cmap is None and colors is None.Colormap. etc). . If origin is None. but filled contouring may not handle internal masked regions correctly. X. all levels will be plotted with this linewidth.1 xunits. If a number.pyplot. the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array. Note: contourf fills intervals that are closed at the top. that is. for boundaries z1 and z2. then that minimum value will be included in the lowest interval. the ‘solid’ is used. so this option may be removed. Except as noted. If a tuple. call signatures: contour(Z) make a contour plot of an array Z. Examples: Additional kwargs: hold = [True|False] overrides default hold state matplotlib.Matplotlib. respectively. function signatures and return values are the same for both versions. This may never actually be advantageous. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. no subdivision of the domain. 50. then the linestyle specified in contour.units. the default width in lines. **kwargs) contour() and contourf() draw contour lines and filled contours. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points.negative_linestyle in matplotlibrc will be used. If contour is using a monochrome colormap and the contour level is less than 0.contourf(*args. add line contours with calls to contour().linewidth in matplotlibrc is used. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. If this iterable is shorter than the number of contour levels it will be repeated as necessary.pyplot 709 .0.ConversionInterface. matplotlib. The level values are chosen automatically. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. contourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0. contourf() differs from the MATLAB version in that it does not draw the polygon edges. different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. To draw edges. contour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None. Release 1.1. Release 1. Y specify the (x.0 0.50 1.Z.0 contour(X. but filled contouring may not handle internal masked regions correctly.. and Z must be arrays with the same dimensions. y) coordinates of the surface contour(Z.Y.Y. cmap .. 710 Chapter 50. **kwargs) Use keyword args to control colors.0 0.5 1.V) draw contour lines at the values specified in sequence V contourf(. matplotlib pyplot .00 0 00 -1.500 0 1..Z.V) contour(X. origin. Z may be a masked array.000 0.0 3 2 1 0 1 2 0. X. contour(Z.50 0 -0.Y.5 2. Y.1 Simplest default with labels 1.N) contour N automatically-chosen levels.5 0. linewidth..N) contour(X. V) fill the (len(V)-1) regions between the values in V contour(Z.Z) X.0.5 1. see below for more details.Matplotlib.0 1.. matplotlib.5 1.0 0.origin will be used.0 3 2 -0. .500 1.000 negative contours dashed 1. etc).0).Normalize instance for scaling data values to colors.0 1.00 0 1 0 1 2 C = contour(. different levels will be plotted in different colors in the order specified.0 00 0..1 Single color -0. If a tuple of matplotlib color args (string.. level1. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None.colors. the colormap specified by cmap will be used.Matplotlib.0 0. float.pyplot 711 . location (0. the rc value for image.. If norm is None and colors is None. levels [level0. 50.. all levels will be plotted in this color. rgb.5 0. norm: [ None | Normalize ] A matplotlib. If cmap is None and colors is None.5 2.500 0. the first value of Z will correspond to the lower left corner.) returns a QuadContourSet object.1. If a string. the default linear scaling is used.0..000 1.5 00 -1. like ‘r’ or ‘red’. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None. a default Colormap is used. Release 1. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None.5 1. If ‘image’. leveln] A list of floating point numbers indicating the level curves to draw. set_under() and matplotlib.x1.1 Single color0. then extent is interpreted as in matplotlib.00 0 1 0 1 2 This keyword is not active if X and Y are specified in the call to contour. then (x0.y0. contour levels are automatically added to one or both ends of the range so that all data are included. extent: [ None | (x0.500 0.5 00 -1.imshow(): it gives the outer pixel boundaries.colors.Matplotlib.Locator subclass ] If locator is None.ConversionInterface.5 1. xunits.Colormap. The locator is used to determine the contour levels if they are not given explicitly via the V argument.0 0. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’.0].units.0 3 2 -0.negative contours solid 1. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. y0) is the position of Z[0. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range.0.0 1.pyplot.5 0.000 1. the position of Z[0. Release 1. not a corner. If origin is None.colors. but can be set via matplotlib. y1) is the position of Z[-1.0 00 0.Colormap. This keyword is not active if X and Y are specified in the call to contour. and (x1.5 1. matplotlib pyplot .-1].set_over() methods.000 . the default MaxNLocator is used.500 1.5 2. In this case. 712 Chapter 50.y1) ] If origin is not None. locator: [ None | ticker.0] is the center of the pixel.0 0. 000 Crazy lines 0.00 0 1 0 1 2 contour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None.1. Release 1.0 0.0 1. If a tuple. then the linestyle specified in contour. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If a number.5 00 1. If this iterable is shorter than the number of contour levels it will be repeated as necessary.5 2. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. no subdivision of the domain. the default width in lines.0 00 0. different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. matplotlib.5 1.500 -1.0 3 2 -0.1 0.500 1.5 1. If contour is using a monochrome colormap and the contour level is less than 0.linewidth in matplotlibrc is used.000 1. the ‘solid’ is used.pyplot 713 .0 0. contourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0.Matplotlib. all levels will be plotted with this linewidth. This may 50.0.negative_linestyle in matplotlibrc will be used.5 0. 2 0. that is.6 3 2 1 0 1.cool() set the default colormap to cool and apply to current image if any.Matplotlib.0 0.2 1.0. Chunking introduces artifacts at the chunk boundaries unless antialiased is False.pyplot.0 0.4 0.2 2 3 1 1.5 0.0 1.0 Lines with colorbar 0.4 0. Note: contourf fills intervals that are closed at the top. Release 1.8 1.1 2.5 1. for boundaries z1 and z2.0 0.0 -0.4 1. matplotlib pyplot .40.4 0.pyplot.8 0.6 never actually be advantageous. See help(colormaps) for more information 714 Chapter 50.2 -0.2 0.6 1. Examples: Additional kwargs: hold = [True|False] overrides default hold state matplotlib.0 1.8 0. so this option may be removed. then that minimum value will be included in the lowest interval.5 1.2 0.copper() set the default colormap to copper and apply to current image if any.5 2.0 0.8 1.0 -1. the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array. See help(colormaps) for more information matplotlib. matplotlib.pyplot. noverlap=0. in cycles per time unit.8 matplotlib. The vectors x and y are divided into NFFT length segments. hold=None.pyplot . scale_by_freq=None. Fc=0.1.Matplotlib. **kwargs) call signature: csd(x. Fs=2.detrend_none. pad_to=None. The default value is 2. with a scaling to correct for power loss due to windowing.csd(x. detrend=mlab. Release 1. detrend: callable The function applied to each segment before fft-ing. scale_by_freq=None. designed to re50. It is used to calculate the Fourier frequencies. a power 2 is most efficient. pad_to=None. Returns the tuple (Pxy. y. sides=’default’. y. Fs=2. noverlap=0. **kwargs) The cross spectral density P xy by Welch’s average periodogram method. The default value is 256.6 0. window=<function window_hanning at 0x3a178c0>.6 1. and 10 log10 |P xy | is plotted. The product of the direct FFTs of x and y are averaged over each segment to compute P xy . freqs). Must be even. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT.0 0.0. Each segment is detrended by function detrend and windowed by function window. Fs: scalar The sampling frequency (samples per time unit). window=mlab. Fc=0. NFFT=256. NFFT=256. sides=’default’.1 Nonsense (3 masked regions) 2 sentence length anomaly 1 0 1 2 33 2 1 0 1 2 word length anomaly 1.2 1.window_hanning. freqs.2 verbosity coefficient 715 0. P is the cross spectrum (complex valued). detrend=<function detrend_none at 0x3a1c668>. in matplotlib is it a function. This can be different from NFFT. noverlap: integer The number of points of overlap between blocks.bartlett().get_window().0 1. The default value is 0 (no overlap).5 0. numpy.0. To create window vectors see window_hanning(). it must take a data segment as an argument and return the windowed version of the segment. window: callable or ndarray A function or a vector of length NFFT. The pylab module defines detrend_none().5 0. The default is None. and detrend_linear(). Release 1.0 1. scipy.signal.5 1.5 -1.5 move the mean or linear trend. window_none().Matplotlib. matplotlib pyplot . but you can use a custom function as well. If a function is passed as the argument.signal(). which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. scipy.5 -1. numpy. where the detrend parameter is a vector.0 0. numpy.1 Listed colors (3 masked regions) 2 1 0 1 2 33 2 1 0 1 2 0. 0 1.hamming(). While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). detrend_mean(). Unlike in MATLAB.0 -0. this can give more points in the plot. etc. This corresponds to the n parameter in the call to fft(). allowing for more detail.0 0. pad_to: integer The number of points to which the data segment is padded when performing the FFT.blackman(). Default gives the default behavior. The default is window_hanning(). which specifies the number of data points used. which returns one-sided for real data and both 716 Chapter 50.0 0. which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.0 0. ‘onesided’ forces the return of a one-sided PSD.0 opaque) [True | False] [True | False] 50. This allows for integration over the returned frequency values.0 for complex data.5 1.0 0. John Wiley & Sons (1986) kwargs control the Line2D properties: Property agg_filter alpha animated antialiased or aa Description unknown float (0.1. matplotlib.5 0.pyplot 717 . References: Bendat & Piersol – Random Data: Analysis and Measurement Procedures. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency.500 0 1.5 1.1 Simplest default with labels 1.50 1.0 3 2 1 0 1 2 0.0.Matplotlib.50 0 -0.0 transparent through 1.5 2. while ‘twosided’ forces two-sided.00 0 00 -1.000 0. The default is True for MATLAB compatibility.0 1. Release 1. Fc: integer The center frequency of x (defaults to 0). which gives density in units of Hz^-1. transforms. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Bbox instance [True | False] [ (Path. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. If ax doesn’t exist.Matplotlib.0.Transform instance a url string [True | False] 1D array 1D array any number Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. Release 1. an error will be raised.1 axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder an Axes instance a matplotlib. delaxes(): delete the current axes 718 Chapter 50. stride) float distance in points or callable pick function fn(artist.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.figure.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.pyplot.’ | ’. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.delaxes(*args) delaxes(ax): remove ax from the current figure.transforms. matplotlib pyplot . 0 00 0. xerr=None. elinewidth=None. yerr=None.5 1. barsabove=False.0 3 2 -0. xerr=None. xlolims=False. ecolor=None.errorbar(x.Matplotlib.00 0 1 0 1 2 matplotlib. on_press) #.draw() redraw the current figure matplotlib.5 0. xuplims=False.5 1. Vertical errorbars are plotted if yerr is not None. matplotlib.5 00 -1.1 Single color -0. uplims=False.1. xuplims=False) Plot x versus y with error deltas in yerr and xerr.500 1. Release 1.0 0.mpl_connect(’button_press_event’. uplims=False.pyplot. elinewidth=None.000 negative contours dashed 1. fmt=’-‘. capsize=3. xlolims=False. 50. Horizontal errorbars are plotted if xerr is not None.disconnect(cid) disconnect callback id cid Example usage: cid = canvas. barsabove=False.0 0.0.500 0.pyplot 719 . yerr=None. lolims=False.000 1..pyplot. capsize=3. hold=None. fmt=’-’.5 2. ecolor=None. **kwargs) call signature: errorbar(x.pyplot. lolims=False. y.mpl_disconnect(cid) matplotlib.later canvas..0 1. y. or 2xN array-like ] If a scalar number.Matplotlib. Release 1.5 00 -1.0. use the linewidth. and yerr can all be scalars. which plots a single error bar at x.5 1. will plot the errorbars above the plot symbols. If a sequence of shape 2xN. errorbars are drawn +/.500 0. y. For example.0 1. elinewidth: scalar the linewidth of the errorbar lines.value.000 . matplotlib pyplot . only the errorbars are plotted. Default is below. len(N) array-like object. In that case a caret symbol is used to indicate this.0 00 0. or an Nx1 array-like object. lolims/uplims/xlolims/xuplims: [ False | True ] These arguments can be used to indicate that a value gives only upper/lower limits. if None. this 720 Chapter 50. Nx1.5 1. capsize: scalar the size of the error bar caps in points barsabove: [ True | False ] if True.1 Single color0.negative contours solid 1. Optional keyword arguments: xerr/yerr: [ scalar | N. y.0 0. for example.0 0.5 2.000 1. This is used for adding errorbars to a bar plot.5 0.0 3 2 -0. All other keyword arguments are passed on to the plot command for the markers. xerr. use the marker color. errorbars are drawn at -row1 and +row2 fmt: ‘-‘ The plot format symbol.500 1. ecolor: [ None | mpl color ] a matplotlib color arg which gives the color the errorbar lines. If fmt is None. If None. lims-arguments may be of the same type as xerr and yerr.00 0 1 0 1 2 x. 0 0. mec.500 -1.000 Crazy lines 0.transforms.0 0.5 1. ms and mew are aliases for the longer property names.y. mew=4) where mfc.yerr = rand(3.Bbox instance [True | False] [ (Path. y.pyplot 721 . markeredgecolor.10) errorbar(x.0 3 2 -0.0 transparent through 1.1 0. valid kwargs for the marker properties are Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle Description unknown float (0.5 00 1. ms=20.0 1.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. Release 1.500 1.0.00 0 1 0 1 2 code makes big red squares with thick green edges: x.000 1.5 0. marker=’s’. mfc=’red’. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] 50. markerfacecolor.Matplotlib.5 2.0 00 0.1. mec=’green’. markersize and markeredgewith.5 1. yerr. matplotlib. Release 1. stride) float distance in points or callable pick function fn(artist.Transform instance a url string [True | False] 1D array 1D array any number Returns (plotline.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. matplotlib pyplot . caplines. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Matplotlib.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. **kwargs) call signatures: 722 Chapter 50.1 dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.figimage(*args.pyplot.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.transforms. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.0.’ | ’.figure. Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. y plot markers and/or line caplines: list of error bar cap Line2D instances barlinecols: list of LineCollection instances for the horizontal and vertical error ranges. barlinecols): plotline: Line2D instance x. 8 0. **kwargs) adds a non-resampled array X to the figure.4 1.1 2.5 1.0 0. matplotlib.4 0.5 1.0 -0.1.2 0. Release 1.0 0.2 -0.0.0 -1.0 Lines with colorbar 0.2 0. figimage(X.4 0.Matplotlib.40.6 figimage(X. yo) with pixel offsets xo.2 1.0 1. xo. assume RGB •If X is MxNx4.8 1. assume RGBA Optional keyword arguments: 50.0 0.6 3 2 1 0 1.pyplot 723 .4 0.5 0.5 2.2 0. assume luminance (grayscale) •If X is MxNx3.8 0. yo.2 2 3 1 1.6 1. X must be a float array: •If X is MxN.8 1.0 0.0 1. image.FigureImage instance is returned. Additional kwargs are Artist kwargs passed on to :class:‘~matplotlib. loc. alpha the alpha blending value.cm.colors. Release 1. labels. An matplotlib.6 0. the x and y image offset in pixels a matplotlib. Defaults to the rc image.Normalize instance. The default is normalization().1]. This scales luminance -> 0-1 vmin|vmax used to scale a luminance image to 0-1.Matplotlib.image.2 verbosity coefficient 0. If either is None. default is None ori[ ‘upper’ | ‘lower’ ] Indicates where the [0.origin value figimage complements the axes image (imshow()) which will be resampled to fit the current axes.0 0. the min and max are of the luminance values will be used. you can define an Axes with size [0.figlegend(handles.0. matplotlib pyplot .jet.1. If None. eg cm. If you want a resampled image to fill the entire figure.ColorMap instance.cmap value norm a matplotlib.2 2 1 0 1 2 word length anomaly 1. Note if you pass a norm instance.pyplot.0.1 Nonsense (3 masked regions) 2 sentence length anomaly 1 0 1 2 33 Keyword xo or yo cmap 1.0] index of the array is in the upper gin left or lower left corner of the axes.8 Description An integer. the settings for vmin and vmax will be ignored. **kwargs) 724 Chapter 50.FigureImage‘Addition kwargs: hold = [True|False] overrides default hold state matplotlib. default to the rc image.6 1. s. fontdict=None.figtext(*args. 50. **kwargs) Add text to figure at location x.5 -1.Matplotlib. ’label3’). y.0.5 0.0 1.pyplot 725 . **kwargs) Call signature: figtext(x. line3). (’label1’. Release 1. ’label2’.5 0.0 0.0 -0.pyplot.0 0.1.5 1. Example: figlegend( (line1. line2. See text() for the meaning of the other arguments. 0 1.5 -1.5 Place a legend in the figure. ’upper right’ ) See Also: legend() matplotlib.0 1.1 Listed colors (3 masked regions) 2 1 0 1 2 33 2 1 0 1 2 0. labels a sequence of strings handles a sequence of Line2D or Patch instances loc can be a string or an integer specifying the legend location A matplotlib.Legend instance is returned. matplotlib.0 0. y (relative 0-1 coords).legend. 080 45 55 65 75 850 s1 and s2 1 2 time 3 4 5 CSD (db) 10 20 30 Frequency 40 50 kwargs control the Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod Description unknown float (0. matplotlib pyplot .08 0. Release 1.Bbox instance [True | False] [ (Path.02 0.0 transparent through 1.Matplotlib.figure.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.06 0.1 0.04 0.font_manager.Figure instance a matplotlib.06 0.02 0.00 0. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.0.04 0.transforms.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] 726 Chapter 50. figure(num=None.Figure instance. Release 1. frameon=True.pyplot . facecolor=None. facecolor=’w’.figure. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number matplotlib. defaults to rc figure. matplotlib. edgecolor=None. edgecolor=’k’) Create a new figure and return a matplotlib. dpi=80.Figure’>.figure. make it active and return a reference to it.9 – continued from multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x. defaults to rc figure. dpi=None.pyplot. make sure you explicitly call “close” on the figures you are not using.facecolor the border color. If num = None.1 Table 50.dpi the background color. figsize=(8. 6). the figure number will be incremented and a new figure will be created. Numbering starts at 1. MATLAB style: figure(1) If you are creating many figures.edgecolor 727 50.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. **kwargs) call signature: figure(num=None. The returned figure objects have a number attribute holding this number. defaults to rc figure. because this will enable pylab to properly clean up the memory.0. and figure(num) already exists. FigureClass=<class ‘matplotlib.figsize resolution. defaults to rc figure. If num is an integer.1. Optional keyword arguments: Keyword figsize dpi facecolor edgecolor Description width x height in inches.Matplotlib. figsize=None. If figure(num) does not exist it will be created. 728 shade a region between 0 and y along x. see plot() for details on the argument parsing. matplotlib. to plot a polygon with vertices at x. 0. y pairs with an optional color format string.fill(x1. eg.y. ’r’) Return value is a list of Patch instances that were added.0 rcParams defines the default values. ’b’ ) An arbitrary number of x.5 3.4 in y 1.8 0. Additional kwargs will be passed on to your figure init function. which can be modified in the matplotlibrc file FigureClass is a Figure or derived class that will be passed on to new_figure_manager() in the backends which allows you to hook custom Figure classes into the pylab interface.0 0. color groups can be specified: ax.2 0.5 0. If you would like to fill below a curve.4 0. x2.: ax.4 Simplest errorbars.5 1.2 1. args is a variable length argument.pyplot. y2.fill(x.40.5 4. The same color strings that plot() supports are supported by the fill format string. **kwargs) call signature: fill(*args.0 0. y1. y. **kwargs) Plot filled polygons. y in blue. allowing for multiple x. use Chapter 50.0. Release 1.0 3.fill(*args. For example.5 2.6 0. ’g’.1 1.0 2. matplotlib pyplot .0 1.2 in x.0 0.Matplotlib. 0.2 0. Matplotlib.0 Hor.. log y 6 0 2 4 1 10 100 10-1 0 2 4 10-2 2 6 0 2 4 6 50.0 2Mixed sym.0 0.0 0.2 6 0.1 1.pyplot 729 .0 0.5 2 fill_between() The closed kwarg will close the polygon when True (default).5 0.8 0. Release 1.5 Vert. matplotlib. V asymmetric 1. kwargs control the Polygon properties: Variable errorbars 0. symmetric 1.5 H.1.0.5 0.0 0.5 2 0 2 4 1.6 0. symmetric 1.4 0. Bbox instance [True | False] [ (Path. or ‘none’ for no color mpl color spec. or ‘none’ for no color a matplotlib. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Chapter 50. matplotlib pyplot Transform instance a url string [True | False] .Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.transforms.Matplotlib.1 730 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. or None for default. Release 1.0.figure. or None for default. Otherwise.1 0.pyplot. it is a a N length numpy boolean array and the fill will only happen over the regions where where==True interpolate If True.0. interpolate=False.0 Additional kwargs: hold = [True|False] overrides default hold state matplotlib.5 0.2 0.1 Example: 0. y2=0.4 0.0 0. y1.Matplotlib.8 1.0 0. y1. kwargs keyword args passed on to the PolyCollection 50.1 0.3 0.6 0.2 0.fill_between(x. hold=None. where=None.1. the start and end points of the filled region will only occur on explicit values in the x array. matplotlib. interpolate between the two lines to find the precise point of intersection. y2=0. **kwargs) Create a PolyCollection filling the regions between y1 and y2 where where==True x an N length np array of the x data y1 an N length scalar or np array of the y data y2 an N length scalar or np array of the y data where if None. If not None. where=None. **kwargs) call signature: fill_between(x. default to fill between everywhere. Release 1.4 0.6 0.2 0.pyplot 731 . transforms. matplotlib pyplot .Figure instance an id string any string [’solid’ | ‘dashed’. **kwargs) call signature: 732 Chapter 50. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib.1 kwargs control the Polygon properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized snap transform url urls visible zorder Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.0. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number See Also: fill_betweenx() for filling between two sets of x-values Additional kwargs: hold = [True|False] overrides default hold state matplotlib. where=None.Bbox instance [True | False] [ (Path. ‘dashdot’.Matplotlib. ‘dotted’ | (offset. Release 1.figure. x1. hold=None.pyplot. x2=0.fill_betweenx(y. 5 1.5 0. **kwargs) Create a PolyCollection filling the regions between x1 and x2 where where==True y an N length np array of the y data x1 an N length scalar or np array of the x data x2 an N length scalar or np array of the x data where if None.0 x 1.5 1.5 1.5 1.0 1.1.0.5 0. x2=0.5 0. where=None.0 1.0 0.0 0.0 1.5 2.0 1. matplotlib.1 between y1 andbetween y1 and 1 y2 between y1 and 0 1.0 0.5 0.5 1.0 0.0 0.pyplot 733 .0 0. Release 1.0 0.5 1.5 2. If not None. it is a a N length numpy boolean array and the fill will only happen over the regions where where==True kwargs keyword args passed on to the PolyCollection kwargs control the Polygon properties: Property agg_filter alpha animated antialiased or antialiaseds array axes Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance Continued on next page 50.0 1.5 2. x1. default to fill between everywhere.0 0.0 0.0 0.0 0.5 1.0 fill_between(y.Matplotlib. 1 Table 50.Bbox instance clip_on [True | False] clip_path [ (Path. Only return artists of class type 734 Chapter 50. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number See Also: fill_between() for filling between two sets of y-values Additional kwargs: hold = [True|False] overrides default hold state matplotlib. match=None) Recursively find all :class:matplotlib.pyplot.Artist instances contained in self. ‘dashdot’. match=None) pyplot signature: findobj(o=gcf().Matplotlib.11 – continued from previous page clim a length 2 sequence of floats clip_box a matplotlib.transforms.figure. Release 1.findobj(o=None. matplotlib pyplot .Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’.artist. match can be •None: return all objects contained in artist (including artist) •function with signature boolean = match(artist) used to filter matches •class instance: eg Line2D. Transform) | Patch | None ] cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib.0. ‘dotted’ | (offset. 1.5 1.5 1.gci() Get the current ScalarMappable instance (image or patch collection).10]) or: plot(t.5 masked 2. and the commands pcolor() and scatter() create Collection instances.0 1.pyplot.5 1. The current image is an attribute of the current axes.pyplot.5 0.s) set(gca(). or None if no images or patch collections have been defined.0 0.0 fill between where 0. or the nearest earlier axes in the current figure that contains an image.5 0.pyplot.0 Now regions with y2>1 are1.0 1.5 0.pyplot. [0. This can be used to control axis properties either using set or the Axes methods.pyplot 735 . The commands imshow() and figimage() create Image instances.0 matplotlib.0 0.5 1.gca(**kwargs) Return the current axis instance. matplotlib.set_xlim([0.0 0. Release 1. setting the xaxis range: plot(t.gcf() Return a reference to the current figure.0 0.flag() set the default colormap to flag and apply to current image if any.1 1.0 0.0.0 1. See help(colormaps) for more information matplotlib. ’xlim’. for example.5 1.5 0. matplotlib.s) a = gca() a.5 2. 50.10]) matplotlib.Matplotlib.0 1. 5 2.ginput(*args. mouse_pop=3.get_fignums() Return a list of existing figure numbers.Matplotlib. removing points.0 matplotlib.pyplot. 3 for right. terminating the inputs) can be overriden via the arguments mouse_add. Right clicking cancels last input. mouse_add=1.get_plot_commands() matplotlib.0 0. 736 Chapter 50.get_current_fig_manager() matplotlib. If n is zero or negative. mouse_pop and mouse_stop.1 1. matplotlib.0 0. This will wait for n clicks from the user and return a list of the coordinates of each click. Release 1. If timeout is zero or negative. **kwargs) call signature: ginput(self. 2 for middle.pyplot.pyplot.0. timeout=30. mouse_stop=2) Blocking call to interact with the figure.5 0.pyplot.0 0. accumulate clicks until a middle click (or potentially both mouse buttons at once) terminates the input.5 1.0 0. that give the associated mouse button: 1 for left. matplotlib pyplot .0 1. does not timeout. n=1. The buttons used for the various actions (adding points. show_clicks=True.5 1. 0 x 0. kawrgs are used to set the grid line properties.Matplotlib. the enter key terminates input and any other key (not already used by the window manager) selects a point.0 1. If kwargs are supplied. See help(colormaps) for more information matplotlib.) If b is None and len(kwargs)==0.5 0.5 0.5 0.5 0. or ‘both’ to control whether major tick grids.pyplot. b is a boolean.grid(b=None. which can be ‘major’ (default).0 0. **kwargs) call signature: grid(self.0 0.0 0.5 1.0 0.5 1.0.01.0 1.01. ‘on’ or ‘off’.5 1..5 The keyboard can also be used to select points in case your mouse does not have one or more of the buttons.pyplot. b may also be a string. matplotlib.0 0. remove last point).5 1. minor tick grids. ‘minor’.5 1.5 0.5 0.0 0.0 1. eg: 50. Release 1.01.0 1.1 between y1 andbetween y1 and 1 y2 between y1 and 0 2.0 0.1.5 1. it is assumed that you want a grid and b is thus set to True.5 2.5 2. (For MATLAB compatibility.5 1.0 0.pyplot 737 . or both are affected.e. matplotlib. The delete and backspace keys act like right clicking (i. which=’major’. which=’major’.0 1.0 1. toggle the grid state.5 1.5 1. b=None.gray() set the default colormap to gray and apply to current image if any. **kwargs) Set the axes grids on or off. 1 2.0 0.5 0.5 ax.Bbox instance [True | False] [ (Path.0.5 0.0 fill between where 1. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. linestyle=’-’.0 0.01.0 transparent through 1.transforms.5 2.0 0.01.5 0. Release 1.0 > 10.5 y2 are 1.5 1. matplotlib pyplot .0 opaque) [True | False] [True | False] an Axes instance a matplotlib.5 masked 1.0 1.Matplotlib.0 0.5 1.Figure instance 738 Chapter 50. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.5 Now regions with0.5 1.figure.0 1.0 1.0 0. linewidth=2) Valid Line2D kwargs are Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure Description unknown float (0.5 1.grid(color=’r’. 1 fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. mincnt=None. xscale = ’linear’. Release 1. yscale=’linear’. C = None. gridsize=100. (If C is specified.transforms. extent=None. y are 1-D sequences of the same length. norm=None.’ | ’.hexbin(x. mincnt=None. vmin=None.mean. bins=None. marginals=True **kwargs) Make a hexagonal binning plot of x versus y. bins = None.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. y. If C is specified.pyplot. If C is None (the default).’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.y[i]). alpha=None.1. this is a histogram of the number of occurences of the observations at (x[i].y[i]). linewidths=None. These values are accumulated for each hexagonal bin and then reduced according to reduce_C_function. vmax=None. vmax=None. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. which defaults to numpy’s mean function (np. it specifies values at the coordinate (x[i].mean). y. alpha=None. yscale = ’linear’. xscale=’linear’. linewidths=None. where x. gridsize = 100. edgecolors=’none’ reduce_C_function = np.) 50. cmap=None. vmin=None. N.Matplotlib. hold=None.0. marginals=False.Transform instance a url string [True | False] 1D array 1D array any number matplotlib. edgecolors=’none’. it must also be a 1-D sequence of the same length as x and y. matplotlib. stride) float distance in points or callable pick function fn(artist. norm=None. **kwargs) call signature: hexbin(x. C=None. cmap=None. reduce_C_function=<function mean at 0x2b55320>.pyplot 739 . Alternatively.0. y and/or C may be masked arrays. bins: [ None | ‘log’ | integer | sequence ] If None. Release 1. If an integer. the color of each hexagon directly corresponds to its count value. divide the counts in the specified number of bins.1 20 15 10 5 0 0. no binning is applied. If ‘log’. default is 100. Internally.5 1. in which case only unmasked points will be plotted. scale: [ ‘linear’ | ‘log’ ] Use a linear or log10 scale on the vertical axis. matplotlib pyplot . Optional keyword arguments: gridsize: [ 100 | integer ] The number of hexagons in the x-direction.0 x. log10 (i + 1) is used to determine the hexagon color. only display cells with more than mincnt number of points in the cell 740 Chapter 50. xscale: [ ‘linear’ | ‘log’ ] Use a linear or log10 scale on the horizontal axis. the values of the lower bound of the bins to be used.Matplotlib. gridsize can be a tuple with two elements specifying the number of hexagons in the x-direction and the y-direction. and color the hexagons accordingly.5 1. mincnt: None | a positive integer If not None.0 2. The corresponding number of hexagons in the y-direction is chosen such that the hexagons are approximately regular.5 3. use a logarithmic scale for the color map. If a sequence of values.0 Message length ---> Minimum Message Length Model length Data length Total message length 0.0 Model complexity ---> 2. colors. Note if you pass a norm instance. If either are None. Here are the standard descriptions of all the Collection kwargs: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.1. draws the edges in the same color as the fill color. Other keyword arguments controlling the Collection properties: edgecolors: [ None | mpl color | color sequence ] If ‘none’. Note that this is a tuple. the min and max of the color array C is used.transforms. as it avoids unsightly unpainted pixels between the hexagons. or None the alpha value for the patches linewidths: [ None | scalar ] If None. right. Release 1.1 marginals: True|False if marginals is True.cm. your settings for vmin and vmax will be ignored. If None.cmap. as required by RegularPolyCollection.1. If a matplotlib color arg or sequence of rgba tuples. alpha: scalar between 0 and 1. This is the default. xscale and yscale.Matplotlib.Bbox instance [True | False] [ (Path. y. matplotlib. defaults to rc image.Colormap instance. vmin/vmax: scalar vmin and vmax are used in conjunction with norm to normalize luminance data.Normalize instance is used to scale luminance data to 0. x. The default assigns the limits based on gridsize. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples Continued on next page 741 50.0. plot the marginal density as colormapped rectagles along the bottom of the x-axis and left of the y-axis extent: [ None | scalars (left. If None. Other keyword arguments controlling color mapping and normalization arguments: cmap: [ None | Colormap ] a matplotlib. norm: [ None | Normalize ] matplotlib. bottom. draws the outlines in the specified color.linewidth. top) ] The limits of the bins.pyplot . draws the outlines in the default color. and if you set the linewidths argument you must set it as a sequence of floats. defaults to rc lines. patches) or ([n0. **kwargs) call signature: hist(x. rwidth=None.hist(x. . use get_array() on this PolyCollection to get the counts in each hexagon. log=False. histtype=’bar’.pyplot. align=’mid’. histtype=’bar’.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’.. .13 – continued from previous page facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib.1 Table 50.. Note that the ndarray form is transposed relative to the list form.. Multiple data can be provided via x as a list of datasets of potentially different length ([x0...]). color=None. n1. ‘dashdot’. bins=10.]. range=None. orientation=’vertical’. hold=None. horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. matplotlib pyplot . [patches0.. cumulative=False. Release 1.]) if the input contains multiple data. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number The return value is a PolyCollection instance. Keyword arguments: 742 Chapter 50.Matplotlib.. rwidth=None. The return value is a tuple (n. cumulative=False. x1. weights=None. log=False. label=None. bins. patches1. bins.0. or as a 2-D ndarray in which each column is a dataset. ‘dotted’ | (offset. If marginals is True. normed=False. **kwargs) Compute and draw the histogram of x. bottom=None. align=’mid’.figure. bottom=None. normed=False. Masked arrays are not supported at present.. orientation=’vertical’. bins=10. range=None. MPL inherited that error.3.Matplotlib. range is (x. Release 1. If not provided.00 log10(N) 743 1..sum(pdf * np. Range has no effect if bins is a sequence..hist(. patches = ax. n/(len(x)*dbin). If bins is a sequence or range is specified.1 Hexagon binning 20 10 0 10 20 With a log color scale 20 140 120 10 100 80 60 counts 0 2.1. bins + 1 bin edges will be returned.) print np. normed: If True. the integral of the histogram should be 1.50 0. In a probability density.25 4 3 2 10 1 2 3 4 0. of the same shape as x.pyplot .00 1. If bins is an integer. consistent with numpy.75 0. Each value in x only contributes its 50.histogram() for numpy version >= 1.min(). matplotlib. the first element of the return tuple will be the counts normalized to form a probability density.50 1. autoscaling is based on the specified bin range instead of the range of x. x. and with the new = True argument in earlier versions.max()).diff(bins)) Note: Until numpy release 1.00 0. Unequally spaced bins are supported if bins is a sequence.5. the underlying numpy histogram function was incorrect with normed*=*True if bin sizes were unequal. Lower and upper outliers are ignored.. i. range: The lower and upper range of the bins. It is now corrected within MPL when using earlier numpy versions weights An array of weights. bins.25 4010 20 0 20 4 3 2 10 1 2 3 4 bins: Either an integer number of bins or a sequence giving the bins.e.0.75 1. you can verify that with a trapezoidal integration of the probability density function: pdf. randn(1000). Ignored if histtype = ‘step’ or ‘stepfilled’. • ‘left’: bars are centered on the left bin edges. • ‘mid’: bars are centered between the bin edges. If None.0. cumulative: If True. If multiple data are given the bars are aranged side by side. histtype: [ ‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’ ] The type of histogram to draw. Release 1. if normed is also True. empty bins will be filtered out and only the non-empty (n.hist(10+2*np. patches) will be returned. automatically compute the width.5) ax.randn(1000). rwidth: The relative width of the bars as a fraction of the bin width. label=’women’.random. or sequence of strings to match multiple datasets. align: [’left’ | ‘mid’ | ‘right’ ] Controls how the histogram is plotted. the weights are normalized. the direction of accumulation is reversed. log: If True. alpha=0. so that the legend command will work as expected: ax. label: String. • ‘stepfilled’ generates a lineplot that is by default filled. If normed is True. matplotlib pyplot . The last bin gives the total number of datapoints.g. • ‘bar’ is a traditional bar-type histogram. then the histogram is normalized such that the first bin equals 1. barh() will be used for bar-type histograms and the bottom kwarg will be the left edges. so that the integral of the density over the range remains 1. If normed is also True then the histogram is normalized such that the last bin equals 1. Bar charts yield multiple patches per dataset. bins. -1). In this case.legend() kwargs are used to update the properties of the Patch instances returned by hist: 744 Chapter 50. orientation: [ ‘horizontal’ | ‘vertical’ ] If ‘horizontal’.random. color: Color spec or sequence of color specs.hist(12+3*np. • ‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other. If log is True and x is a 1D array. If cumulative evaluates to less than 0 (e. then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. but only the first gets the label.Matplotlib.1 associated weight towards the bin count (instead of 1). label=’men’) ax. • ‘step’ generates a lineplot that is by default unfilled. one per dataset. • ‘right’: bars are centered on the right bin edges. the histogram axis will be set to a log scale. Default (None) uses the standard line color sequence. colors=’k’. xmin.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. 50. label=’‘. hold=None. or ‘none’ for no color mpl color spec. linestyles=’solid’. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. xmin and xmax: can be scalars or len(x) numpy arrays. or None for default. If they are scalars. else the widths of the lines are determined by xmin and xmax.1.figure. or None for default.pyplot 745 . Returns the LineCollection that was added. matplotlib.Bbox instance [True | False] [ (Path.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Additional kwargs: hold = [True|False] overrides default hold state matplotlib.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Example: Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. colors=’k’. Release 1.transforms. xmax. **kwargs) Plot horizontal lines at each y from xmin to xmax.Matplotlib.hlines(y. xmax. Required arguments: y: a 1-D numpy array or iterable. or ‘none’ for no color a matplotlib. xmin.pyplot. linestyles=’solid’. then the respective values are constant.0. **kwargs) call signature: hlines(y. σ =15 60 80 100 120 Smarts 140 160 Optional keyword arguments: colors: a line collections color argument.Matplotlib. See help(colormaps) for more information matplotlib. If b is None (default).1 0. subsequent plot commands will be added to the current axes.030 0.020 Probability 0.pyplot.pyplot.pyplot. When hold is False.025 0.hsv() set the default colormap to hsv and apply to current image if any. See help(colormaps) for more 746 Chapter 50.hot() set the default colormap to hot and apply to current image if any. the current axes and figure will be cleared on the next plot command. matplotlib.hold(b=None) Set the hold state. either a single color or a len(y) list of colors linestyles: [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. Release 1.010 0. else set the hold state to boolean value b: hold() # toggle hold hold(True) # hold is on hold(False) # hold is off When hold is True. matplotlib pyplot .0.005 0.000 40 Histogram of IQ : µ =100.015 0. toggle the hold state. PNG is tried.9 0. the return value is MxNx3. it will use it to load the image and return an array (if possible) which can be used with imshow(). Release 1.array. For RGBA images the return value is MxNx4.pyplot 747 .8 0.Matplotlib.6 0. otherwise the format is deduced from the filename. For grayscale images.3 0. but if PIL is installed.array as an image with one pixel per element. matplotlib can only read PNGs natively. Arguments: fname: A string containing a path to a filename.imsave(*args.7 0.2 0.0 time (s) information matplotlib. matplotlib. **kwargs) Saves a 2D numpy. If nothing can be deduced. the output format is deduced from the extension of the filename. matplotlib.1.pyplot. Return value is a numpy. Keyword arguments: 50.0.1 5 4 3 2 1 Comparison of model with data 0 0. or a Python file-like object. arr: A 2D array. the return array is MxN. **kwargs) Return image file in fname as numpy. If format is provided.4 0. For RGB images. fname may be a string path or a Python file-like object. The output formats available depend on the backend being used. will try to read file of that type.array.pyplot. If format is None and fname is a string.imread(*args.1 0.5 0. 0. eg. X may be a float array. interpolation=None. vmax=None. If None.imshow(X.aspect value. pdf. hold=None.cm. Most backends support png. a uint8 array or a PIL image.cmap value.cmap value.origin value. eps and svg. extent=None. vmin=None. filternorm=1.0. cmap: cmap is a colors.1 vmin/vmax: [ None | scalar ] vmin and vmax set the color scaling for the image by fixing the values that map to the colormap color limits. alpha=None. resample=None.0] index of the array is in the upper left or lower left corner of the axes. If either vmin or vmax is None. default to the rc image. If None. aspect=None. matplotlib. MxN float arrays may be normalised. **kwargs) call signature: imshow(X. default to rc image. norm=None. cmap=None.AxesImage instance is returned. matplotlib pyplot .Colormap instance. X can have the following shapes: •MxN – luminance (grayscale. format: One of the file extensions supported by the active backend. If None. eg cm.jet. the axes aspect ratio is changed to match that of the extent. changes the axes aspect ratio to match that of the image. origin=None. default to rc image. interpolation=None. origin=None.pyplot. If X is an array. url=None. interpolation: 748 Chapter 50. norm=None.0. Defaults to the rc image. and extent is None. imlim=None. cmap=None. that limit is determined from the arr min/max value. origin [ ‘upper’ | ‘lower’ ] Indicates where the [0. aspect=None. changes the image aspect ratio to match that of the axes If ‘equal’. An matplotlib. **kwargs) Display the image in X to current axes. cmap is ignored when X has RGB(A) information aspect: [ None | ‘auto’ | ‘equal’ | scalar ] If ‘auto’.jet. dpi The DPI to store in the metadata of the file. alpha=None.Colormap instance. ps. filterrad=4.Matplotlib. Release 1.image. vmin=None. float array only) •MxNx3 – RGB (float or uint8 array) •MxNx4 – RGBA (float or uint8 array) The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0. If extent is not None. extent=None. vmax=None.0 to 1. Keyword arguments: cmap: [ None | Colormap ] A matplotlib. This does not affect the resolution of the output image. shape=None. cm. the min and max of the luminance values will be used. Release 1. the filter function must produce a graph of the proper shape. top) ] Data limits for the axes. ‘lanczos’ or ‘blackman’ Additional kwargs are Artist properties: 50. ‘hamming’. ‘spline16’.Matplotlib. This scales luminance -> 0-1 norm is only used for an MxN float array. The default assigns zero-based row.origin. ‘kaiser’.0. ‘spline36’. ‘gaussian’.0 which means that any sum of pixel weights must be equal to 1. default is normalization(). It doesn’t do anything with the source floating point values.1. vmin/vmax: [ None | scalar ] Used to scale a luminance image to 0-1. extent: [ None | scalars (left. default to rc image. the settings for vmin and vmax will be ignored. alpha: scalar The alpha blending value. ‘bessel’. ‘bicubic’. ‘quadric’.1 Acceptable values are None. between 0 (transparent) and 1 (opaque) or None origin: [ None | ‘upper’ | ‘lower’ ] Place the [0. Note if norm is not None. ‘mitchell’. ‘sinc’. ‘bilinear’.colors. filterrad: The filter radius for filters that have a radius parameter.Normalize instance.pyplot 749 . shape: [ None | scalars (columns. ‘lanczos’ If interpolation is None. ‘nearest’. bottom. ‘catrom’. if None. when interpolation is one of: ‘sinc’. if filternorm = 1. ‘hermite’. From the antigrain documentation. matplotlib. it corrects only integers according to the rule of 1. the filter normalizes integer values and corrects the rounding errors.0] index of the array in the upper left or lower left corner of the axes.0. rows) ] For raw buffer images filternorm: A parameter for the antigrain image resize filter. right. See also the filternorm and filterrad parameters norm: [ None | Normalize ] An matplotlib.interpolation. default to rc image. If either is None. i.e. ‘hanning’. If None. column indices to the x. y centers of the pixels. So. 0.0 transparent through 1. matplotlib pyplot .Bbox instance [True | False] [ (Path.0 opaque) [True | False] an Axes instance a matplotlib.Matplotlib.Figure instance an id string any string [True | False] [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 3 2 1 0 1 2 33 2 1 0 1 2 3 750 Chapter 50. Release 1. Transform) | Patch | None ] a callable function a matplotlib.figure.1 Property agg_filter alpha animated axes clip_box clip_on clip_path contains figure gid label lod picker rasterized snap transform url visible zorder Example: Description unknown float (0.transforms. ’label3’). ’label2’. matplotlib.ion() Turn interactive mode on. loc=’upper left’) or: 50.pyplot. ’label3’) ) To make a legend at a given location.set_label(’my data’).pyplot. ’label2’. ’label3’) ) To make a legend for a list of lines and labels: legend( (line1. See help(colormaps) for more information matplotlib.ishold() Return the hold status of the current axes matplotlib. y. using a location argument: legend( (’label1’. To automatically generate the legend from labels: legend( (’label1’. ’label2’.1 Additional kwargs: hold = [True|False] overrides default hold state matplotlib. To make a legend with existing lines: legend() legend() by itself will try and build a legend using the label property of the lines/patches/collections. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location. Release 1. **kwargs) Place a legend on the current axes at location loc.jet() set the default colormap to jet and apply to current image if any.pyplot. label=’my data’) or: line. line2. matplotlib.Matplotlib.pyplot. line3).pyplot. If label is set to ‘_nolegend_’. (’label1’. matplotlib.ioff() Turn interactive mode off. the item will not be shown in legend.isinteractive() Return the interactive status matplotlib. **kwargs) call signature: legend(*args. You can set the label of a line by doing: plot(x.pyplot.0.pyplot 751 .legend(*args.1. matplotlib pyplot . default is 1 752 Chapter 50.0. frameon: [ True | False ] if True. use rc settings. original.FontProperties instance. by using the bbox_transform keyword. use rc settings. line2. numpoints: integer The number of points in the legend for line scatterpoints: integer The number of points in the legend for scatter plot scatteroffsets: list of floats a list of yoffsets for scatter symbols in legend markerscale: [ None | scalar ] The relative size of legend markers vs. loc=2) The location codes are Location String ‘best’ ‘upper right’ ‘upper left’ ‘lower left’ ‘lower right’ ‘right’ ‘center left’ ‘center right’ ‘lower center’ ‘upper center’ ‘center’ Location Code 0 1 2 3 4 5 6 7 8 9 10 Users can specify any arbitrary location for the legend using the bbox_to_anchor keyword argument. bbox_to_anchor = (0. ncol [integer] number of columns. use rc shadow: [ None | False | True ] If True. draw a frame. For example. Release 1. Default is True fancybox: [ None | False | True ] if True. (’label1’. line3). The legend location can be specified in other coordinate.font_manager. The loc itslef can be a 2-tuple giving x. If None. 0. Keyword arguments: prop: [ None | FontProperties | dict ] A matplotlib. ’label2’. loc = ‘upper right’. If prop is a dictionary.5.y of the lower-left corner of the legend in axes coords (bbox_to_anchor is ignored). use rc settings.5) will place the legend so that the upper right corner of the legend at the center of the axes. draw a frame with a round fancybox. If None. If None.Matplotlib.1 legend( (line1. If None. a new instance will be created with prop. ’label3’). draw a shadow behind legend. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 floats. g.1. Release 1. E. 50. title [string] the legend title Padding and spacing between various elements use following keywords parameters.. a fontsize of 10 points and a handlelength=5 implies a handlelength of 50 points. These values are measure in font-size units. transAxes if None. Values from rcParams will be used if None. matplotlib. the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor) bbox_to_anchor [an instance of BboxBase or a tuple of 2 or 4 floats] the bbox that the legend will be anchored.Matplotlib.pyplot 753 . Keyword borderpad labelspacing handlelength handletextpad borderaxespad columnspacing Example: Description the fractional whitespace inside the legend border the vertical space between the legend entries the length of the legend handles the pad between the legend handle and text the pad between the axes and legend border the spacing between columns Minimum Message Length Model length Data length Total message length Message length ---> Model complexity ---> Also see Legend guide. bbox_transform [[ an instance of Transform | None ]] the transform for the bbox.1 mode [[ “expand” | None ]] if mode is “expand”.0. for example: ax.0 transparent through 1. autoscale_view() is called automatically after the parameters are changed.pyplot. see matplotlib.set_xscale() / matplotlib.0. tight [True | False | None] Parameter passed to autoscale_view().transforms. **kwargs) Make a plot with log scaling on the x and y axis.set_yscale() for details nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid.locator_params(axis=’both’.Axes. matplotlib pyplot .0 opaque) [True | False] [True | False] an Axes instance a matplotlib. for no change. matplotlib.axes. loglog() supports all the keyword arguments of plot() matplotlib. tight=None.set_yscale(). Remaining keyword arguments are passed to directly to the set_params() method.Matplotlib. or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on Description unknown float (0.loglog(*args. Keyword arguments: axis [’x’ | ‘y’ | ‘both’] Axis on which to operate. None defaults to autosubs. nbins=4) Because the locator is involved in autoscaling. which depend on the number of decades in the plot.Axes. This presently works only for the MaxNLocator used by default on linear axes.pyplot.Axes.axes. **kwargs) Convenience method for controlling tick locators.set_xscale() / matplotlib.axes.Bbox instance [True | False] and 754 Chapter 50. Notable keyword arguments: basex/basey: scalar > 1 base of the x/y logarithm subsx/subsy: [ None | sequence ] the location of the minor x/y ticks. Default is None. **kwargs) call signature: loglog(*args. Release 1. default is ‘both’.axes. but it may be generalized.1 matplotlib. Typically one might want to reduce the maximum number of ticks and use tight bounds when plotting small subplots.Axes.locator_params(tight=True. signatures: margins() returns xmargin. ymargin 50. matplotlib.Transform instance a url string [True | False] 1D array 1D array any number Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. stride) float distance in points or callable pick function fn(artist. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Matplotlib.’ | ’.0. Release 1.figure.1. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.transforms.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. **kw) Convenience method to set or retrieve autoscaling margins.pyplot 755 .margins(*args.1 clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [ (Path.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.pyplot. The tight parameter is passed to autoscale_view(). if xmargin is not None. Specifying any margin changes only the autoscaling. on the assumption that when margins are specified.0 0. ymargin) margins(x=xmargin. unless this would make an excessively short or narrow figure. matplotlib pyplot ..0 -2 10-1 100 101 102 10 All three forms above set the xmargin and ymargin parameters. All keyword parameters are optional. Setting tight to None will preserve the previous setting. The origin is set at the upper left hand corner and rows (first dimension of the array) are displayed horizontally. A single argument specifies both xmargin and ymargin. which is executed after a margin is changed..0. the default here is True.5 15 201.1 100 10-1 10-2 0 102 semilogy 104 103 101 102 101 100 100 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 10-1 -1 0 2 2 2 2 2 2 2 2 2 2 2 2 25 10 10 101 102 103 margins(margin) margins(xmargin. tight=False) loglog base 4 on x 105Errorbars go negative 5 10 semilogx 1. fignum=None.pyplot. matplotlib.0 0. then xmargin times the X data interval will be added to each end of that interval before it is used in autoscaling.Matplotlib. Release 1. Tick labels for the xaxis are placed on top. **kw) Display an array as a matrix in a new figure window.matshow(A.. The aspect ratio of the figure window is that of the array. 756 Chapter 50. y=ymargin) margins(.5 0. no additional padding to match tick marks is usually desired. for example. the quadrilateral for C[i. then the last row and column of C will be ignored. j]. Y[i. the created figure will use this figure number. j]). Y[i. matplotlib. if you provide the number of an already existing figure. j+1]. making a rectangular grid. X. matplotlib.pyplot. they will be expanded as needed into the appropriate 2-D arrays.1 With the exception of fignum. X and Y. Y and C may be masked arrays. Because of how matshow() tries to set the figure aspect ratio to be the one of the array.over(func. j]. j]).minorticks_off() Remove minor ticks from the current plot. [i. matplotlib. **kwargs) pcolor(X. nothing is plotted. see the Grid Orientation section below. If either or both of X and Y are 1-D arrays or column vectors. (X[i. If fignum is False or 0. if given. If fignum is given as an integer. j]. matplotlib. j+1]) is masked. Y. turn them off using minorticks_off() if drawing speed is a problem. [i+1.1. keyword arguments are passed to imshow(). fignum: [ None | integer | False ] By default.pcolor(*args. Ideally the dimensions of X and Y should be one greater than those of C. j+1]. j+1]).j] (X or Y at [i. Y[i+1. Y[i+1. Note that the the column index corresponds to the x-coordinate. C is the array of color values. (X[i+1. Displaying minor ticks reduces performance. or one of the vertices surrounding C[i. j+1]. strange things may happen. (X[i+1. specify the (x. j]. if the dimensions are the same. Release 1. *args. **kwargs) call signatures: pcolor(C. j]. y) coordinates of the colored quadrilaterals. a new figure window will NOT be created.j] has corners at: (X[i.[i+1.0. and the row index corresponds to y.Matplotlib. matplotlib. j+1]). **kwargs) over calls: func(*args. C. matshow() creates a new figure window with automatic numbering.pyplot 757 .pyplot. If either C[i. for details.pyplot. **kwargs) with hold(True) and then restores the hold state. Keyword arguments: 50. **kwargs) Create a pseudocolor plot of a 2-D array.minorticks_on() Display minor ticks on the current plot.pyplot. if ‘flat’. ncolumns) is plotted with the column number as X and the row number as Y.1. If either are None. [0.Colormap instance. Default is ‘flat’.1 cmap: [ None | Colormap ] A matplotlib.y) is equivalent to: X = array([[0. edges will not be visible. Y = meshgrid(x.Collection instance. An mpl color or sequence of colors will set the edge color alpha: 0 <= scalar <= 1 or None the alpha blending value Return value is a matplotlib. If None. That is. please use ‘edgecolors’ instead: • shading=’flat’ – edgecolors=’none’ • shading=’faceted – edgecolors=’k’ edgecolors: [ None | ‘none’ | color | color sequence] If None. defaults to normalize(). 4]. 1. the rc setting is used by default.arange(3) X. 1. 2. Y. 2. 2]]) so if you have: C = rand( len(x). 2. 1.cm. len(y)) then you need: pcolor(X. edges are not drawn. contrary to MATLAB. except that the Y axis is reversed. Release 1. [1. C is taken as C*(*y.arange(5) y = np. If None. 2. Similarly for meshgrid(): x = np. 4]. 1. norm: [ None | Normalize ] An matplotlib.0. x). 0. vmin and vmax will be ignored.colors. C. increasing up. shading: [ ‘flat’ | ‘faceted’ ] If ‘faceted’. 2. [0. 1]. 3. 3. hence it is plotted the way the array would be printed. 0]. 1. 2. matplotlib pyplot . use rc settings.collection. 4]]) Y = array([[0. 1. The grid orientation follows the MATLAB convention: an array C with shape (nrows. 0.Normalize instance is used to scale luminance data to 0. [2.Matplotlib. a black grid is drawn around each rectangle.T) or: pcolor(C. the min and max of the color array C is used. If ‘none’. 0.T) 758 Chapter 50. 3. If you pass a norm instance. This kwarg is deprecated. vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data. 1.pyplot 759 . matplotlib.Matplotlib. Additional kwargs: hold = [True|False] overrides default hold state 50. kwargs can be used to control the PolyCollection properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized snap transform url urls visible zorder Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. which defaults to True. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number Note: the default antialiaseds is taken from rcParams[’patch. particularly if alpha is 1. you may be able to reduce rendering artifacts (light or dark patch boundaries) by setting it to False. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib.antialiased’]. or if X and Y have one more row and column than C. there seems to be no single combination of parameters that eliminates artifacts under all conditions.1 MATLAB pcolor() always discards the last row and column of C. ‘dotted’ | (offset. In some cases. ‘dashdot’.0.Bbox instance [True | False] [ (Path.transforms. but matplotlib displays the last row and column if X and Y are not specified.Figure instance an id string any string [’solid’ | ‘dashed’. Unfortunately.figure. An alternative it to set edgecolors to ‘face’. Release 1. cm. contrary to MATLAB. defaults to normalize().QuadMesh properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. if ‘flat’. C) pcolormesh(C.pcolormesh(*args.colors. please use ‘edgecolors’ instead: • shading=’flat’ – edgecolors=’None’ • shading=’faceted – edgecolors=’k’ edgecolors: [ None | ‘None’ | color | color sequence] If None.pyplot.1. **kwargs) call signatures: pcolormesh(C) pcolormesh(X. This kwarg is deprecated. Transform) | Patch | None ] Continued on next page Chapter 50. If either are None.Bbox instance [True | False] [ (Path. a black grid is drawn around each rectangle. Keyword arguments: cmap: [ None | Colormap ] A matplotlib. the min and max of the color array C is used.0. Release 1. If you pass a norm instance. in contrast. shading: [ ‘flat’ | ‘faceted’ | ‘gouraud’ ] If ‘faceted’. Masked array support is implemented via cmap and norm. Y. kwargs can be used to control the matplotlib. If None. pcolor() simply does not draw quadrilaterals with masked colors or vertices. vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data. vmin and vmax will be ignored.transforms. **kwargs) C may be a masked array. If ‘None’.collection. An mpl color or sequence of colors will set the edge color alpha: 0 <= scalar <= 1 or None the alpha blending value Return value is a matplotlib. norm: [ None | Normalize ] A matplotlib. If None. matplotlib pyplot 760 .QuadMesh object. but X and Y may not.Matplotlib. edges are not drawn. use rc settings. edges will not be visible.Normalize instance is used to scale luminance data to 0.Colormap instance.1 matplotlib. Default is ‘flat’.collections. the rc setting is used by default. colors=None. matplotlib. Additional kwargs: hold = [True|False] overrides default hold state matplotlib. Keyword arguments: 50. then the values of x give the fractional area directly and the array will not be normalized. explode=None.pyplot 761 . ‘dashdot’. explode=None.0. ’m’.16 – continued from previous page cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. hold=None) call signature: pie(x.1 Table 50.Matplotlib.1. labels=None. ’w’).1.figure. ’k’. If sum(x) <= 1. ’c’.pie(x. shadow=False) Make a pie chart of array x. ’r’. The fractional area of each wedge is given by x/sum(x).pyplot. pctdistance=0. ’y’.59999999999999998. autopct=None.1000000000000001. autopct=None. shadow=False. labels=None.6. labeldistance=1. ‘dotted’ | (offset. Release 1. ’g’. pctdistance=0. colors=(’b’. labeldistance=1. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number See Also: pcolor() For an explanation of the grid orientation and the expansion of 1-D X and/or Y to 2-D arrays. 0. colors: [ None | color sequence ] A sequence of matplotlib color args through which the pie chart will cycle. 0.1. is a len(x) array which specifies the fraction of the radius with which to offset each wedge. where patches and texts are as above.N-1 but with red plusses If x and/or y is 2-dimensional.patches. default is 0. Additional kwargs: hold = [True|False] overrides default hold state matplotlib.. return the tuple (patches.pyplot. The pie chart will probably look best if the figure and axes are square. texts): • patches is a sequence of matplotlib.pink() set the default colormap to pink and apply to current image if any. **kwargs) Plot lines and/or markers to the Axes. it will be called. fmt groups can be specified.8)) ax = axes([0.Wedge instances • texts is a list of the label matplotlib. An arbitrary number of x. For example. and y using default line style and color and y using blue circle markers using x as index array 0. pctdistance: scalar The ratio between the center of each pie slice and the start of the text generated by autopct.0.8]) Return value: If autopct is None. labels: [ None | len(x) sequence of strings ] A sequence of strings providing the labels for each wedge autopct: [ None | format string | format function ] If not None.text. ’r+’) # # # # plot x plot x plot y ditto.Matplotlib.1 explode: [ None | len(x) sequence ] If not None. y) plot(x. is a string or function used to label the wedges with their numeric value. If it is a format string. If it is a function. each of the following is legal: plot(x. autotexts). The label will be placed inside the wedge. then the corresponding columns will be plotted. the label will be fmt%pct. y pairs with an optional format string. ’bo’) plot(y) plot(y. y.Text instances. texts. Release 1.1. args is a variable length argument. and autotexts is a list of Text instances for the numeric labels.plot(*args. return the tuple (patches.8. Eg.6. allowing for multiple x. y.: figure(figsize=(8. matplotlib pyplot . See help(colormaps) for more information matplotlib. as in: 762 Chapter 50. 0. If autopct is not None. labeldistance: scalar The radial distance at which the pie labels are drawn shadow: [ False | True ] Draw a shadow beneath the pie.pyplot. Ignored if autopct is None. 1 a. y1. hex strings (’#008000’). ’g^’. the string specifications can be used in place of a fmt group. ’g-’) Return value is a list of lines that were added.0.Matplotlib.’ ’:’ ’.pyplot 763 . Release 1. RGB or RGBA tuples ((0. matplotlib.0. 50. Of these.1.1)) or grayscale intensities as a string (’0. but the tuple forms can be used only as kwargs. The following format string characters are accepted to control the line style or marker: character ’-’ ’--’ ’-. y2.8’).1.’ ’o’ ’v’ ’^’ ’<’ ’>’ ’1’ ’2’ ’3’ ’4’ ’s’ ’p’ ’*’ ’h’ ’H’ ’+’ ’x’ ’D’ ’d’ ’|’ ’_’ description solid line style dashed line style dash-dot line style dotted line style point marker pixel marker circle marker triangle_down marker triangle_up marker triangle_left marker triangle_right marker tri_down marker tri_up marker tri_left marker tri_right marker square marker pentagon marker star marker hexagon1 marker hexagon2 marker plus marker x marker diamond marker thin_diamond marker vline marker hline marker The following color abbreviations are supported: character ‘b’ ‘g’ ‘r’ ‘c’ ‘m’ ‘y’ ‘k’ ‘w’ color blue green red cyan magenta yellow black white In addition. x2.plot(x1. you can specify colors in many weird and wonderful ways. including full names (’green’).’ ’. and markercolor with: plot(x.4.2.: plot(x1. The kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod Description unknown float (0.Matplotlib. e. The kwargs can be used to set line properties (any property that has a set_* method). 10]) legend() If you make multiple lines with one plot command.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. x2. which are just abbreviations.2. marker=’o’.1 Line styles and colors are combined in a single format string.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. marker face color. linestyle=’dashed’. See :class:‘~matplotlib. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. You do not need to use format strings.Line2D‘ for details. 4. label=’line 2’) axis([0. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.figure. antialised=False) Neither line will be antialiased.Bbox instance [True | False] [ (Path. label=’line 1’. All of the line properties can be controlled by keyword arguments.9]. ’rs’. ’go-’.2. 0. marker. color=’green’. etc.3]. y. Here is an example: plot([1. linewidth=2) plot([1.lines. For example. y1. [1. Release 1. matplotlib pyplot . you can set the color.0. the kwargs apply to all those lines. linestyle. You can use this to set a line label (for auto legends).0 transparent through 1. linewidth.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] 764 Chapter 50.g. anitialising.transforms.3]. as in ’bo’ for blue circles. markerfacecolor=’blue’. markersize=12). [1.3]. y2. ydate=False.plot_date(x.1 marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder [ ’+’ | ’*’ | ’. are passed on to autoscale_view() to determine whether the x and y axes are autoscaled. if defined. fmt=’bo’.0. fmt=’bo’. stride) float distance in points or callable pick function fn(artist. except the x or y (or both) data is considered to be dates. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. y.pyplot 765 .pyplot. ydate=False. If None. Keyword arguments: fmt: string The plot format string. and the axis is labeled accordingly. the x-axis will be labeled with dates.AutoDateLocator (if the tick locator is not al50. tz=None. hold=None. xdate=True. Note if you are using custom date tickers and formatters.transforms. **kwargs) call signature: plot_date(x.’ | ’. Additional kwargs: hold = [True|False] overrides default hold state matplotlib. Release 1.Transform instance a url string [True | False] 1D array 1D array any number kwargs scalex and scaley. x and/or y can be a sequence of dates represented as float days since 0001-01-01 UTC.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. matplotlib. y. tz: [ None | timezone string ] The time zone to use in labeling dates.1. defaults to rc value. xdate=True. the y-axis will be labeled with dates.dates.Matplotlib. xdate: [ True | False ] If True. the default is True. ydate: [ False | True ] If True. **kwargs) Similar to the plot() command. it may be necessary to set the formatters/locators after the call to plot_date() since plot_date() will set the default tick locator to matplotlib. tz=None. transforms.transforms. Valid kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata Description unknown float (0.0 transparent through 1. Release 1.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.Matplotlib.DateLocator instance) and the default tick formatter to matplotlib. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.Transform instance a url string [True | False] 1D array 1D array 766 Chapter 50.dates.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.dates. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib. matplotlib pyplot . stride) float distance in points or callable pick function fn(artist.Bbox instance [True | False] [ (Path.0.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.1 ready set to a matplotlib.DateFormatter instance).0 opaque) [True | False] [True | False] an Axes instance a matplotlib.figure.AutoDateFormatter (if the tick formatter is not already set to a matplotlib.dates.’ | ’. ‘. If it is a string. so ’Adj Close*’ will have name ’adj_close’. or for lines in a single subplot if subplots is False. ‘fill’. comments. else in a new figure. checkrows. subplots=True. matplotlib will make column headers lower case. it indicates the column number. etc. (0. eg.csv2rec() to load the data into a record array. checkrows=5. delimiter. Release 1. plotfuncs=None. specify an alternate plot type for volume plotfile(fname. other choices are ‘semilogy’.. and names are matplotlib. then including any function such as ‘semilogy’ that changes the axis scaling will set the scaling for all columns.0. plotfuncs={’volume’: ’semilogy’}) 50. it will be made in the current figure if one exists. If it is an int. the plot always will be made in a new figure. Example usage: # plot the 2nd and 4th column against the 1st in two subplots plotfile(fname.pylab. only that column will be plotted on the y axis. ’volume’.Matplotlib. •If len(cols) == 1. if False.1 zorder any number See Also: dates for helper functions date2num(). An identifier is either an int or a string. num2date() and drange() for help on creating the required floating point dates. skiprows=0.pyplot. is a dictionary mapping identifier to an Axes plotting function as a string. replace spaces with underscores. If subplots is False. newfig=True. plotfuncs.plotfile(fname. matplotlib.pyplot 767 .1. it indicates the column header. comments=’#’. (’date’.3)) # plot using column names. delimiter=’. ‘bar’. ’adj_close’). **kwargs) Plot the data in fname cols is a sequence of column identifiers to plot. all passed on to If newfig is True. Default is ‘plot’. integer column numbers in both or column names in both.1. •If len(cols) > 1. the first element will be an identifier for data for the x axis and the remaining elements will be the column indexes for multiple subplots if subplots is True (the default). skiprows. names=None. if not None. ). kwargs are passed on to plotting functions. Additional kwargs: hold = [True|False] overrides default hold state matplotlib. You must use the same type of identifier in the cols vector as you use in the plotfuncs dictionary. and remove all illegal characters. cols=(0. 1 Note: plotfile is intended as a convenience for quickly plotting data from flat files.0. matplotlib pyplot 768 .Matplotlib. w/o resampling add text in figure coords create or change active figure make filled polygons make filled polygons between two sets of y-values make filled polygons between two sets of x-values return the current axes return the current figure get the current image. or None get a graphics property make a histogram set the hold state on current axes add a legend to the axes a log log plot load image file into array save array as an image file plot image data display a matrix in a new figure preserving aspect make a pseudocolor plot make a line plot plot data from a flat file make a plot of power spectral density make a direction field (arrows) plot control the default params Continued on next page Chapter 50.pyplot. matplotlib. Release 1.plotting() Plotting commands Command axes axis bar boxplot cla clabel clf close colorbar cohere contour contourf csd draw errorbar figlegend figimage figtext figure fill fill_between fill_betweenx gca gcf gci getp hist hold legend loglog imread imsave imshow matshow pcolor plot plotfile psd quiver rc Description Create a new axes Set or return the current axis limits make a bar chart make a box and whiskers chart clear current axes label a contour plot clear a figure window close a figure window add a colorbar to the current figure make a plot of coherence make a contour plot make a filled contour plot make a plot of cross spectral density force a redraw of the current figure make an errorbar graph add a legend to the figure add an image to the figure. it is not intended as an alternative interface to general plotting with pyplot or matplotlib. 50.pyplot.Matplotlib. matplotlib.19 – continued from previous page savefig save the current figure scatter make a scatter plot setp set a graphics property semilogx log x axis semilogy log y axis show show the figures specgram a spectrogram plot stem make a stem plot subplot make a subplot (numrows.1 Table 50.y to the current axes title add a title to the current axes xlabel add an xlabel to the current axes ylabel add a ylabel to the current axes The following commands will set the default colormap accordingly: •autumn •bone •cool •copper •flag •gray •hot •hsv •jet •pink •prism •spring •summer •winter •spectral matplotlib.pyplot 769 .1. Release 1.polar(*args. r arguments are supported. numcols. Multiple theta. as in plot(). **kwargs) call signature: polar(theta. axesnum) table add a table to the axes text add some text at location x. with format strings. r.0. **kwargs) Make a polar plot. If a function is passed as the argument. which sets pad_to equal to NFFT 770 Chapter 50. Fs: scalar The sampling frequency (samples per time unit). This can be different from NFFT. Unlike in MATLAB.get_window(). This corresponds to the n parameter in the call to fft(). noverlap: integer The number of points of overlap between blocks.signal(). The default value is 0 (no overlap). matplotlib. Fc=0. Release 1. window_none().blackman(). NFFT=256. numpy. Fs is the sampling frequency. freqs. numpy.1 An optional kwarg resolution sets the number of vertices to interpolate between each pair of points. pad_to=None. numpy. detrend_mean().hamming(). noverlap=0. The vector x is divided into NFFT length segments. sides=’default’. Fc=0. noverlap gives the length of the overlap between segments.window_hanning.pyplot.psd(x. sides=’default’. **kwargs) call signature: psd(x. It is used to calculate the Fourier frequencies. hold=None. **kwargs) The power spectral density by Welch’s average periodogram method. window=mlab. this can give more points in the plot. which disables interpolation. The default value is 256. scipy. noverlap=0.prism() set the default colormap to prism and apply to current image if any.Matplotlib. The default value is 2. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. designed to remove the mean or linear trend. allowing for more detail. scale_by_freq=None. Fs=2.signal. matplotlib pyplot . etc. Each segment is detrended by function detrend and windowed by function window. Must be even. window: callable or ndarray A function or a vector of length NFFT. The default is None. window=<function window_hanning at 0x3a178c0>. detrend=<function detrend_none at 0x3a1c668>. where the detrend parameter is a vector. pad_to: integer The number of points to which the data segment is padded when performing the FFT.detrend_none. pad_to=None. detrend=mlab. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). Fs=2. and detrend_linear(). The default is 1.bartlett(). it must take a data segment as an argument and return the windowed version of the segment. NFFT=256. The default is window_hanning(). scale_by_freq=None. To create window vectors see window_hanning(). which specifies the number of data points used. The |fft(i)|2 of each segment i are averaged to compute Pxx.0. in cycles per time unit. a power 2 is most efficient. The pylab module defines detrend_none(). but you can use a custom function as well. with a scaling to correct for power loss due to windowing.pyplot. detrend: callable The function applied to each segment before fft-ing. in matplotlib is it a function. See help(colormaps) for more information matplotlib. scipy. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. John Wiley & Sons (1986) kwargs control the Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc Description unknown float (0. which gives density in units of Hz^-1.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. ‘onesided’ forces the return of a one-sided PSD. For plotting.1 sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return. which returns one-sided for real data and both for complex data. freqs). matplotlib.Matplotlib.0.pyplot 771 .’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color 50. Default gives the default behavior.0 transparent through 1.Bbox instance [True | False] [ (Path.1. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’. while ‘twosided’ forces two-sided. Release 1. References: Bendat & Piersol – Random Data: Analysis and Measurement Procedures. which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband. This allows for integration over the returned frequency values. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x. Fc: integer The center frequency of x (defaults to 0). Returns the tuple (Pxx.transforms. though Pxx itself is returned.’ | ’.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. The default is True for MATLAB compatibility.figure. the power is plotted as 10 log10 (P xx ) for decibels. 00 0.05 0. Release 1.05 0.Matplotlib.10 0. matplotlib pyplot . stride) float distance in points or callable pick function fn(artist.15 0.1 markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder any matplotlib color float None | integer | (startind. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Transform instance a url string [True | False] 1D array 1D array any number Example: Power Spectral Density (dB/Hz) 0.150 10 20 30 40 50 60 70 80 900 2 4 6 8 10 10 20 30 Frequency 40 50 Additional kwargs: hold = [True|False] overrides default hold state 772 Chapter 50.0.10 0.transforms. angles: [’uv’ | ‘xy’ | array] With the default ‘uv’. **kw) U. see pivot kwarg) U.1. based on the figure dpi • ‘x’. **kw) Plot a 2-D field of arrows.pyplot 773 . the arrow points from (x. V: give the x and y components of the arrow vectors C: an optional array used to map colors to the arrows All arguments may be 1-D or 2-D arrays or sequences.quiver(*args. matplotlib. V. quiver(X. • ‘width’ or ‘height’: the width or height of the axes • ‘dots’ or ‘inches’: pixels or inches.meshgrid(). Y. the arrow dimensions except for length are in multiples of this unit. If U and V are 2-D arrays but X and Y are 1-D. so that if U*==*V the angle of the arrow on the plot is 45 degrees CCW from the x-axis. Release 1. For ‘x’ or ‘y’. **kw) Arguments: X. they will be generated as a uniform grid. call signatures: quiver(U. If X and Y are absent. quiver(U. then X and Y will be expanded with numpy.1 matplotlib. Y are not supported at present. the arrows get larger as one zooms in. or ‘xy’: X. the arrow aspect ratio is 1.Matplotlib. With ‘xy’. and if len(X) and len(Y) match the column and row dimensions of U. CCW from the x-axis. Y: The x and y coordinates of the arrow locations (default is tail of arrow. or sqrt(X^2+Y^2) data units The arrows scale differently depending on the units. ‘y’. when the the window is resized. the arrow size increases with the width and height of the axes. V.0. the arrow size is independent of the zoom state. respectively. but masked X. arbitrary angles may be specified as an array of values in degrees. Keyword arguments: units: [’width’ | ‘height’ | ‘dots’ | ‘inches’ | ‘x’ | ‘y’ | ‘xy’] arrow units. **kw) C. V. Alternatively. scale: [ None | float ] 50. V. Y. C may be masked arrays. U. resizing does not change the arrows. **kw) U.y) to (x+u. for ‘dots’ or ‘inches’. quiver(X.pyplot. For ‘width or ‘height’. V. C. for other units. Y. y+v). Default is 1. matplotlib pyplot 774 . If None. Additional PolyCollection keyword arguments: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib. to make the head a triangle. above. color: [ color | color sequence ] This is a synonym for the PolyCollection facecolor kwarg. use “angles=’xy’. width: shaft width in arrow units. scale=1”. default is 4. The defaults give a slightly swept-back arrow. e. If C has been set.5 x-axis units.g. reduce headwidth or increase headlength and headaxislength. For example.5 minshaft: scalar length below which arrow scales. a typical starting value is about 0.v) = (1. headwidth: scalar head width as multiple of shaft width.0). linewidths and edgecolors can be used to customize the arrow outlines. scale_units=’xy’. scale is 2. If scale_units is ‘width’. if scale_units is ‘inches’.0.5 inches long. scale down all the head parameters. plot a dot (hexagon) of this diameter instead. color has no effect. The arrow length unit is given by the scale_units parameter scale_units: None.0. in units of head length. pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point. make headaxislength the same as headlength. m/s per plot width.005 times the width of the plot. then the vector will be half the width of the axes.Bbox instance [True | False] Continued on next page Chapter 50. then the vector will be 0. If scale_units is ‘x’ then the vector will be 0.Matplotlib. Release 1. default depends on choice of units. To make the arrow more pointed. with u and v having the same units as x and y. a simple autoscaling algorithm is used. if an arrow length is less than this. To plot vectors in the x-y plane. hence the name pivot. Do not set this to less than 1. To make the head smaller relative to the shaft. default is 5 headaxislength: scalar head length at shaft intersection. or small arrows will look terrible! Default is 1 minlength: scalar minimum length as a multiple of shaft width. and number of vectors. a smaller scale parameter makes the arrow longer.transforms. the arrow rotates about this point. or any of the units options. default is 3 headlength: scalar head length as multiple of shaft width. and (u. based on the average vector length and the number of vectors. You will probably do best to leave minshaft alone.1 data units per arrow length unit. X.1. label.quiverkey(*args. **kw) Arguments: Q: The Quiver instance returned by a call to quiver. U: The length of the key label: a string with the length and units of the key Keyword arguments: coordinates = [ ‘axes’ | ‘figure’ | ‘data’ | ‘inches’ ] Coordinate system and units for X.21 – continued from previous page clip_path [ (Path. ‘dashdot’. call signature: quiverkey(Q. **kw) Add a key to a quiver plot. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] snap unknown transform Transform instance url a url string urls unknown visible [True | False] zorder any number Additional kwargs: hold = [True|False] overrides default hold state matplotlib.0 in the lower left 50.pyplot. Y: ‘axes’ and ‘figure’ are normalized coordinate systems with 0. X.pyplot 775 .Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. matplotlib. Y: The location of the key. U.Matplotlib. Transform) | Patch | None ] cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib.1 Table 50. additional explanation follows.0. Release 1.figure. Y. ‘dotted’ | (offset. 1 and 1. If labelpos is ‘N’ or ‘S’.0. and so on.1 in the upper right. c=’r’) Note you can use python’s kwargs dictionary facility to store dictionaries of default parameters.0 at the lower left corner. respectively. style. X. kwargs is a dictionary attribute name/value pairs. the group is axes. ytick). The positioning of the key depends on X. coordinates. **kwargs) Set the current rc params. color=’r’) sets the current rc params and is equivalent to: rcParams[’lines. labelpos = [ ‘N’ | ‘S’ | ‘E’ | ‘W’ ] Position the label above.facecolor.linewidth’] = 2 rcParams[’lines.color’] = ’r’ The following aliases are available to save typing for interactive users: Alias ‘lw’ ‘ls’ ‘c’ ‘fc’ ‘ec’ ‘mew’ ‘aa’ Property ‘linewidth’ ‘linestyle’ ‘color’ ‘facecolor’ ‘edgecolor’ ‘markeredgewidth’ ‘antialiased’ Thus you could abbreviate the above rc command as: rc(’lines’. labelsep: Distance in inches between the arrow and the label. fontproperties: A dictionary with keyword arguments accepted by the FontProperties initializer: family. (xtick. If labelpos is ‘E’. eg. weight Any additional keyword arguments are used to override vector properties taken from Q. X. to the left of the arrow. for lines. Y. linewidth=2. Default is 0.rc(*args. Y positions the tail. ‘inches’ is position in the figure in inches.Matplotlib. Additional kwargs: hold = [True|False] overrides default hold state matplotlib. matplotlib pyplot . to the right. variant.linewidth the group is lines. eg: rc(’lines’. for axes. Y give the position of the middle of the key arrow. and if labelpos is ‘W’. ‘data’ are the axes data coordinates (used for the locations of the vectors in the quiver plot itself). size. lw=2. with 0. X. color: overrides face and edge colors from Q. Eg. Group is the grouping for the rc. eg. Y positions the head. Release 1. X. in either of these two cases. below.pyplot. you can customize the font rc as follows: 776 Chapter 50. Y is somewhere in the middle of the arrow+label key object.1 labelcolor: defaults to default Text color. and labelpos. Group may also be a list or tuple of group names. orientation=’portrait’.pyplot.savefig(*args.rgrids(*args.25. rgrid() simply returns the tuple (lines. labels = rgrids(radii. ’Dick’. format=None. **kwargs) Set/Get the radial locations of the gridlines and ticklabels on a polar plot. Release 1.0) ) # set the locations and labels of the radial gridlines and labels lines. matplotlib. papertype=None.25. call signatures: lines. See rc_file_defaults for reloading the default params from the rc file matplotlib. is a len(radii) list of strings of the labels to use at each angle. If format is None and fname is a string.pyplot.0.pyplot.5. where lines is an array of radial gridlines (Line2D instances) and labels is an array of tick labels (Text instances). matplotlib. 0. if not None.these are not the params loaded by the rc file. ’Harry’ ) matplotlib. 1. dpi=None. labels = rgrids() lines.5. angle=22. When called with arguments. labels = rgrids( (0. 1. transparent=False.1. the output format is deduced from the extension of the filename. Use rcdefaults() to restore the default rc params after changes.0). 0. the rformatter will be used Examples: # set the locations of the radial gridlines and labels lines. but mpl’s internal params. If labels is None.pyplot 777 . or possibly some backend-dependent object such as PdfPages. the value of the rc parameter 50. labels). **font) # pass in the font dict as kwargs This enables you to easily switch between several configurations.rcdefaults() Restore the default rc params . ’size’ : ’larger’} rc(’font’.5.1 font = {’family’ : ’monospace’. **kwargs) call signature: savefig(fname. labels=None. labels. The output formats available depend on the backend being used. **kwargs) When called with no arguments.1): Save the current figure. edgecolor=’w’.Matplotlib. labels = rgrids( (0. facecolor=’w’. the labels will appear at the specified radial distances and angles. or a Python file-like object. ’weight’ : ’bold’. pad_inches=0. bbox_inches=None. If the filename has no extension. (’Tom’. Arguments: fname: A string containing a path to a filename. currently only on postscript output papertype: One of ‘letter’. vmax=None. eps and svg. the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs.pyplot. or a sequence of color specifications of length N. s=20.pyplot. **kwargs) call signatures: scatter(x. marker=’o’. N. matplotlib pyplot . y are converted to 1-D sequences which must be of the same length. cmap=None. ‘b0’ through ‘b10’. s=20. for displaying a plot on top of a colored background on a web page. pdf. alpha=None. pad_inches: Amount of padding around the figure when bbox_inches is ‘tight’. Only supported for postscript output. Only the given portion of the figure is saved. edgecolor: the colors of the figure rectangle orientation: [ ‘landscape’ | ‘portrait’ ] not supported on all backends. try to figure out the tight bbox of the figure. norm=None. bbox_inches: Bbox in inches. faceted=True.0.scatter(x. It is a scalar or an array of the same length as x and y. **kwargs) Make a scatter plot of x versus y. transparent: If True. hold=None. format: One of the file extensions supported by the active backend. If that value is ‘auto’. c=’b’. c: a color. ‘ledger’. the axes patches will all be transparent. cmap=None. Keyword arguments: dpi: [ None | scalar > 0 ] The resolution in dots per inch. verts=None. c can be a single color format string. verts=None. The current Figure is updated to the parent of ax. or a sequence of N numbers to be mapped to colors using the cmap and 778 Chapter 50. If fname is not a string. matplotlib. ‘legal’. If None it will default to the value savefig. ps. y. ‘a0’ through ‘a10’. This is useful. c=’b’. bbox_extra_artists: A list of extra artists that will be considered when the tight bbox is calculated.sca(ax) Set the current Axes instance to ax. norm=None.Matplotlib. for example. vmax=None. linewidths=None. y. The transparency of these patches will be restored to their original values upon exit of this function. If ‘tight’. the backend determines the extension. marker=’o’. Keyword arguments: s: size in points^2. Release 1. facecolor. Most backends support png. vmin=None.dpi in the matplotlibrc file. linewidths=None. ‘executive’. remember to specify format to ensure that the correct backend is used.extension is used. alpha=None.1 savefig. vmin=None. matplotlib. where x. Matplotlib. matplotlib. Other keyword arguments: the color mapping and normalization arguments will be used only if c is an array of floats. If None.Colormap instance or registered name. use the kwarg combination marker = None. norm: [ None | Normalize ] A matplotlib. cmap is only used if c is an array of floats. Alternatively. y) vertices for a custom scatter symbol. however. y. c can be a 2-D array in which the rows are RGB or RGBA. and c may be masked arrays.cmap. 1. which will create a custom.1 norm specified via kwargs (see below).pyplot 779 . cmap: [ None | Colormap ] A matplotlib. use the default normalize(). in which case all masks will be combined and only unmasked points will be plotted. style.0.1.colors. norm is only used if c is an array of floats. regular symbol. 0): verts is a sequence of (x. defaults to rc image. angle).Normalize instance is used to scale luminance data to 0. If None. s. marker can be (verts. verts = verts. marker: can be one of: Value ’s’ ’o’ ’^’ ’>’ ’v’ ’<’ ’d’ ’p’ ’h’ ’8’ ’+’ ’x’ Description square circle triangle up triangle right triangle down triangle left diamond pentagon hexagon octagon plus cross The marker can also be a tuple (numsides. Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. Release 1. vmin/vmax: vmin and vmax are used in conjunction with norm to normalize luminance 50. Any or all of x.colors. numsides: the number of sides style: the style of the regular symbol: Value 0 1 2 3 Description a regular polygon a star-like symbol an asterisk a circle (numsides and angle is ignored) angle: the angle of rotation of the symbol Finally. Matplotlib. the min and max of the color array C is used.transforms. Optional kwargs control the Collection properties. matplotlib pyplot 780 . defaults to (lines.0. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples unknown a callable function matplotlib color arg or sequence of rgba tuples matplotlib color arg or sequence of rgba tuples a matplotlib. ‘dotted’ | (offset. alpha: 0 <= scalar <= 1 or None The alpha value for the patches linewidths: [ None | scalar | sequence ] If None. on-off-dash-seq) ] float or sequence of floats [True | False] unknown float or sequence of floats unknown [None|float|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown Continued on next page Chapter 50.Figure instance an id string any string [’solid’ | ‘dashed’. as required by RegularPolyCollection. Note if you pass a norm instance. If either are None. Note that this is a tuple. your settings for vmin and vmax will be ignored.figure. and if you set the linewidths argument you must set it as a sequence of floats. in particular: edgecolors: The string ‘none’ to plot faces with no outlines facecolors: The string ‘none’ to plot unfilled outlines Here are the standard descriptions of all the Collection kwargs: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap color colorbar contains edgecolor or edgecolors facecolor or facecolors figure gid label linestyle or linestyles or dashes linewidth or lw or linewidths lod norm offsets paths picker pickradius rasterized snap transform url urls Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.1 data.linewidth. ‘dashdot’.).Bbox instance [True | False] [ (Path. Release 1. Release 1.transforms. hot() or clim()).pyplot. None defaults to autosubs.axes. matplotlib. or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle Description unknown float (0. matplotlib.1. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x.Matplotlib. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] keyword arguments of plot() and 50.sci(im) Set the current image (target of colormap commands like jet().0 transparent through 1. semilogx() supports all the matplotlib. nonposx: [’mask’ | ‘clip’ ] non-positive values in x can be masked as invalid.semilogx(*args.set_xscale(). which depend on the number of decades in the plot.1 visible zorder Table 50. see set_xscale() for details.Bbox instance [True | False] [ (Path. Additional kwargs: hold = [True|False] overrides default hold state matplotlib.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. Notable keyword arguments: basex: scalar > 1 base of the x logarithm subsx: [ None | sequence ] The location of the minor xticks. The current image is an attribute of the current axes.22 – continued from previous page [True | False] any number A Collection instance is returned.pyplot.0.Axes. **kwargs) call signature: semilogx(*args. **kwargs) Make a plot with log scaling on the x axis.pyplot 781 . set_yscale().0.Axes.Transform instance a url string [True | False] 1D array 1D array any number See Also: loglog() For example code and figure Additional kwargs: hold = [True|False] overrides default hold state matplotlib.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. Notable keyword arguments: basey: scalar > 1 Base of the y logarithm keyword arguments of plot() and 782 Chapter 50. Release 1.figure. stride) float distance in points or callable pick function fn(artist. **kwargs) call signature: semilogy(*args. semilogy() supports all the matplotlib.’ | ’.Matplotlib. **kwargs) Make a plot with log scaling on the y axis. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.semilogy(*args.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.transforms. matplotlib pyplot .’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind.pyplot.axes.1 figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder a matplotlib. 0.0 transparent through 1.Bbox instance [True | False] [ (Path.1.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a float value in points [True | False] [ ’+’ | ’*’ | ’.transforms.Transform instance a url string [True | False] 1D array 50.figure.pyplot 783 .1 subsy: [ None | sequence ] The location of the minor yticks. event) float distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.Matplotlib.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/off ink in points 2D array (rows are x. see set_yscale() for details. stride) float distance in points or callable pick function fn(artist. which depend on the number of decades in the plot. Release 1. None defaults to autosubs.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color float value in points any matplotlib color any matplotlib color float None | integer | (startind. or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data drawstyle figure fillstyle gid label linestyle or ls linewidth or lw lod marker markeredgecolor or mec markeredgewidth or mew markerfacecolor or mfc markerfacecoloralt or mfcalt markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata Description unknown float (0. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.transforms. nonposy: [’mask’ | ‘clip’ ] non-positive values in y can be masked as invalid. matplotlib.’ | ’. linewidth=2. y1. color=’r’) setp() works with the MATLAB style string/value pairs or with python kwargs. x.’ | ’:’ | ’steps’ | ’None’ ] If you want to see all the properties that can be set.0. matplotlib pyplot .set_cmap(cmap) set the default colormap to cmap and apply to current image if any.0.01) y1 = sin(2*pi*x) y2 = sin(4*pi*x) lines = plot(x. **kwargs) matplotlib supports the use of setp() (“set property”) and getp() to set and get object properties. E. ’linestyle’) linestyle: [ ’-’ | ’--’ | ’-.0.Colormap instance. When actually setting values.setp(*args.pyplot.1 ydata zorder 1D array any number See Also: loglog() For example code and figure Additional kwargs: hold = [True|False] overrides default hold state matplotlib.. and their possible values. For example.1. y2) setp(lines. as well as to do introspection on the object. the following are equivalent: 784 Chapter 50. to set the linestyle of a line to be dashed. only the first instance in the sequence is used.. matplotlib. long output listing omitted setp() operates on a single instance or a list of instances.. For example. See help(colormaps) for more information.Matplotlib. Release 1.pyplot. you can do: >>> line. See register_cmap() and get_cmap().2.g. or the name of a registered colormap. linestyle=’--’) If you want to know the valid types of arguments. If you are in query mode introspecting the possible values. the following will make both lines thicker and red: >>> >>> >>> >>> >>> x = arange(0.3]) >>> setp(line. suppose you have a list of two lines. cmap must be a colors. all the instances will be set. you can provide the name of the property you want to set without a value: >>> setp(line. = plot([1. you can do: >>> setp(line) . window: callable or ndarray A function or a vector of length NFFT.window_hanning.pyplot. Fc=0. This corresponds to the n parameter in the call to fft(). Fc=0. ’color’. r’) >>> setp(lines. hold=None. Fs: scalar The sampling frequency (samples per time unit). Must be even. sides=’default’. pad_to: integer The number of points to which the data segment is padded when performing the FFT. pad_to=None. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. NFFT=256. If a function is passed as the argument. Data are split into NFFT length segments and the PSD of each section is computed. NFFT=256. Default gives the default behavior. The default value is 2. sides=’default’. The default is window_hanning(). freqs. numpy.1 >>> setp(lines.signal(). where the detrend parameter is a vector. It is used to calculate the Fourier frequencies. The default is None. xextent=None.blackman(). in matplotlib is it a function. xextent=None. this can give more points in the plot. designed to remove the mean or linear trend. The windowing function window is applied to each segment.detrend_none. window_none(). etc.bartlett(). ’linewidth’. which returns one-sided for real data and both 50.1. which specifies the number of data points used.hamming(). and detrend_linear(). scipy. it must take a data segment as an argument and return the windowed version of the segment. scipy. detrend=mlab. This can be different from NFFT. color=’r’) # MATLAB style # python style matplotlib. scale_by_freq=None. The default value is 0 (no overlap). but you can use a custom function as well. scale_by_freq=None. Unlike in MATLAB. **kwargs) call signature: specgram(x. window=mlab. a power 2 is most efficient. numpy. numpy. detrend: callable The function applied to each segment before fft-ing. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the PSD to return.specgram(x.0. matplotlib. allowing for more detail.signal. The pylab module defines detrend_none(). Release 1. **kwargs) Compute a spectrogram of data in x. and the amount of overlap of each segment is specified with noverlap. cmap=None. detrend_mean(). pad_to=None. Fs=2. in cycles per time unit. noverlap=128. cmap=None. 2. detrend=<function detrend_none at 0x3a1c668>.pyplot 785 . linewidth=2.Matplotlib. Fs=2.get_window(). To create window vectors see window_hanning(). window=<function window_hanning at 0x3a178c0>. noverlap: integer The number of points of overlap between blocks. noverlap=128. The default value is 256. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). any non-zero value will be plotted. if None use default determined by rc xextent: The image extent along the x-axis. bins. cmap: A matplotlib.Matplotlib.e. This can be overridden using the sides keyword argument. If precision is 0. See help(colormaps) for more information matplotlib.pyplot.max(bins)). See help(colormaps) for more information matplotlib. matplotlib pyplot . If x is complex.0. while ‘twosided’ forces two-sided. Fc: integer The center frequency of x (defaults to 0). aspect=’equal’. Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. **kwargs) spy(Z) plots the sparsity pattern of the 2-D array Z. hold=None. non-complex).spring() set the default colormap to spring and apply to current image if any. precision=0. precision=0. aspect=’equal’. else. The default is True for MATLAB compatibility. Release 1. which offsets the y extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.spy(Z. scale_by_freq: boolean Specifies whether the resulting density values should be scaled by the scaling frequency. which gives density in units of Hz^-1. freqs. markersize=None. im): •bins are the time points the spectrogram is calculated over •freqs is an array of frequencies •Pxx is a len(times) x len(freqs) array of power •im is a matplotlib. marker=None. markersize=None.Colormap instance. **kwargs) call signature: spy(Z. both positive and negative parts of the spectrum are shown.pyplot.cm. values of |Z| > precision will be plotted.xmax) The default is (0. ‘onesided’ forces the return of a one-sided PSD.image. This allows for integration over the returned frequency values. only the positive spectrum is shown.spectral() set the default colormap to spectral and apply to current image if any.AxesImage instance Note: If x is real (i. 786 Chapter 50.pyplot.1 for complex data. where bins is the return value from mlab.specgram() kwargs: Additional kwargs are passed on to imshow which makes the specgram image Return value is (Pxx. xextent = (xmin. marker=None. or to any scalar number to specify the aspect ratio of an array element directly. there is a special case: if precision is ‘present’. with the first index (row) increasing down and the second index (column) increasing to the right. even if it is identically zero. If marker and markersize are None.1 3 2 1 0 1 2 30 1000 800 600 400 200 00 5 10 15 20 5 10 15 20 For scipy. else.0. useful kwargs include: •cmap •alpha See Also: imshow() For image options. and any remaining kwargs passed to the plot() method. an image will be returned and any remaining kwargs are passed to imshow(). any value present in the array will be plotted.sparse. but only the marker style works for scipy. Two plotting styles are available: image or marker. set the aspect kwarg to ‘auto’ to allow the plot to fill the plot box. so that each array element occupies a square space.Matplotlib. The array will be plotted as it would be printed. By default aspect is ‘equal’.spmatrix instances.sparse. matplotlib. Release 1.pyplot 787 . If marker and markersize are None. a Line2D object will be returned with the value of marker determining the marker type. 50.spmatrix instances.1. Both are available for full arrays. y. useful kwargs include: •marker •markersize •color Useful values for marker include: •‘s’ square (default) •‘o’ circle •‘. cyan background and red marks. baseline).g. that x is uniformly increasing. e. y. **kwargs) call signature: step(x. x and y must be 1-D sequences. basefmt=’r-‘. Release 1.step(x. and it is assumed. A horizontal line at 0 is is plotted using basefmt. basefmt=’r-’) A stem plot plots vertical lines (using linefmt) at each x location from the baseline to y. markerfmt=’bo’. linefmt=’b-’. Keyword arguments: 788 Chapter 50. *args. use: cmap = mcolors. y. linefmt=’b-‘. Additional keyword args to step() are the same as those for plot(). but not checked. **kwargs) Make a step plot. hold=None) call signature: stem(x. matplotlib pyplot .0. and places a marker there using markerfmt.1 For controlling colors.ListedColormap([’c’. *args.py for a demo Additional kwargs: hold = [True|False] overrides default hold state matplotlib.Matplotlib.stem(x. stemlines.’ pixel See Also: plot() For plotting options Additional kwargs: hold = [True|False] overrides default hold state matplotlib. markerfmt=’bo’. y.’ point •‘.pyplot. Return value is a tuple (markerline.’r’]) If marker or markersize is not None. See Also: this document for details examples/pylab_examples/stem_plot.pyplot. the interval from x[i] to x[i+1] has level y[i+1] If ‘post’.py For an example Example: matplotlib. Defaults to False.2.colors for more information. matplotlib. axisbg=’y’) # creates 2nd subplot with yellow background Keyword arguments: axisbg: The background color of the subplot. Additional kwargs: hold = [True|False] overrides default hold state matplotlib.1.add_subplot() or the axes() command. 50.projections. Release 1.Figure.register_projection() See Also: axes() For additional information on axes() and subplot() keyword arguments. examples/pylab_examples/polar_scatter. colspan=1. 1 column. max(plotNum) == numRows * numCols You can leave out the commas if numRows <= numCols <= plotNum < 10. New subplots that overlap old will delete the old axes. colspan cells in each direction. the jumps in y occur half-way between the x-values. numCols. spanning rowspan.pyplot.1 where: [ ‘pre’ | ‘post’ | ‘mid’ ] If ‘pre’. This projection must have been previously registered. as in: subplot(211) # 2 rows.: from pylab import * plot([1.3]) # implicitly creates subplot(111) subplot(211) # overlaps. See matplotlib. Eg. creating axes with: subplot(numRows. rand(12)) subplot(212. which can be any valid color specifier. projection: A string giving the name of a custom projection to be used for the subplot.Matplotlib.subplot2grid(shape.figure. **kwargs) It creates a subplot in a grid of shape. If you do not want this behavior.pyplot 789 . rowspan=1. The index for loc is 0-based. at location of loc. that interval has level y[i] If ‘mid’. polar: A boolean flag indicating whether the subplot plot should be a polar projection. plotNum) where plotNum = 1 is the first plot number and increasing plotNums fill rows first. first (upper) plot subplot(111) is the default axis. use matplotlib. **kwargs) Create a subplot command. subplot(111) is killed plot(rand(12). See matplotlib.subplot(*args.pyplot.0. loc. shape[2]) subplotspec=gridspec.6 0. rowspan.2 0. sharex [bool] If True.0 0.subplots(nrows=1. the X axis will be shared amongst all subplots. Release 1. ncols=1.5 1. Defaults to 1. rowspan=1. in a single call.0.Matplotlib.0 subplot2grid(shape. Keyword arguments: nrows [int] Number of rows of the subplot grid.0 0.0 0. loc.pyplot.subplot_tool(targetfig=None) Launch a subplot tool window for targetfig (default gcf).5 1. squeeze=True. 790 Chapter 50. This utility wrapper makes it convenient to create common layouts of subplots.4 0.4 0.0 time (s) 1. sharex=False. Defaults to 1. matplotlib.0 0.8 0. colspan) subplot(subplotspec) matplotlib. matplotlib pyplot . colspan=1) is identical to gridspec=GridSpec(shape[0].SubplotTool instance is returned.5 2.5 0.widgets.1 1. subplot_kw=None. including the enclosing figure object.6 0.2 0. A matplotlib.new_subplotspec(loc. **fig_kw) Create a figure with a set of subplots already made. ncols [int] Number of columns of the subplot grid.80 1.pyplot.0 A tale of 2 subplots Damped oscillation 1 2 3 4 5 Undamped 0.0 0. sharey=False. set_title(‘Sharing Y axis’) ax2.2 hspace = 0.subplots(2. subplot_kw [dict] Dict with keywords passed to the add_subplot() call used to create each subplots.pyplot 791 . sharey=True) ax1.for Nx1 or 1xN subplots. the resulting single Axis object is returned as a scalar. even if it ends up being 1x1.figure. squeeze : bool If True.9 wspace = 0. top=None.subplots_adjust(*args.plot(x. y) # Four polar axes plt. the returned object is a 1-d numpy object array of Axis objects are returned as numpy 1-d arrays. ax [tuple] • fig is the Matplotlib Figure object • ax can be either a single axis object or an array of axis objects if more than one supblot was created. Note that all keywords not recognized above will be automatically included here. see above. .9 bottom = 0. unpack the output array immediately f. right=None. bottom=None. wspace=None.SubplotParams mechanism.2 # # # # # # the the the the the the left side of the subplots of the figure right side of the subplots of the figure bottom of the subplots of the figure top of the subplots of the figure amount of width reserved for blank space between subplots amount of height reserved for white space between subplots 50. hspace=None) Tune the subplot layout via the matplotlib. The dimensions of the resulting array can be controlled with the squeeze keyword. ax2) = plt. Examples: x = np. The parameter meanings (and suggested defaults) are: left = 0.pyplot.scatter(x. extra dimensions are squeezed out from the returned axis object: • if only one subplot is constructed (nrows=ncols=1). 2. for NxM subplots with N>1 and M>1 are returned as a 2d array. 2*np.sin(x**2) # Just a figure and one subplot f.subplots() ax. If False.subplots(1. matplotlib. Returns: fig.linspace(0. **kwargs) call signature: subplots_adjust(left=None. no squeezing at all is done: the returned axis object is always a 2-d array contaning Axis instances.0.plot(x. subplot_kw=dict(polar=True)) matplotlib. Release 1. y) ax1.1 top = 0. (ax1.1. the Y axis will be shared amongst all subplots. y) ax.pi. 400) y = np.1 sharex [bool] If True. ax = plt.125 right = 0.set_title(‘Simple plot’) # Two subplots. 2. fig_kw [dict] Dict with keywords passed to the figure() call.Matplotlib. colColours=None. you will explode. you may want to switch to the PS backend before running them to avoid having a bunch of GUI windows popup. colLabels=None.0. This feature is experimental. fontsize=12) matplotlib. if you have a bunch of PostScript scripts that you want to run from an interactive ipython session. the defaults are: •x = 0.Matplotlib. colLoc=’center’. and is only expected to work switching to an image backend. cellLoc=’right’.Table instance. Eg. matplotlib. kwargs control the Table properties: 792 Chapter 50.table.suptitle(*args.98 the y location of the text in figure coords •horizontalalignment = ‘center’ the horizontal alignment of the text •verticalalignment = ‘top’ the vertical alignment of the text A matplotlib.pyplot.pyplot.text. Returns a matplotlib. Release 1.switch_backend(newbackend) Switch the default backend to newbackend. loc=’bottom’. kwargs are matplotlib. Example: fig. rowColours=None. rowLoc=’left’. See help(colormaps) for more information matplotlib. rowLabels=None.summer() set the default colormap to summer and apply to current image if any.pyplot. cellColours=None.table(**kwargs) call signature: table(cellText=None.pyplot. use the Table class and add it to the axes with add_table().suptitle(’this is the figure title’.1 The actual defaults are controlled by the rc file matplotlib.Text instance is returned. If you try to interactively switch from one GUI backend to another.text. **kwargs) Add a centered title to the figure. bbox=None): Add a table to the current axes. matplotlib pyplot . Thanks to John Gill for providing the class and table.5 the x location of text in figure coords •y = 0. Using figure coordinates.Text properties. colWidths=None. Calling this command will close all open windows. For finer grained control over tables. 0. withdash: [ False | True ] Creates a TextWithDash instance instead of a Text instance. s.’matplotlib’. Release 1. Keyword arguments: fontdict: A dictionary to override the default text properties. horizontalalignment=’center’.patches.Bbox instance [True | False] [ (Path. The example below places text in the center of the axes: text(0.0 opaque) [True | False] an Axes instance a matplotlib.Matplotlib.transforms. Individual keyword arguments can be used to override any given parameter: text(x.0 transparent through 1. y. y. **kwargs) Add text in string s to axis at location x. s. bbox is a dictionary of matplotlib.Figure instance a float in points an id string any string [True | False] [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number matplotlib.0 is lower-left and 1.1.5. fontdict=None. you can specify text in axis coords (0. Transform) | Patch | None ] a callable function a matplotlib. transform = ax.pyplot.1 is upper-right). matplotlib. fontsize=12) The default transform specifies that text is in data coords.1 Property agg_filter alpha animated axes clip_box clip_on clip_path contains figure fontsize gid label lod picker rasterized snap transform url visible zorder Description unknown float (0. y. to set a background color) by using the keyword bbox. verticalalignment=’center’. s. the defaults are determined by your rc parameters.figure.transAxes) You can put a rectangular box around the text instance (eg. If fontdict is None.5.pyplot 793 . y. withdash=False.Rectangle properties.text(x. data coordinates. **kwargs) call signature: text(x. 0. For example: 50. fontdict=None. alternatively. Matplotlib.5)) Valid kwargs are matplotlib. bbox=dict(facecolor=’red’.Bbox instance [True | False] [ (Path.text.0 transparent through 1. Transform instance a url string [ ‘normal’ | ‘small-caps’ ] [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] [True | False] [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | float float any number 794 Chapter 50.1 text(x.y) [True | False | None] [ angle in degrees | ‘vertical’ | ‘horizontal’ ] unknown [ size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ unknown [ a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘c [ ‘normal’ | ‘italic’ | ‘oblique’] string or anything printable with ‘%s’ conversion. alpha=0. s.Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path color contains family or fontfamily or fontname or name figure fontproperties or font_properties gid horizontalalignment or ha label linespacing lod multialignment path_effects picker position rasterized rotation rotation_mode size or fontsize snap stretch or fontstretch style or fontstyle text transform url variant or fontvariant verticalalignment or va or ma visible weight or fontweight x y zorder Description unknown float (0. matplotlib pyplot . Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.transforms.0.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. y.figure.font_manager. Release 1.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string float (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|float|boolean|callable] (x.Figure instance a matplotlib. Return value is a list of tuples (lines. (’NE’. default is ‘both’. Examples: # set the locations of the radial gridlines and labels lines. set all parameters to defaults before processing other keyword arguments. If labels is None.360. frac is the fraction of the polar axes radius at which to place the label (1 is the edge). labels): •lines are Line2D instances •labels are Text instances. matplotlib. direction [’in’ | ‘out’] Puts ticks inside or outside the axes. angles is in degrees.1 matplotlib. labels = thetagrids() Otherwise the syntax is: lines. the labels will be fmt%angle. frac = 1. Keyword arguments: axis [’x’ | ‘y’ | ‘both’] Axis on which to operate.0.pyplot 795 .Matplotlib. reset [True | False] If True. **kwargs) Set/Get the theta locations of the gridlines and ticklabels. is a len(angles) list of strings of the labels to use at each angle. color Tick color. return a tuple (lines.90). labels=None. the labels argument is a list of strings. length Tick length in points. width Tick width in points.90) ) # set the locations and labels of the radial gridlines and labels lines. if not None. ’SW’.’SE’) ) matplotlib. labels. If no arguments are passed. Note that on input. labels = thetagrids( range(45. and on output it is a list of Text instances.360. labels) where lines is an array of radial gridlines (Line2D instances) and labels is an array of tick labels (Text instances): lines. 1.pyplot. Release 1.pyplot. 50. labels = thetagrids(angles.05 is outside the axes and 0. Eg.thetagrids(*args. labels = thetagrids( range(45.1) set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). accepts any mpl color spec. Default is False. ’NW’. which [’major’ | ‘minor’ | ‘both’] Default is ‘major’: apply arguments to major ticks only.95 is inside the axes. fmt=’%d’.tick_params(axis=’both’. **kwargs) Convenience method for changing the appearance of ticks and tick labels.1. if a numeric offset is specified.0) to include all numbers.1 pad Distance in points between tick and label. bottom. *args. Release 1. **kwargs) Set the title of the current axis to s. labelcolor Tick label color. zorder Tick and label zorder. 796 Chapter 50. n). colors=’r’) This will make all major ticks be red. labeltop. matplotlib pyplot . an AttributeError will be raised. the offset will be calculated as needed.pyplot.title(s. Tick labels will also be red.Matplotlib. top. pair of integers. Use (0. it will be used. Example: ax. scientific notation will be used for numbers outside the range 10‘-m‘:sup: to 10‘n‘:sup:. mpl color spec. colors Changes the tick color and the label color to the same value: mpl color spec. right Boolean or [’on’ | ‘off’]. no offset will be used. [True | False | offset]. ’verticalalignment’: ’baseline’. if style is ‘sci’.pyplot. and with dimensions 6 points by 2 points. labelsize Tick label font size in points or as a string (e. If the method is called when the ScalarFormatter is not the Formatter being used. pointing out of the box. left. length=6.0. Optional keyword arguments: Keyword style scilimits useOffset axis Description [ ‘sci’ (or ‘scientific’) | ‘plain’ ] plain turns off scientific notation (m. if False.ticklabel_format(**kwargs) Convenience method for manipulating the ScalarFormatter used by default for linear axes. controls whether to draw the respective ticks.g.tick_params(direction=’out’. labelleft. controls whether to draw the respective tick labels. matplotlib. ‘large’). Default font override is: override = {’fontsize’: ’medium’. width=2. ’horizontalalignment’: ’center’} See Also: text() for information on how override and the optional args work. labelright Boolean or [’on’ | ‘off’]. if True. matplotlib. [ ‘x’ | ‘y’ | ‘both’ ] Only the major ticks are affected. labelbottom. . y. Z... y. tricontour(x. .1 matplotlib. ..) triangles.pyplot 797 .. See Triangulation for a explanation of these possibilities. linewidth. 50. **kwargs) tricontour() and tricontourf() draw contour lines and filled contours.. different levels will be plotted in different colors in the order specified.. tricontour(x. or tricontour(x.) triangles... like ‘r’ or ‘red’.. matplotlib. Z. The remaining arguments may be: tricontour(. . etc). The triangulation can be specified in one of two ways. . tricontour(x. tricontour(.) triangles=triangles.tricontour(*args. tricontour(x. see below for more details. Z) where Z is the array of values to contour.. . function signatures and return values are the same for both versions. If a string.. The level values are chosen automatically.. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None. on an unstructured triangular grid.) triangles... y. y. origin. float.. Except as noted. tricontour(x.) mask.) in which case a Triangulation object will be created. all levels will be plotted in this color.1... respectively. rgb. mask=mask.. C = tricontour(... the colormap specified by cmap will be used.) returns a TriContourSet object. one per point in the triangulation. Z..pyplot. N) contour N automatically-chosen levels. Release 1. y.) mask=mask... y... tricontour(. either: tricontour(triangulation.. **kwargs) Use keyword args to control colors.. V) fill the (len(V)-1) regions between the values in V tricontour(Z. mask... If a tuple of matplotlib color args (string. tricontour(x. . cmap . y.. .) where triangulation is a Triangulation object. V) draw contour lines at the values specified in sequence V tricontourf(.0.. .Matplotlib. If cmap is None and colors is None. but can be set via matplotlib. the ‘solid’ is used. locator: [ None | ticker.y1) ] If origin is not None.. If origin is None.0. a default Colormap is used.colors.0).y0. location (0.-1]. and (x1..pyplot. This keyword is not active if X and Y are specified in the call to contour. different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. then extent is interpreted as in matplotlib. This keyword is not active if X and Y are specified in the call to contour.Matplotlib. level1. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. matplotlib pyplot . If ‘image’.origin will be used.0]. xunits.set_over() methods. the position of Z[0. If a number.1 alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None. In this case.set_under() and matplotlib. .colors.linewidth in matplotlibrc is used.Normalize instance for scaling data values to colors. not a corner. extent: [ None | (x0. contour levels are automatically added to one or both ends of the range so that all data are included. the first value of Z will correspond to the lower left corner.Colormap. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range.Locator subclass ] If locator is None. Release 1. If a tuple. 798 Chapter 50. the default width in lines. all levels will be plotted with this linewidth. norm: [ None | Normalize ] A matplotlib. tricontour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None. levels [level0. then (x0.. the default linear scaling is used. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None. leveln] A list of floating point numbers indicating the level curves to draw.colors. the rc value for image. If norm is None and colors is None.0] is the center of the pixel.units. the default MaxNLocator is used.Colormap. y0) is the position of Z[0. y1) is the position of Z[-1.x1. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’.imshow(): it gives the outer pixel boundaries. The locator is used to determine the contour levels if they are not given explicitly via the V argument.ConversionInterface. 0 0.25 0. Release 1.0.00 50. If this iterable is shorter than the number of contour levels it will be repeated as necessary.00 1. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array.pyplot 799 .50 0.0 0. Note: tricontourf fills intervals that are closed at the top.01.75 0. that is.5 1.1 linestyles can also be an iterable of the above strings specifying a set of linestyles to be used.75 1. If contour is using a monochrome colormap and the contour level is less than 0. tricontourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0.25 0. matplotlib.5 1.5 0. so this option may be removed. for boundaries z1 and z2. This may never actually be advantageous.Matplotlib.5 0. no subdivision of the domain. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. then the linestyle specified in contour.50 0.00 0.1.negative_linestyle in matplotlibrc will be used. then that minimum value will be included in the lowest interval. Examples: Contour plot of Delaunay triangulation 1.0 0.0 0.0 0. .60 where triangulation is a Triangulation object. y..) triangles. tricontour(x..tricontourf(*args.95 0... y.) mask=mask. Release 1.80 0. matplotlib pyplot . . respectively..Matplotlib. .) triangles.) mask. either: tricontour(triangulation.. Except as noted.. or tricontour(x.) triangles=triangles. y. tricontour(x. The triangulation can be specified in one of two ways. **kwargs) tricontour() and tricontourf() draw contour lines and filled contours. y.85 0.. .0. See Triangulation for a explanation of these possibilities.00 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) Additional kwargs: hold = [True|False] overrides default hold state matplotlib..90 0.. y..70 0.1 Contour plot of user-specified triangulation 1. tricontour(x..75 0.. tricontour(x. The remaining arguments may be: 800 Chapter 50.) triangles.. tricontour(x. on an unstructured triangular grid. . tricontour(x. mask=mask..) 0.) in which case a Triangulation object will be created. y. .. function signatures and return values are the same for both versions. . y. mask.65 0. .pyplot. . tricontour(. different levels will be plotted in different colors in the order specified.Normalize instance for scaling data values to colors. all levels will be plotted in this color.. etc).colors. the first value of Z will correspond to the lower left corner.Matplotlib. level1.. ... see below for more details. cmap ..pyplot.0] is the center of the pixel. origin.. not a corner. If origin 50. tricontour(. linewidth. norm: [ None | Normalize ] A matplotlib. If a tuple of matplotlib color args (string.. Z) where Z is the array of values to contour. like ‘r’ or ‘red’. the colormap specified by cmap will be used.y0.. This keyword is not active if X and Y are specified in the call to contour. leveln] A list of floating point numbers indicating the level curves to draw. Z. Z.y1) ] If origin is not None.. If ‘image’.. float. matplotlib. In this case.. the default linear scaling is used. The level values are chosen automatically. Release 1. the rc value for image..1 tricontour(. then extent is interpreted as in matplotlib. the position of Z[0.... one per point in the triangulation.. N) contour N automatically-chosen levels.) returns a TriContourSet object. Z.0). C = tricontour(.pyplot 801 .. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None. levels [level0. alpha: float The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None. V) fill the (len(V)-1) regions between the values in V tricontour(Z.1.0. rgb.x1. location (0.. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None.imshow(): it gives the outer pixel boundaries. If cmap is None and colors is None. If norm is None and colors is None. a default Colormap is used.origin will be used. **kwargs) Use keyword args to control colors. V) draw contour lines at the values specified in sequence V tricontourf(. If a string. extent: [ None | (x0. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’.Colormap. then the linestyle specified in contour. Release 1. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. the default width in lines. so this option may be removed. then (x0. but can be set via matplotlib. If a tuple. If this iterable is shorter than the number of contour levels it will be repeated as necessary. y1) is the position of Z[-1. tricontour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None. tricontourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0. This may never actually be advantageous.units.0]. then that minimum value will be included in the lowest interval. 802 Chapter 50.Locator subclass ] If locator is None.set_under() and matplotlib. contour levels are automatically added to one or both ends of the range so that all data are included. for boundaries z1 and z2. the filled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range. y0) is the position of Z[0. xunits.linewidth in matplotlibrc is used. different levels will be plotted with different linewidths in the order specified linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. that is.Matplotlib. matplotlib pyplot . If contour is using a monochrome colormap and the contour level is less than 0. If a number.ConversionInterface.set_over() methods. and (x1. no subdivision of the domain. the ‘solid’ is used.-1]. locator: [ None | ticker. the default MaxNLocator is used. all levels will be plotted with this linewidth.colors. Note: tricontourf fills intervals that are closed at the top. The locator is used to determine the contour levels if they are not given explicitly via the V argument. Chunking introduces artifacts at the chunk boundaries unless antialiased is False.1 is None.colors.Colormap.0.negative_linestyle in matplotlibrc will be used. This keyword is not active if X and Y are specified in the call to contour. matplotlib. y.0 0.1. **kwargs) Create a pseudocolor plot of an unstructured triangular grid to the Axes. 50. y.) mask=mask. the array of color values. y.) in which case a Triangulation object will be created. either: tripcolor(triangulation. .5 1.. See Triangulation for a explanation of these possibilities... tripcolor(x.) where triangulation is a Triangulation object. tripcolor(x. or tripcolor(x.pyplot 803 .01.tripcolor(*args. The colors used for each triangle are from the mean C of the triangle’s three points.) mask.0.75 1.Matplotlib.. The next argument must be C.00 0.50 0..0 0.) triangles=triangles..5 1. tripcolor(x. y. y. y.5 0...0 0. .00 1.) triangles..50 0. . .. tripcolor(x. tripcolor(x..pyplot. The triangulation can be specified in one of two ways.75 0..1 Examples: Contour plot of Delaunay triangulation 1.5 0.) triangles.. .. . y. one per point in the triangulation.0 0..0 0.. .25 0. mask=mask. tripcolor(x.25 0.00 Additional kwargs: hold = [True|False] overrides default hold state matplotlib. mask. Release 1. .) triangles. mask=mask. . Release 1..) mask.0. y. 804 Chapter 50. .) in which case a Triangulation object will be created. triplot(x. or triplot(x...95 0.triplot(*args.) triangles.) triangles.) where triangulation is a Triangulation object. triplot(x.) mask=mask.. triplot(x...70 0.65 0. y. y. y. triplot(x. Example: 0.. triplot(x.75 0. matplotlib pyplot .90 0. **kwargs) Draw a unstructured triangular grid as lines and/or markers to the Axes.. .85 0. y. See Triangulation for a explanation of these possibilities... y.80 0...) triangles=triangles. The triangulation to plot can be specified in one of two ways. triplot(x.00 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) The remaining kwargs are the same as for pcolor(). y. .. mask.pyplot. .Matplotlib. . . either: triplot(triangulation.1 Contour plot of user-specified triangulation 1.) triangles.60 Additional kwargs: hold = [True|False] overrides default hold state matplotlib.. ... pyplot. linestyles=’solid’. ymax.0 0.4 0.pyplot.vlines(x. Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib. See Also: examples/api_examples/two_scales. ymax.5 1. linestyles=’solid’) 50.0 0.4 0.0 0.5 0.01.0 tripcolor of Delaunay triangulation 0. The ticks for ax2 will be placed on the right.pyplot 805 . color=’k’.0 0. colors=’k’. ymin.6 0. **kwargs) call signature: vlines(x. and the ax2 instance is returned.2 0. Release 1.1. and the ax2 instance is returned. matplotlib.5 1.twinx(ax=None) Make a second axes overlay ax (or the current axes if ax is None) sharing the xaxis. label=’‘.Matplotlib.twiny(ax=None) Make a second axes overlay ax (or the current axes if ax is None) sharing the yaxis. matplotlib. The ticks for ax2 will be placed on the top.5 0.8 The remaining args and kwargs are the same as for plot().0 0. hold=None.8 0.py For an example matplotlib. ymin.6 0.0.pyplot.1 1.2 0. ymin or ymax can be scalars or len(x) numpy arrays.96 0.72 0.Bbox instance [True | False] Continued on next page Chapter 50.64 Plot vertical lines at each x from ymin to ymax.88 0. Release 1. kwargs are LineCollection properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on Description unknown float or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of floats a matplotlib.transforms.76 0.0. else the heights of the lines are determined by ymin and ymax.1 tripcolor of user-specified triangulation 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) 0. If they are scalars.68 0. either a single color or a len(x) list of colors linestyles one of [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] Returns the matplotlib.collections.Matplotlib.92 0. matplotlib pyplot 806 .LineCollection that was added. then the respective values are constant.84 0. colors a line collections color args.80 0. detrend=<function detrend_none at 0x3a1c668>.xcorr(x. normed=True. usevlines=True.0. **kwargs) 50. Transform) | Patch | None ] cmap a colormap or registered colormap name color matplotlib color arg or sequence of rgba tuples colorbar unknown contains a callable function edgecolor or edgecolors matplotlib color arg or sequence of rgba tuples facecolor or facecolors matplotlib color arg or sequence of rgba tuples figure a matplotlib.pyplot 807 .1 Table 50. If timeout is negative. does not timeout. hold=None.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. See help(colormaps) for more information matplotlib. **kwargs) call signature: waitforbuttonpress(self.pyplot. ‘dashdot’.pyplot. timeout=-1) Blocking call to interact with the figure.26 – continued from previous page clip_path [ (Path. matplotlib. on-off-dash-seq) ] linewidth or lw or linewidths float or sequence of floats lod [True | False] norm unknown offsets float or sequence of floats paths unknown picker [None|float|boolean|callable] pickradius unknown rasterized [True | False | None] segments unknown snap unknown transform Transform instance url a url string urls unknown verts unknown visible [True | False] zorder any number Additional kwargs: hold = [True|False] overrides default hold state matplotlib.1.Matplotlib. ‘dotted’ | (offset.winter() set the default colormap to winter and apply to current image if any.figure.waitforbuttonpress(*args. matplotlib. This will return True is a key was pressed. maxlags=10. False if a mouse button was pressed and None if timeout was reached without either being pressed. Release 1. y.pyplot. 5 0.1 1. c.correlate() with mode = 2. normalize the data by the cross correlation at 0-th lag.Matplotlib. usevlines=True. matplotlib pyplot .5 1. which are Line2D properties. If usevlines is True: vlines() rather than plot() is used to draw vertical lines from the origin to the xcorr.0 call signature: 0. 808 Chapter 50.0 0.0 def xcorr(self.5 0. c. Otherwise the plotstyle is determined by the kwargs. The cross correlation is performed with numpy. The default linestyle is None and the default marker is ‘o’. maxlags=10.01. normed=True. x and y must be equal length.5 triplot of Delaunay triangulation 1. x and y are detrended by the detrend callable (default no normalization). **kwargs) Return value is a tuple (lags.0. x. **kwargs): Plot the cross correlation between x and y. If normed = True.0 0. line) where: •lags are a length 2*maxlags+1 lag vector •c is the 2*maxlags+1 auto correlation vector •line is a Line2D instance returned by plot(). y. Data are plotted as plot(lags. detrend=mlab. Release 1.0 0.detrend_none. though these can be overridden with keyword args. 0.pyplot 809 . b) where linecol is the matplotlib. c.1. ’verticalalignment’ : ’top’. **kwargs) Set the x axis label of the current axis to s Default override is: override = { ’fontsize’ : ’small’. ’horizontalalignment’ : ’center’ } 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) The return value is a tuple (lags. linecol.pyplot.1 triplot of user-specified triangulation 58 Latitude (degrees) Example: xcorr() above. matplotlib. Example: Additional kwargs: hold = [True|False] overrides default hold state matplotlib.xlabel(s. *args.Matplotlib. See Also: 50.LineCollection instance and b is the x-axis. Release 1.collections. and acorr() below. maxlags is a positive integer detailing the number of lags to show. The default value of None will return all (2*len(x)-1) lags. 2 0.15 0. xmax = xlim() xlim( (xmin.xscale(*args. xmax # set the xlim to xmin.260 40 20 0 20 40 60 40 20 0 20 40 60 text() For information on how override and the optional args work matplotlib. Release 1. xmax ) # return the current xlim # set the xlim to xmin. eg. xmax If you do not specify args.xlim(*args.10 0.20 0.05 0.0 0.2060 1. matplotlib pyplot .0.: xlim(xmax=3) # adjust the max leaving min unchanged xlim(xmin=1) # adjust the min leaving max unchanged The new axis limits are returned as a length 2 tuple.00 0.0 0.4 0. you can pass the xmin and xmax as kwargs. **kwargs) Set the scaling for the x-axis: ‘linear’ | ‘log’ | ‘symlog’ Different keywords may be accepted.1 0. matplotlib. depending on the scale: ‘linear’ 810 Chapter 50.10 0.8 0.pyplot.Matplotlib.pyplot. xmax) ) xlim( xmin.15 0.6 0. **kwargs) Set/Get the xlimits of the current axes: xmin.05 0. **kwargs) call signature: xscale(scale. 8. 9] will place 10 logarithmically spaced minor ticks between each major tick. Defaults override is: override = { ’fontsize’ ’verticalalignment’ ’horizontalalignment’ ’rotation’=’vertical’ : : : : ’small’. Should be a sequence of integers. labels = xticks() # set the locations of the xticks xticks( arange(6) ) # set the locations and labels of the xticks xticks( arange(5). For example. } See Also: 50. 7. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick.month_name[1:13]. **kwargs) Set the y axis label of the current axis to s. 6. ’Harry’. ’Sue’) ) The keyword args. 1. x) within which the plot is linear (to avoid having the plot go to infinity around zero).pyplot. 3.ylabel(s.1. *args.Matplotlib. ’Dick’. For example. 4. if any. ’right’.pyplot.1 ‘log’ basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. to rotate long labels: xticks( arange(12).pyplot 811 . ’Sally’. matplotlib. 7. 4. locs. labels where locs is an array of tick locations and # labels is an array of tick labels. Release 1. 2. in a log10 scale: [0. 1. rotation=17 ) matplotlib. 8. 2. ’center’.0. Should be a sequence of integers. in a log10 scale: [0. **kwargs) Set/Get the xlimits of the current ticklocs and labels: # return locs. are Text properties. 6. calendar. 9] will place 10 logarithmically spaced minor ticks between each major tick. 5. subsx/subsy: Where to place the subticks between each major tick. 3. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. (’Tom’. matplotlib. 5.xticks(*args. For example. matplotlib pyplot .Matplotlib. **kwargs) Set the scaling for the y-axis: ‘linear’ | ‘log’ | ‘symlog’ Different keywords may be accepted. For example. ymax ) # return the current ylim # set the ylim to ymin.ylim(*args. **kwargs) Set/Get the ylimits of the current axes: ymin. Should be a sequence of integers. 2. depending on the scale: ‘linear’ ‘log’ basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. 4. x) within which the plot is linear (to avoid having the plot go to infinity around zero). 7. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick. 3. in a log10 scale: [0. you can pass the ymin and ymax as kwargs. 2. 3.yscale(*args. matplotlib. 4. Release 1. matplotlib. For example. **kwargs) Set/Get the ylimits of the current ticklocs and labels: 812 Chapter 50.pyplot. in a log10 scale: [0. ymax # set the ylim to ymin. Should be a sequence of integers.1 text() For information on how override and the optional args work.pyplot. 6.yticks(*args.: ylim(ymax=3) # adjust the max leaving min unchanged ylim(ymin=1) # adjust the min leaving max unchanged The new axis limits are returned as a length 2 tuple. 6. 7. 9] will place 10 logarithmically spaced minor ticks between each major tick. ymax If you do not specify args. eg. **kwargs) call signature: yscale(scale. matplotlib. subsx/subsy: Where to place the subticks between each major tick. ymax = ylim() ylim( (ymin. 9] will place 10 logarithmically spaced minor ticks between each major tick. ymax) ) ylim( ymin.pyplot. 1. 5. 8. 1. 5.0. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. 8. ’Harry’. to rotate long labels: yticks( arange(12).1. ’Sue’) ) The keyword args. calendar. ’Dick’. matplotlib.1 # return locs. labels where locs is an array of tick locations and # labels is an array of tick labels. Release 1.pyplot 813 . labels = yticks() # set the locations of the yticks yticks( arange(6) ) # set the locations and labels of the yticks yticks( arange(5).0. rotation=45 ) 50. locs.Matplotlib. are Text properties. (’Tom’. ’Sally’.month_name[1:13]. if any. For example. Release 1. matplotlib pyplot .0.1 814 Chapter 50.Matplotlib. that are not available in numpy 815 .CHAPTER FIFTYONE MATPLOTLIB NXUTILS 51.1 matplotlib.nxutils general purpose numerical utilities. eg for computational geometry. Release 1.Matplotlib.1 816 Chapter 51.0. matplotlib nxutils . The default position is (’outward’.spines.patches. depending if function:~matplotlib.set_patch_line or function:~matplotlib. Spines draw a line or a circle.Patch an axis spine – the line noting the data area boundaries Spines are the lines connecting the axis tick marks and noting the boundaries of the data area.Spine. Spines are subclasses of class:~matplotlib.Spine(axes.patches.spines.set_position for more information.1 matplotlib.set_patch_circle has been called.Patch. spine_type.spines.spines. Line-like is the default. They can be placed at arbitrary positions.Spine.spine class matplotlib.CHAPTER FIFTYTWO MATPLOTLIB SPINE 52. •axes : the Axes instance containing the spine •spine_type : a string specifying the spine type •path : the path instance used to draw the spine Valid kwargs are: 817 . **kwargs) Bases: matplotlib. and inherit much of their behavior. See function:~matplotlib. path.Spine.0). renderer. get_patch_transform() get_path() get_position() get the spine position get_smart_bounds() get whether the spine has smart bounds get_spine_transform() 818 Chapter 52.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] float or None for default [True | False] unknown [None|float|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number classmethod circular_spine(axes.Matplotlib. or None for default. **kwargs) (staticmethod) Returns a circular Spine.0. matplotlib spine . center. **kwargs) get_bounds() Get the bounds of the spine. or None for default. or ‘none’ for no color mpl color spec. Release 1. cla() Clear the current spine draw(artist.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. or ‘none’ for no color a matplotlib. *args.Bbox instance [True | False] [ (Path.transforms. radius.figure. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.1 Property agg_filter alpha animated antialiased or aa axes clip_box clip_on clip_path color contains edgecolor or ec facecolor or fc figure fill gid hatch label linestyle or ls linewidth or lw lod path_effects picker rasterized snap transform url visible zorder Description unknown float or None [True | False] [True | False] or None for default an Axes instance a matplotlib. 1. set_edgecolor() For setting the edge or face color individually. 0. radius) set the spine to be circular set_patch_line() set the spine to be linear set_position(position) set the position of the spine Spine position is specified by a 2 tuple of (position type.) •‘axes’ : place the spine at the specified Axes coordinate (from 0.5) •‘zero’ -> (‘data’. set_color(c) Set the edgecolor. matplotlib.0).1 get the spine transform is_frame_like() return True if directly on axes frame This is useful for determining if a spine is the edge of an old style MPL plot.spine 819 . shorthand notations define a special positions: •‘center’ -> (‘axes’. ACCEPTS: matplotlib color arg or sequence of rgba tuples See Also: set_facecolor(). If so. this function will return True. classmethod linear_spine(axes. **kwargs) (staticmethod) Returns a linear Spine.0. The position types are: •‘outward’ : place the spine out from the data area by the specified number of points. amount). register_axis(axis) register an axis An axis should be registered with its corresponding spine from the Axes instance.0. Additionally. high) Set the bounds of the spine. •‘data’ : place the spine at the specified data coordinate. set_patch_circle(center. This allows the spine to clear any axis properties when needed. Release 1.0-1.Matplotlib. set_bounds(low. (Negative values specify placing the spine inward. spine_type.0) set_smart_bounds(value) set the spine and associated axis to have smart bounds 52. Release 1. matplotlib spine .Matplotlib.1 820 Chapter 52.0. Generic tick locators and formatters are provided. where x = range(len(y))) LinearLocator evenly spaced ticks from min to max LogLocator logarithmically ticks from min to max MultipleLocator ticks and range are a multiple of base.1 Tick locating and formatting This module contains classes to support completely configurable tick locating and formatting. they are used by the Axis class to support major and minor tick locating and formatting. either integer or float OldAutoLocator choose a MultipleLocator and dyamically reassign it for intelligent ticking during navigation MaxNLocator finds up to a max number of ticks at nice locations AutoLocator MaxNLocator with simple defaults. as well as domain specific custom ones.ticker 53. 821 . You initialize this with a base. Although the locators know nothing about major or minor ticks.. The locators handle autoscaling of the view limits based on the data limits.1. A useful semi-automatic tick locator is MultipleLocator. eg 10.1 matplotlib.CHAPTER FIFTYTHREE MATPLOTLIB TICKER 53. Tick locating The Locator class is the base class for all tick locators. and the choosing of tick locations. This is the default tick locator for most plotting. The Locator subclasses defined here are NullLocator No ticks FixedLocator Tick locations are fixed IndexLocator locator for index plots (eg. and it picks axis limits and ticks that are multiples of your base. The formatter operates on a single tick value and returns a string to the axis.set_major_formatter( ax.yaxis.set_major_locator( ax.set_minor_formatter( xmajorFormatter xminorFormatter ymajorFormatter yminorFormatter ) ) ) ) See pylab_examples-major_minor_demo1 for an example of setting major an minor ticks.see the dates module You can define your own locator by deriving from Locator.yaxis.set_minor_locator( xmajorLocator xminorLocator ymajorLocator yminorLocator ) ) ) ) The default minor locator is the NullLocator. The formatter class has access to the axis view and data limits. use one of the following methods: ax.yaxis.dates module for more information and examples of using date locators and formatters.xaxis.yaxis. If you want to override the default locator.set_minor_formatter( ax.set_minor_locator( ax.set_major_formatter( ax. eg no minor ticks on by default. and you will probably want to override the autoscale method to set the view limits from the data limits. use one of the above or a custom locator and pass it to the x or y axis instance. To control the major and minor tick label formats. The relevant methods are: ax.xaxis. autopick the fmt string LogFormatter formatter for log axes You can derive your own formatter from the Formatter base class by simply overriding the __call__ method. NullFormatter no labels on the ticks IndexFormatter set the strings from a list of labels FixedFormatter set the strings manually for the labels FuncFormatter user defined function sets the labels FormatStrFormatter use a sprintf format string ScalarFormatter default formatter for scalars. class matplotlib. Tick formatting Tick formatting is controlled by classes derived from Formatter.TickHelper class DummyAxis get_data_interval() 822 Chapter 53. See the matplotlib.1 There are a number of locators specialized for date locations .xaxis.Matplotlib. You must override the __call__ method.ticker. matplotlib ticker . Release 1.set_major_locator( ax.xaxis.0. which returns a sequence of locations. Matplotlib, Release 1.0.1 get_view_interval() set_data_interval(vmin, vmax) set_view_interval(vmin, vmax) TickHelper.create_dummy_axis() TickHelper.set_axis(axis) TickHelper.set_bounds(vmin, vmax) TickHelper.set_data_interval(vmin, vmax) TickHelper.set_view_interval(vmin, vmax) class matplotlib.ticker.Formatter Bases: matplotlib.ticker.TickHelper Convert the tick location to a string fix_minus(s) some classes may want to replace a hyphen for minus with the proper unicode symbol as described here. The default is to do nothing Note, if you use this method, eg in :meth‘format_data‘ or call, you probably don’t want to use it for format_data_short() since the toolbar uses this for interative coord reporting and I doubt we can expect GUIs across platforms will handle the unicode correctly. So for now the classes that override fix_minus() should have an explicit format_data_short() method format_data(value) format_data_short(value) return a short string version get_offset() set_locs(locs) class matplotlib.ticker.FixedFormatter(seq) Bases: matplotlib.ticker.Formatter Return fixed strings for tick labels seq is a sequence of strings. For positions i < len(seq) return seq[i] regardless of x. Otherwise return ‘’ get_offset() set_offset_string(ofs) class matplotlib.ticker.NullFormatter Bases: matplotlib.ticker.Formatter Always return the empty string class matplotlib.ticker.FuncFormatter(func) Bases: matplotlib.ticker.Formatter User defined function for formatting 53.1. matplotlib.ticker 823 Matplotlib, Release 1.0.1 class matplotlib.ticker.FormatStrFormatter(fmt) Bases: matplotlib.ticker.Formatter Use a format string to format the tick class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False) Bases: matplotlib.ticker.Formatter Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter. fix_minus(s) use a unicode minus rather than hyphen format_data(value) return a formatted string representation of a number format_data_short(value) return a short formatted string representation of a number get_offset() Return scientific notation, plus offset get_useOffset() pprint_val(x) set_locs(locs) set the locations of the ticks set_powerlimits(lims) Sets size thresholds for scientific notation. e.g. formatter.set_powerlimits((-3, 4)) sets the pre-2007 default in which scientific notation is used for numbers less than 1e-3 or greater than 1e4. See also set_scientific(). set_scientific(b) True or False to turn scientific notation on or off see also set_powerlimits() set_useOffset(val) useOffset class matplotlib.ticker.LogFormatter(base=10.0, labelOnlyBase=True) Bases: matplotlib.ticker.Formatter Format values for log axis; if attribute decadeOnly is True, only the decades will be labelled. base is used to locate the decade tick, which will be the only one to be labeled if labelOnlyBase is False base(base) change the base for labeling - warning: should always match the base used for LogLocator 824 Chapter 53. matplotlib ticker Matplotlib, Release 1.0.1 format_data(value) format_data_short(value) return a short formatted string representation of a number label_minor(labelOnlyBase) switch on/off minor ticks labeling pprint_val(x, d) class matplotlib.ticker.LogFormatterExponent(base=10.0, labelOnlyBase=True) Bases: matplotlib.ticker.LogFormatter Format values for log axis; using exponent = log_base(value) base is used to locate the decade tick, which will be the only one to be labeled if labelOnlyBase is False class matplotlib.ticker.LogFormatterMathtext(base=10.0, labelOnlyBase=True) Bases: matplotlib.ticker.LogFormatter Format values for log axis; using exponent = log_base(value) base is used to locate the decade tick, which will be the only one to be labeled if labelOnlyBase is False class matplotlib.ticker.Locator Bases: matplotlib.ticker.TickHelper Determine the tick locations; Note, you should not use the same locator between different Axis because the locator stores references to the Axis data and view limits autoscale() autoscale the view limits pan(numsteps) Pan numticks (can be positive or negative) raise_if_exceeds(locs) raise a RuntimeError if Locator attempts to create more than MAXTICKS locs refresh() refresh internal information based on current lim view_limits(vmin, vmax) select a scale for the range from vmin to vmax Normally This will be overridden. zoom(direction) Zoom in/out on axis; if direction is >0 zoom in, else zoom out class matplotlib.ticker.IndexLocator(base, offset) Bases: matplotlib.ticker.Locator 53.1. matplotlib.ticker 825 Matplotlib, Release 1.0.1 Place a tick on every multiple of some base number of points plotted, eg on every 5th point. It is assumed that you are doing index plotting; ie the axis is 0, len(data). This is mainly useful for x ticks. place ticks on the i-th data points where (i-offset)%base==0 class matplotlib.ticker.FixedLocator(locs, nbins=None) Bases: matplotlib.ticker.Locator Tick locations are fixed. If nbins is not None, the array of possible positions will be subsampled to keep the number of ticks <= nbins +1. The subsampling will be done so as to include the smallest absolute value; for example, if zero is included in the array of possibilities, then it is guaranteed to be one of the chosen ticks. class matplotlib.ticker.NullLocator Bases: matplotlib.ticker.Locator No ticks class matplotlib.ticker.LinearLocator(numticks=None, presets=None) Bases: matplotlib.ticker.Locator Determine the tick locations The first time this function is called it will try to set the number of ticks to make a nice tick partitioning. Thereafter the number of ticks will be fixed so that interactive navigation will be nice Use presets to set locs based on lom. A dict mapping vmin, vmax->locs view_limits(vmin, vmax) Try to choose the view limits intelligently class matplotlib.ticker.LogLocator(base=10.0, subs=[1.0], numdecs=4) Bases: matplotlib.ticker.Locator Determine the tick locations for log axes place ticks on the location= base**i*subs[j] base(base) set the base of the log scaling (major tick every base**i, i integer) subs(subs) set the minor ticks the log scaling every base**i*subs[j] view_limits(vmin, vmax) Try to choose the view limits intelligently class matplotlib.ticker.AutoLocator Bases: matplotlib.ticker.MaxNLocator class matplotlib.ticker.MultipleLocator(base=1.0) Bases: matplotlib.ticker.Locator Set a tick on every integer that is multiple of base in the view interval view_limits(dmin, dmax) Set the view limits to the nearest multiples of base that contain the data 826 Chapter 53. matplotlib ticker Matplotlib, Release 1.0.1 class matplotlib.ticker.MaxNLocator(*args, **kwargs) Bases: matplotlib.ticker.Locator Select no more than N intervals at nice locations. Keyword args: nbins Maximum number of intervals; one less than max number of ticks. steps Sequence of nice numbers starting with 1 and ending with 10; e.g., [1, 2, 4, 5, 10] integer If True, ticks will take only integer values. symmetric If True, autoscaling will result in a range symmetric about zero. prune [’lower’ | ‘upper’ | ‘both’ | None] Remove edge ticks – useful for stacked or ganged plots where the upper tick of one axes overlaps with the lower tick of the axes above it. If prune==’lower’, the smallest tick will be removed. If prune==’upper’, the largest tick will be removed. If prune==’both’, the largest and smallest ticks will be removed. If prune==None, no ticks will be removed. bin_boundaries(vmin, vmax) set_params(**kwargs) view_limits(dmin, dmax) 53.1. matplotlib.ticker 827 Matplotlib, Release 1.0.1 828 Chapter 53. matplotlib ticker CHAPTER FIFTYFOUR MATPLOTLIB UNITS 54.1 matplotlib.units The classes here provide support for using custom classes with matplotlib, eg those that do not expose the array interface but know how to converter themselves to arrays. It also supoprts classes with units and units conversion. Use cases include converters for custom objects, eg a list of datetime objects, as well as for objects that are unit aware. We don’t assume any particular units implementation, rather a units implementation must provide a ConversionInterface, and the register with the Registry converter dictionary. For example, here is a complete implementation which support plotting with native datetime objects import matplotlib.units as units import matplotlib.dates as dates import matplotlib.ticker as ticker import datetime class DateConverter(units.ConversionInterface): @staticmethod def convert(value, unit, axis): ‘convert value to a scalar or array’ return dates.date2num(value) @staticmethod def axisinfo(unit, axis): ‘return major and minor tick locators and formatters’ if unit!=’date’: return None majloc = dates.AutoDateLocator() majfmt = dates.AutoDateFormatter(majloc) return AxisInfo(majloc=majloc, majfmt=majfmt, label=’date’) @staticmethod def default_units(x, axis): ‘return the default unit for x or None’ return ‘date’ # finally we register our object type with a converter units.registry[datetime.date] = DateConverter() class matplotlib.units.AxisInfo(majloc=None, minloc=None, majfmt=None, minfmt=None, label=None, default_limits=None) information to support default axis labeling and tick labeling, and default limits majloc and minloc: TickLocators for the major and minor ticks majfmt and minfmt: TickFormatters for the major and minor ticks label: the default axis label default_limits: the default min, max of the axis if no data is present If any of the above are None, the axis will simply use the default 829 Matplotlib, Release 1.0.1 class matplotlib.units.ConversionInterface The minimal interface for a converter to take custom instances (or sequences) and convert them to values mpl can use static axisinfo(unit, axis) return an units.AxisInfo instance for axis with the specified units static convert(obj, unit, axis) convert obj using unit for the specified axis. If obj is a sequence, return the converted sequence. The ouput must be a sequence of scalars that can be used by the numpy array layer static default_units(x, axis) return the default unit for x or None for the given axis static is_numlike(x) The matplotlib datalim, autoscaling, locators etc work with scalars which are the units converted to floats given the current unit. The converter may be passed these floats, or arrays of them, even when units are set. Derived conversion interfaces may opt to pass plain-ol unitless numbers through the conversion interface and this is a helper function for them. class matplotlib.units.Registry Bases: dict register types with conversion interface get_converter(x) get the converter interface instance for x, or None 830 Chapter 54. matplotlib units CHAPTER FIFTYFIVE MATPLOTLIB BACKENDS 55.1 matplotlib.backend_bases Abstract base classes define the primitives that renderers and graphics contexts must implement to serve as a matplotlib backend RendererBase An abstract base class to handle drawing/rendering operations. FigureCanvasBase The abstraction layer that separates the matplotlib.figure.Figure from the backend specific details like a user interface drawing area GraphicsContextBase An abstract base class that provides color, line styles, etc... Event The base class for all of the matplotlib event handling. Derived classes suh as KeyEvent and MouseEvent store the meta data like keys and buttons pressed, x and y locations in pixel and Axes coordinates. ShowBase The base class for the Show class of each interactive backend; the ‘show’ callable is then set to Show.__call__, inherited from ShowBase. class matplotlib.backend_bases.CloseEvent(name, canvas, guiEvent=None) Bases: matplotlib.backend_bases.Event An event triggered by a figure being closed In addition to the Event attributes, the following event attributes are defined: class matplotlib.backend_bases.Cursors class matplotlib.backend_bases.DrawEvent(name, canvas, renderer) Bases: matplotlib.backend_bases.Event An event triggered by a draw operation on the canvas In addition to the Event attributes, the following event attributes are defined: renderer the RendererBase instance for the draw event class matplotlib.backend_bases.Event(name, canvas, guiEvent=None) A matplotlib event. Attach additional attributes as defined in FigureCanvasBase.mpl_connect(). The following attributes are defined and shown with their default values name the event name 831 Matplotlib, Release 1.0.1 canvas the FigureCanvas instance generating the event guiEvent the GUI event that triggered the matplotlib event class matplotlib.backend_bases.FigureCanvasBase(figure) The canvas the figure renders into. Public attributes figure A matplotlib.figure.Figure instance blit(bbox=None) blit the canvas in bbox (default entire canvas) button_press_event(x, y, button, guiEvent=None) Backend derived classes should call this function on any mouse button press. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in MouseEvent. This method will be call all functions connected to the ‘button_press_event’ with a MouseEvent instance. button_release_event(x, y, button, guiEvent=None) Backend derived classes should call this function on any mouse button release. x the canvas coordinates where 0=left y the canvas coordinates where 0=bottom guiEvent the native UI event that generated the mpl event This method will be call all functions connected to the ‘button_release_event’ with a MouseEvent instance. close_event(guiEvent=None) This method will be called by all functions connected to the ‘close_event’ with a CloseEvent draw(*args, **kwargs) Render the Figure draw_cursor(event) Draw a cursor in the event.axes if inaxes is not None. Use native GUI drawing for efficiency if possible draw_event(renderer) This method will be call all functions connected to the ‘draw_event’ with a DrawEvent draw_idle(*args, **kwargs) draw() only if idle; defaults to draw but backends can overrride enter_notify_event(guiEvent=None) Backend derived classes should call this function when entering canvas guiEvent the native UI event that generated the mpl event flush_events() Flush the GUI events for the figure. Implemented only for backends with GUIs. get_default_filetype() 832 Chapter 55. matplotlib backends Matplotlib, Release 1.0.1 get_supported_filetypes() get_supported_filetypes_grouped() get_width_height() return the figure width and height in points or pixels (depending on the backend), truncated to integers grab_mouse(ax) Set the child axes which are currently grabbing the mouse events. Usually called by the widgets themselves. It is an error to call this if the mouse is already grabbed by another axes. idle_event(guiEvent=None) call when GUI is idle key_press_event(key, guiEvent=None) This method will be call all functions connected to the ‘key_press_event’ with a KeyEvent key_release_event(key, guiEvent=None) This method will be call all functions connected to the ‘key_release_event’ with a KeyEvent leave_notify_event(guiEvent=None) Backend derived classes should call this function when leaving canvas guiEvent the native UI event that generated the mpl event motion_notify_event(x, y, guiEvent=None) Backend derived classes should call this function on any motion-notify-event. x the canvas coordinates where 0=left y the canvas coordinates where 0=bottom guiEvent the native UI event that generated the mpl event This method will be call all functions connected to the ‘motion_notify_event’ with a MouseEvent instance. mpl_connect(s, func) Connect event with string s to func. The signature of func is: def func(event) where event is a matplotlib.backend_bases.Event. The following events are recognized •‘button_press_event’ •‘button_release_event’ •‘draw_event’ •‘key_press_event’ •‘key_release_event’ •‘motion_notify_event’ •‘pick_event’ 55.1. matplotlib.backend_bases 833 Matplotlib, Release 1.0.1 •‘resize_event’ •‘scroll_event’ •‘figure_enter_event’, •‘figure_leave_event’, •‘axes_enter_event’, •‘axes_leave_event’ •‘close_event’ For the location events (button and key press/release), if the mouse is over the axes, the variable event.inaxes will be set to the Axes the event occurs is over, and additionally, the variables event.xdata and event.ydata will be defined. This is the mouse location in data coords. See KeyEvent and MouseEvent for more info. Return value is a connection id that can be used with mpl_disconnect(). Example usage: def on_press(event): print ’you pressed’, event.button, event.xdata, event.ydata cid = canvas.mpl_connect(’button_press_event’, on_press) mpl_disconnect(cid) disconnect callback id cid Example usage: cid = canvas.mpl_connect(’button_press_event’, on_press) #...later canvas.mpl_disconnect(cid) new_timer(*args, **kwargs) Creates a new backend-specific subclass of backend_bases.Timer. This is useful for getting periodic events through the backend’s native event loop. Implemented only for backends with GUIs. optional arguments: interval Timer interval in milliseconds callbacks Sequence of (func, args, kwargs) where func(args, **kwargs) will be executed by the timer every *interval. onHilite(ev) Mouse event processor which highlights the artists under the cursor. Connect this to the ‘motion_notify_event’ using: canvas.mpl_connect(’motion_notify_event’,canvas.onHilite) 834 Chapter 55. matplotlib backends Matplotlib, Release 1.0.1 onRemove(ev) Mouse event processor which removes the top artist under the cursor. Connect this to the ‘mouse_press_event’ using: canvas.mpl_connect(’mouse_press_event’,canvas.onRemove) pick(mouseevent) pick_event(mouseevent, artist, **kwargs) This method will be called by artists who are picked and will fire off PickEvent callbacks registered listeners print_bmp(*args, **kwargs) print_emf(*args, **kwargs) print_eps(*args, **kwargs) print_figure(filename, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, format=None, **kwargs) Render the figure to hardcopy. Set the figure patch face and edge colors. This is useful because some of the GUIs have a gray figure face color background and you’ll probably want to override this on hardcopy. Arguments are: filename can also be a file object on image backends orientation only currently applies to PostScript printing. dpi the dots per inch to save the figure in; if None, use savefig.dpi facecolor the facecolor of the figure edgecolor the edgecolor of the figure orientation landscape’ | ‘portrait’ (not supported on all backends) format when set, forcibly set the file format to save to bbox_inches Bbox in inches. Only the given portion of the figure is saved. If ‘tight’, try to figure out the tight bbox of the figure. pad_inches Amount of padding around the figure when bbox_inches is ‘tight’. bbox_extra_artists A list of extra artists that will be considered when the tight bbox is calculated. print_pdf(*args, **kwargs) print_png(*args, **kwargs) print_ps(*args, **kwargs) print_raw(*args, **kwargs) print_rgb(*args, **kwargs) print_svg(*args, **kwargs) 55.1. matplotlib.backend_bases 835 Matplotlib, Release 1.0.1 print_svgz(*args, **kwargs) release_mouse(ax) Release the mouse grab held by the axes, ax. Usually called by the widgets. It is ok to call this even if you ax doesn’t have the mouse grab currently. resize(w, h) set the canvas size in pixels resize_event() This method will be call all functions connected to the ‘resize_event’ with a ResizeEvent scroll_event(x, y, step, guiEvent=None) Backend derived classes should call this function on any scroll wheel event. x,y are the canvas coords: 0,0 is lower, left. button and key are as defined in MouseEvent. This method will be call all functions connected to the ‘scroll_event’ with a MouseEvent instance. set_window_title(title) Set the title text of the window containing the figure. Note that this has no effect if there is no window (eg, a PS backend). start_event_loop(timeout) Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This is implemented only for backends with GUIs. start_event_loop_default(timeout=0) Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. This function provides default event loop functionality based on time.sleep that is meant to be used until event loop functions for each of the GUI backends can be written. As such, it throws a deprecated warning. Call signature: start_event_loop_default(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or timeout is reached. If timeout is <=0, never timeout. stop_event_loop() Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This is implemented only for backends with GUIs. stop_event_loop_default() Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. 836 Chapter 55. matplotlib backends Matplotlib, Release 1.0.1 Call signature: stop_event_loop_default(self) switch_backends(FigureCanvasClass) instantiate an instance of FigureCanvasClass This is used for backend switching, eg, to instantiate a FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is not done, so any changes to one of the instances (eg, setting figure size or line props), will be reflected in the other class matplotlib.backend_bases.FigureManagerBase(canvas, num) Helper class for pyplot mode, wraps everything up into a neat bundle Public attibutes: canvas A FigureCanvasBase instance num The figure nuamber destroy() full_screen_toggle() key_press(event) resize(w, h) For gui backends: resize window in pixels set_window_title(title) Set the title text of the window containing the figure. Note that this has no effect if there is no window (eg, a PS backend). show_popup(msg) Display message in a popup – GUI only class matplotlib.backend_bases.GraphicsContextBase An abstract base class that provides color, line styles, etc... copy_properties(gc) Copy properties from gc to self get_alpha() Return the alpha value used for blending - not supported on all backends get_antialiased() Return true if the object should try to do antialiased rendering get_capstyle() Return the capstyle as a string in (‘butt’, ‘round’, ‘projecting’) get_clip_path() Return the clip path in the form (path, transform), where path is a Path instance, and transform is an affine transform to apply to the path before clipping. get_clip_rectangle() Return the clip rectangle as a Bbox instance 55.1. matplotlib.backend_bases 837 Matplotlib, Release 1.0.1 get_dashes() Return the dash information as an offset dashlist tuple. The dash list is a even size list that gives the ink on, ink off in pixels. See p107 of to PostScript BLUEBOOK for more info. Default value is None get_hatch() Gets the current hatch style get_hatch_path(density=6.0) Returns a Path for the current hatch. get_joinstyle() Return the line join style as one of (‘miter’, ‘round’, ‘bevel’) get_linestyle(style) Return the linestyle: one of (‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’). get_linewidth() Return the line width in points as a scalar get_rgb() returns a tuple of three floats from 0-1. color can be a MATLAB format string, a html hex color string, or a rgb tuple get_snap() returns the snap setting which may be: •True: snap vertices to the nearest pixel center •False: leave vertices as-is •None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center get_url() returns a url if one is set, None otherwise restore() Restore the graphics context from the stack - needed only for backends that save graphics contexts on a stack set_alpha(alpha) Set the alpha value used for blending - not supported on all backends set_antialiased(b) True if object should be drawn with antialiased rendering set_capstyle(cs) Set the capstyle as a string in (‘butt’, ‘round’, ‘projecting’) set_clip_path(path) Set the clip path and transformation. Path should be a TransformedPath instance. 838 Chapter 55. matplotlib backends Matplotlib, Release 1.0.1 set_clip_rectangle(rectangle) Set the clip rectangle with sequence (left, bottom, width, height) set_dashes(dash_offset, dash_list) Set the dash style for the gc. dash_offset is the offset (usually 0). dash_list specifies the on-off sequence as points. (None, None) specifies a solid line set_foreground(fg, isRGB=False) Set the foreground color. fg can be a MATLAB format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. The GraphicsContextBase converts colors to rgb internally. If you know the color is rgb already, you can set isRGB=True to avoid the performace hit of the conversion set_graylevel(frac) Set the foreground color to be a gray level with frac set_hatch(hatch) Sets the hatch style for filling set_joinstyle(js) Set the join style to be one of (‘miter’, ‘round’, ‘bevel’) set_linestyle(style) Set the linestyle to be one of (‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’). set_linewidth(w) Set the linewidth in points set_snap(snap) Sets the snap setting which may be: •True: snap vertices to the nearest pixel center •False: leave vertices as-is •None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center set_url(url) Sets the url for links in compatible backends class matplotlib.backend_bases.IdleEvent(name, canvas, guiEvent=None) Bases: matplotlib.backend_bases.Event An event triggered by the GUI backend when it is idle – useful for passive animation class matplotlib.backend_bases.KeyEvent(name, canvas, key, x=0, y=0, guiEvent=None) Bases: matplotlib.backend_bases.LocationEvent A key event (key press, key release). Attach additional attributes as defined in FigureCanvasBase.mpl_connect(). In addition to the Event and LocationEvent attributes, the following attributes are defined: 55.1. matplotlib.backend_bases 839 Matplotlib, Release 1.0.1 key the key pressed: None, chr(range(255), shift, win, or control This interface may change slightly when better support for modifier keys is included. Example usage: def on_key(event): print ’you pressed’, event.key, event.xdata, event.ydata cid = fig.canvas.mpl_connect(’key_press_event’, on_key) class matplotlib.backend_bases.LocationEvent(name, canvas, x, y, guiEvent=None) Bases: matplotlib.backend_bases.Event An event that has a screen location The following additional attributes are defined and shown with their default values. In addition to the Event attributes, the following event attributes are defined: x x position - pixels from left of canvas y y position - pixels from bottom of canvas inaxes the Axes instance if mouse is over axes xdata x coord of mouse in data coords ydata y coord of mouse in data coords x, y in figure coords, 0,0 = bottom, left class matplotlib.backend_bases.MouseEvent(name, canvas, x, y, button=None, key=None, step=0, guiEvent=None) Bases: matplotlib.backend_bases.LocationEvent A mouse event (‘button_press_event’, ‘button_release_event’, ‘scroll_event’, ‘motion_notify_event’). In addition to the Event and LocationEvent attributes, the following attributes are defined: button button pressed None, 1, 2, 3, ‘up’, ‘down’ (up and down are used for scroll events) key the key pressed: None, chr(range(255), ‘shift’, ‘win’, or ‘control’ step number of scroll steps (positive for ‘up’, negative for ‘down’) Example usage: def on_press(event): print ’you pressed’, event.button, event.xdata, event.ydata cid = fig.canvas.mpl_connect(’button_press_event’, on_press) x, y in figure coords, 0,0 = bottom, left button pressed None, 1, 2, 3, ‘up’, ‘down’ class matplotlib.backend_bases.NavigationToolbar2(canvas) Base class for the navigation cursor, version 2 backends must implement a canvas that handles connections for ‘button_press_event’ and ‘button_release_event’. See FigureCanvasBase.mpl_connect() for more information 840 Chapter 55. matplotlib backends you’ll be notified with the event release() (optional) whenever a mouse button is released. zoom with right press(event) this will be called whenver a mouse button is pressed press_pan(event) the press mouse button in pan/zoom mode callback 55. you’ll be notified with the event dynamic_update() (optional) dynamically update the window while navigating set_message() (optional) display message set_history_buttons() (optional) you can change the history back / forward buttons to indicate disabled / enabled state.1 They must also define save_figure() save the current figure set_cursor() if you want the pointer icon to change _init_toolbar() create your toolbar widget draw_rubberband() (optional) draw the zoom to rect “rubberband” rectangle press() (optional) whenever a mouse button is pressed.Matplotlib. That’s it. update the locators draw_rubberband(event. x1. pan with left button. x0.1.backend_bases 841 . Release 1. y0. matplotlib. y1) draw a rectangle rubberband to indicate zoom limits dynamic_update() forward(*args) move forward in the view lim stack home(*args) restore the original view mouse_move(event) pan(*args) Activate the pan/zoom tool.0. we’ll do the rest! back(*args) move back up the view lim stack drag_pan(event) the drag callback in pan/zoom mode drag_zoom(event) the drag callback in zoom mode draw() redraw the canvases. 0. zip(xdata[ind].plot(rand(100). picker=5) # 5 points tolerance def on_pick(event): thisline = event. = ax. matplotlib backends . Release 1. ’o’.ind print ’on pick line:’. **kwargs) Bases: matplotlib.PickEvent(name. ydata = thisline.Matplotlib.1 press_zoom(event) the press mouse button in zoom to rect mode callback push_current() push the current view limits and position onto the stack release(event) this will be called whenever mouse button is released release_pan(event) the release mouse button callback in pan/zoom mode release_zoom(event) the release mouse button callback in zoom to rect mode save_figure(*args) save the current figure set_cursor(cursor) Set the current cursor to one of the Cursors enums values set_history_buttons() enable or disable back/forward button set_message(s) display a message on toolbar or in status bar update() reset the axes stack zoom(*args) activate zoom to rect mode class matplotlib. mouseevent. fired when the user picks a location on the canvas sufficiently close to an artist.get_data() ind = event. guiEvent=None. Attrs: all the Event attributes plus mouseevent the MouseEvent that generated the pick artist the Artist picked other extra class dependent attrs – eg a Line2D pick may define different extra attributes than a PatchCollection pick event Example usage: line. canvas.artist xdata.backend_bases.Event artist.backend_bases. ydata[ind]) 842 Chapter 55. a pick event. If origin is lower. transform) Draw a Gouraud-shaded triangle. including control points on curves. transform is an affine transform to apply to the points. rgbFace=None) Draws a marker at each of the vertices in path. gc a GraphicsContext containing clipping information x is the distance in pixels from the left hand side of the canvas. colors. x. transform is an affine transform to apply to the points.1. 55. To avoid that behavior. points is a Nx3x2 array of (x. transform) Draws a series of Gouraud triangles. colors is a 3x4 array of RGBA colors for each point of the triangle.1 cid = fig. triangles_array.backend_bases 843 . marker_trans. path. points. y the distance from the origin. trans. y.0. im) Draw the image instance into the current axes.mpl_connect(’pick_event’.Image instance draw_markers(gc.Matplotlib.canvas. marker_path. Release 1._image. matplotlib. y) points for the trianglex.backend_bases. on_pick) class matplotlib. colors is a Nx3x4 array of RGBA colors for each point of the triangles. those vertices should be removed before calling this function. y is the distance from top. colors_array. That is. This includes all vertices.RendererBase An abstract base class to handle drawing/rendering operations. points is a 3x2 array of (x. if origin is upper. draw_image(gc. y is the distance from bottom im the matplotlib. The following methods must be implemented in the backend: •draw_path() •draw_image() •draw_text() •get_text_width_height_descent() The following methods should be implemented in the backend for optimization reasons: •draw_markers() •draw_path_collection() •draw_quad_mesh() close_group(s) Close a grouping element with label s Is only currently used by backend_svg draw_gouraud_triangle(gc. y) points for the triangle. draw_gouraud_triangles(gc. y. transform. linestyles and antialiaseds. coordinates. paths. linewidths. meshHeight.1 gc the GraphicsContextBase instance marker_trans is an affine transform applied to the marker. Release 1. edgecolors. draw_path(gc. offsetTrans. offsetTrans. s. angle.text. antialiaseds.FontProperties instance angle the rotation angle in degrees backend implementers note When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly). urls) Draws a collection of paths selecting drawing properties from the lists facecolors. antialiased. offsets. It is highly recommended to use those generators. showedges) This provides a fallback implementation of draw_quad_mesh() that generates paths and then calls draw_path_collection(). path. offsets is a list of offsets to apply to each of the paths. ismath=False) Draw the text instance gc the GraphicsContextBase instance x the x location of the text in display coords y the y location of the text in display coords s a matplotlib. draw_path_collection(gc. linestyles. trans is an affine transform applied to the path. styles etc. y. facecolors.0. colors. prop.py: if 0: bbox_artist(self. and then reference that path multiple times with the different offsets. linewidths. master_transform. so that changes to the behavior of draw_path_collection() can be made globally. s. draw_quad_mesh(gc.Text instance prop a matplotlib. offsets. ismath=’TeX!’) draw_text(gc. The offsets in offsets are first transformed by offsetTrans before being applied. prop. all_transforms. and then the actual bounding box will be blotted along with your text. x. it helps to change the line in text. Some backends may want to override this in order to render each set of path data only once.Matplotlib. meshWidth. facecolors. 844 Chapter 55. rgbFace=None) Draws a Path instance using the given affine transform. This provides a fallback implementation of draw_markers that makes multiple calls to draw_path(). matplotlib backends . master_transform. The generator methods _iter_collection_raw_paths() and _iter_collection() are provided to help with (and standardize) the implementation across backends.font_manager. angle. This provides a fallback implementation of draw_path_collection() that makes multiple calls to draw_path(). Some backends may want to override this method in order to draw the marker only once and reuse it multiple times. x. renderer) to if 1. draw_tex(gc. edgecolors. 1.Matplotlib. points_to_pixels(points) Convert points to display units points a float or a numpy array of float return points converted to pixels You need to override this function (unless your backend doesn’t have a dpi.texmanager. If gid is given. option_image_nocomposite() override this method for renderers that do not necessarily want to rescale and composite raster images. Allows a backend to have images at a different resolution to other artists.backend_bases 845 . and the offset from the bottom to the baseline (descent). in display coords of the string s with FontProperties prop new_gc() Return an instance of a GraphicsContextBase open_group(s.0. (like SVG) option_scale_image() override this method for renderers that support arbitrary scaling of image (most of the vector backend).TexManager instance get_text_width_height_descent(s.text) and images (matplotlib. start_rasterizing() Used in MixedModeRenderer. Some imaging systems assume some value for pixels per inch: points to pixels = points * pixels_per_inch/72.0 start_filter() Used in AggRenderer. prop. Is only currently used by backend_svg. Switch to a temporary renderer for image filtering effects. Switch back to the original renderer. use gid as the id of the group. stop_filter(filter_func) Used in AggRenderer. get_texmanager() return the matplotlib. gid=None) Open a grouping element with label s. Switch to the raster renderer.0 * dpi/72. matplotlib. Release 1. postscript or svg).image) only get_canvas_width_height() return the canvas width and height in display coords get_image_magnification() Get the factor by which to magnify images passed to draw_image(). eg. ismath) get the width and height.1 flipy() Return true if y small numbers are top for renderer Is used for drawing text (matplotlib. 55. The contents of the temporary renderer is processed with the filter_func and is drawn on the original renderer as an image. strip_math(s) class matplotlib. Defaults to False. useful for things animations. args) tuples that will be called upon timer events. 846 Chapter 55. matplotlib backends .0.backend_bases. canvas) Bases: matplotlib. Backends need to implement a few specific methods in order to use their own timing mechanisms so that the timer events are integrated into their event loops. if supported by the timer object. Mandatory functions that must be implemented: * _timer_start: Contains backend-specific code for starting the timer * _timer_stop: Contains backend-specific code for stopping the timer Optional overrides: * _timer_set_single_shot: Code for setting the timer to single shot operating mode.backend_bases. which will handle the task of running all callbacks that have been set.1 stop_rasterizing() Used in MixedModeRenderer.ResizeEvent(name. Switch back to the vector renderer and draw the contents of the raster renderer as an image on the vector renderer. if there is a method for doing so on the timer object.Event An event triggered by a canvas resize In addition to the Event attributes. •_timer_set_interval: Code for setting the interval on the timer. Attributes: * interval: The time between timer events in milliseconds. callbacks=None) Bases: object A base class for providing timer events. If not. This list can be manipulated directly.backend_bases. •callbacks: Stores list of (func. the Timer class itself will store the flag and the _on_timer method should be overridden to support such behavior. the following event attributes are defined: width width of the canvas in pixels height height of the canvas in pixels class matplotlib. •single_shot: Boolean flag indicating whether this timer should operate as single shot (run once and then stop). or the functions add_callback and remove_callback can be used.backend_bases. •_on_timer: This is the internal function that any timer object should call. Subclass must override mainloop() method.Matplotlib. Default is 1000 ms.ShowBase Bases: object Simple base class to generate a show() callable in backends.TimerBase(interval=None. mainloop() class matplotlib. Release 1. creates the renderers.register_backend(format. all drawing should be done inside of here when a widget is shown onscreen.2 matplotlib.backends. Release 1. **kwargs) Register func to be called by timer when the event fires.backends. **kwargs) Remove func from list of callbacks.backends. Any additional arguments provided will be passed to func.backend_qt4agg. 55.2. matplotlib.drawable. *args. In Qt.backend_qt4.FigureCanvasQTAgg(figure) Bases: matplotlib.FigureCanvasQT. interval is optional and will be used to reset the timer interval first if provided. which is not compatible with cron jobs. Public attribute figure .backend_bases. *args.FigureCanvasAgg The canvas the figure renders into.0..backend_gtkagg TODO We’ll add this later. importing the gtk backends requires an active X-session. Calls the draw and print fig methods. single_shot start(interval=None) Start the timer object.backend_gtkagg 847 .backends.backend_qt4agg Render to qt from agg class matplotlib.A Figure instance blit(bbox=None) Blit the region in bbox draw() Draw the figure when xwindows is ready for the update drawRectangle(rect) paintEvent(e) Draw to the Agg backend and then copy the image to the qt.backends.. 55. stop() Stop the timer. interval remove_callback(func.Matplotlib. etc.backends. args and kwargs are optional and used to distinguish between copies of the same function registered to be called with different arguments. backend_class) 55. matplotlib.backend_agg.1 add_callback(func. matplotlib.3 matplotlib. backend_qt4agg.NavigationToolbar2WxAgg(canvas) Bases: matplotlib.backends.new_figure_manager(num. the entire buffer is transferred.backends. fig) matplotlib.backends. **kwargs) Create a new figure manager instance 848 Chapter 55. matplotlib. draw(drawDC=None) Render the figure using agg.backends. **kwargs) Create a new figure manager instance 55.backends.but we give a hint as to our preferred minimum size. print_figure(filename.backend_wxagg.FigureCanvasWxAgg(parent. •Initialise the FigureCanvasBase and wxPanel parents. id.backends. and (usually) lives inside a frame instantiated by a FigureManagerWx. Release 1.backends. *args. figure) Bases: matplotlib.backend_qt4.1 print_figure(*args.NavigationToolbar2QT coordinates: should we show the coordinates on the right? matplotlib. In the wxPython backend.backend_wxagg.backends. *args.backends.backend_wx. it is derived from wxPanel.backend_wxagg class matplotlib.backends.backend_agg.FigureCanvasWx The FigureCanvas contains the figure and does event handling.backend_wxagg. fig) Bases: matplotlib. num) Bases: matplotlib.NavigationToolbar2QTAgg(canvas.backends.FigureCanvasAgg.FigureFrameWx get_canvas(fig) class matplotlib.FigureFrameWxAgg(num.FigureManagerQT class matplotlib.backends. coordinates=True) Bases: matplotlib. matplotlib backends .new_figure_manager(num.backend_qt4agg. If bbox is None. The parent window probably implements a wxSizer to control the displayed control size .0. **kwargs) class matplotlib.Matplotlib.backend_qt4agg.backend_wx.backends. **kwargs) class matplotlib.FigureManagerQTAgg(canvas.backend_qt4.4 matplotlib. *args. parent. Initialise a FigureWx instance. •Set event handlers for: EVT_SIZE (Resize event) EVT_PAINT (Paint event) blit(bbox=None) Transfer the region of the agg buffer defined by bbox to the display.backend_wx.NavigationToolbar2Wx get_canvas(frame.backend_wxagg.backends. A Figure instance class matplotlib. etc.backend_pdf.backends. 55. matplotlib.Name(name) Bases: object PDF name object.FigureCanvasBase The canvas the figure renders into.backends.. lw) Return name of a marker XObject representing the given path.5 matplotlib.0.backends. markerObject(path.PdfFile(filename) Bases: object PDF file object.FT2Font() FT2Font class matplotlib. trans. writeInfoDict() Write out the info dictionary. Calls the draw and print fig methods.FigureCanvasPdf(figure) Bases: matplotlib. Public attribute figure . Release 1.backend_pdf.backend_bases. class matplotlib.backend_pdf A PDF matplotlib backend (not yet complete) Author: Jouni K Seppänen <jks@iki. creates the renderers. fontName(fontprop) Select a font based on fontprop and return a name suitable for Op. reserveObject(name=’‘) Reserve an ID for an indirect object. fillp.1 55. characters) Embed the TTF font from the named file into the document. If fontprop is a string. checking it for good form writeTrailer() Write out the PDF trailer. it will be interpreted as the filename (or dvi name) of the font.fi> matplotlib. class matplotlib.backend_pdf 849 .Operator(op) Bases: object PDF operator object. The name is used for debugging in case we forget to print out the object with writeObject. imageObject(image) Return name of an image XObject representing the given image. alphaState(alpha) Return name of an ExtGState that sets alpha to the given value embedTTF(filename.selectfont.5.Matplotlib.backends..backends.backend_pdf.backend_pdf.backends.backends.backend_pdf. the figure instance is looked up by number.backend_pdf. Any other keyword arguments are passed to Figure. and finally call end(). If figure is a number.backends. remember to close the object: pp. This has no pdfRepr method. call begin(). and if figure is None. Release 1. file.) Create a new PdfPages object that will be written to the file named filename.backend_pdf. extra: a dictionary of extra key-value pairs to include in the stream header 850 Chapter 55. infodict() Return a modifiable information dictionary object (see PDF reference section 10. len: an unused Reference object for the length of the stream. making the underlying file a complete PDF file.savefig.savefig(fig) # Once you are done. class matplotlib.PdfPages(filename) Bases: object A multi-page PDF file.2.backends.reserveObject() to create References. or None (to use a memory buffer).Reference(id) Bases: object PDF reference object. then either: fig. then output the contents of the stream by calling write(). in order to avoid confusion when using savefig and forgetting the format argument. id: object id of stream. matplotlib backends .backends. file: a PdfFile. Instead. close() Finalize this object. extra=None) Bases: object PDF stream object. class matplotlib. create a figure fig. class matplotlib.Matplotlib. the active figure is saved.Stream(id. Use PdfFile. savefig(figure=None.1 writeXref() Write out the xref table.savefig(pp. Use like this: # Initialize: pp = PdfPages(’foo. **kwargs) Save the Figure instance figure to this file as a new page.backend_pdf. len. The file is opened at once and any older file with the same name is overwritten.pdf’) # As many times as you like.close() (In reality PdfPages is a thin wrapper around PdfFile.0.1 ‘Document Information Dictionary’). format=’pdf’) # note the format argument! # or: pp. text: fontname = font. The current implementation only reads the first page and does not even attempt to verify the postamble. vf ) Bases: object Object that holds a font’s texname and size. class matplotlib. dpi) Bases: object A dvi (“device-independent”) file. Release 1.0. Initialize the object.py) that are not used for comparison.y. write(data) Write some data on the stream.dviread.backends.height.Dvi(filename. matplotlib..boxes: . if possible.fill(strings.6. as produced by TeX.glyph.font.dviread An experimental module for reading dvi files output by TeX.1 end() Finalize stream.dviread 851 .Matplotlib..new_figure_manager(num.width in page.y. page..backend_pdf.backends. 72) # iterate over pages (but only one page is supported for now): for page in dvi: w. but it is currently used by the pdf backend for processing usetex text. Several limitations make this not (currently) useful as a general-purpose dvi preprocessor.. Interface: dvi = Dvi(filename. d = page. *args.backend_pdf. actually reading the file happens when iterating through the pages of the file. for x.6 matplotlib. **kwargs) Create a new figure manager instance matplotlib. texname.backend_pdf. supports comparison. close() Close the underlying file if it is open.height. with whitespace in between. matplotlib.pdfRepr(obj) Map Python objects to PDF syntax. linelen=75) Make one string from sequence of strings. class matplotlib.width in page.dviread.backends. This takes the filename as input and opens the file.DviFont(scale. There are also internal attributes (for use by dviread. matplotlib. and knows the widths of glyphs in the same units as the AFM file. page. 55. 55. The whitespace is chosen to form lines of at most linelen characters.texname pointsize = font.descent for x.width. tfm.size . h. map formatted file. TeX’s native fonts are not Type-1 but Metafont. For these reasons a mapping is needed from internal font names to font file names.Matplotlib.16700000000000001} >>> entry. 852 Chapter 55. typically 1/1000ths of the point size. The format this class understands is a very limited subset of PostScript.enc’ >>> entry.texname ’ptmbo8r’ >>> entry. Usage (subject to change): for name in Encoding(filename): whatever(name) encoding class matplotlib. the names have to fit in eight characters.1 The size is in Adobe points (converted from TeX points).filename For historical reasons. which is nontrivial to convert to PostScript except as a bitmap.map’)) >>> entry = map[’ptmbo8r’] >>> entry. and dviread. While high-quality conversions to Type-1 format exist and are shipped with modern TeX distributions.map style file.Encoding(filename) Bases: object Parses a *. converted from the slightly smaller TeX points.) Also.PsfontsMap(filename) Bases: object A psfonts.effects {’slant’: 0.PsfontsMap can be used to find the external name of the font. size Size of the font in Adobe points.encoding ’/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r. mapping TeX fonts to PS fonts. Release 1. widths Widths of glyphs in glyph-space units. This is usually very different from any external font names.dviread.psname ’Times-Bold’ >>> entry.enc file referenced from a psfonts. texname Name of the font as used internally by TeX and friends. we need to know which Type-1 fonts are the counterparts of which native fonts. (For one thing. Usage: >>> map = PsfontsMap(find_tex_file(’pdftex. size texname widths class matplotlib.dviread. matplotlib backends . TeX knows many Type-1 fonts by different names than the outside world.0. dviread. checksum Used for verifying against the dvi file. it is used as the value for the --format option.text.0.dviread. so what do we do? (TODO) See Also: 55. class matplotlib.map might avoid embedding the 35 PostScript fonts (i.map.Matplotlib.Dvi A virtual font (*. checksum depth design_size height width class matplotlib. Usage: vf = Vf(filename) glyph = vf[code] glyph.g.map by pdfTeX. depth Depth of each character.width matplotlib.Vf(filename) Bases: matplotlib. psfonts. pdftex. have no filename for them. pdftex. This is a dict because indexing may not start from 0.dviread. matplotlib. This implementation covers only the bare minimum needed by the Dvi class.map by dvipdfm. height Height of each character. psfonts. and dvipdfm. But the user may have configured these files differently. I hear MikTeX (a popular distribution on Windows) doesn’t use kpathsea. needs to be scaled by the factor specified in the dvi file. design_size Design size of the font (in what units?) width Width of each character.map.dviread 853 .find_tex_file(filename. Apparently most existing TeX distributions on Unix-like systems use kpathsea.Tfm(filename) Bases: object A TeX Font Metric file. dvipdfm.e.1 A texmf tree typically includes mapping files called e.dviread. glyph.6.map.map is used by dvips. while the pdf-related files perhaps only avoid the “Base 14” pdf fonts. glyph. as in the Times-Bold example above). format=None) Call kpsewhich to find a file in the texmf tree. Release 1. If format is not None.vf file) containing subroutines for dvi files.boxes.. psfonts. 7 matplotlib.1. Usage: >>> >>> >>> >>> font = Type1Font(filename) clear_part. ISBN 0-20157044-0.0.0 condense). similarly to pdfTeX and friends. matplotlib backends . for use by backends. Returns a new Type1Font object. prop A dictionary of font properties. the encrypted part. Release 1. 854 Chapter 55.type1font This module contains a class representing a Type 1 font.transform({’slant’: 0.Matplotlib. effects should be a dict where effects[’slant’] is the tangent of the angle that the font is to be slanted to the right (so negative values slant to the left) and effects[’extend’] is the multiplier by which the font is to be extended (so values less than 1. Adobe Systems Incorporated. encrypted_part. input can be either the file name of a pfb file or a 3-tuple of already-decoded Type-1 font parts.transform({’extend’: 1.1 Kpathsea documentation The library that kpsewhich is part of.parts slanted_font = font.type1font. Supporting Downloadable PostScript Language Fonts. There is no support yet for subsetting. third printing. finale = font. parts prop transform(effects) Transform the font by slanting or extending.167}) extended_font = font. Initialize a Type-1 font. and the finale of zeros.Type1Font(input) Bases: object A class representing a Type-1 font. It also supports SlantFont and ExtendFont transformations. parts A 3-tuple of the cleartext part. This version reads pfa and pfb files and splits them for embedding in pdf files.2}) Sources: • Adobe Technical Note #5040. class matplotlib. 1993. 55. v1. • Adobe Type 1 Font Format. Part V Glossary 855 . . and is often packages as ‘python-gtk2’ pyqt pyqt provides python wrappers for the Qt widgets library and is requied by the matplotlib QtAgg and Qt4Agg backends. numpy provides fast operations for homogeneous data sets and common mathematical operations like correlations. and OpenType fonts. many linux distributions package this as ‘python-qt3’ or ‘python-qt4’. pytz pytz provides the Olson tz database in Python. it allows accurate and cross platform timezone calculations and solves the issue of ambiguous times at the end of daylight savings Qt Qt is a cross-platform application framework for desktop and embedded development. GDK The Gimp Drawing Kit for GTK+ GTK The GIMP Toolkit (GTK) graphical user interface library JPG The Joint Photographic Experts Group (JPEG) compression method and file format for photographic images numpy numpy is the standard numerical array library for python. application development. and MacOS X freetype freetype is a font rasterization library used by matplotlib which supports TrueType. Widely used on linux and windows. Widely used on linux. python python is an object oriented interpreted language widely used for scripting. standard deviation. Qt4 Qt4 is the most recent version of Qt cross-platform application framework for desktop and embedded development. fourier transforms. a raster graphics format that employs lossless data compression which is more suitable for line art than the lossy jpg format. and convolutions.0. 857 . capable of rendering high-quality images Cairo The Cairo graphics engine dateutil The dateutil library provides extensions to the standard datetime module EPS Encapsulated Postscript (EPS) FLTK FLTK (pronounced “fulltick”) is a cross-platform C++ GUI toolkit for UNIX/Linux (X11).Matplotlib. Unlike the gif format. web application servers. Microsoft Windows. Type 1.1 AGG The Anti-Grain Geometry (Agg) rendering engine. PS Postscript (PS) is a vector graphics ASCII text language widely used in printers and publishing. PDF Adobe’s Portable Document Format (PDF) PNG Portable Network Graphics (PNG). scientific computing and more. Postscript was developerd by adobe systems and is starting to show its age: for example is does not have an alpha channel. PDF was designed in part as a next-generation document format to replace postscript pyfltk pyfltk provides python wrappers for the FLTK widgets library for use with FLTKAgg pygtk pygtk provides python wrappers for the GTK widgets library for use with the GTK or GTKAgg backend. the successor to Numeric and numarray. Release 1. png is not encumbered by requirements for a patent license. Tk Tk is a graphical user interface for Tcl and many other dynamic languages. Vector graphics are generally most practical for typesetting and graphic design applications. lines. TIFF Tagged Image File Format (TIFF) is a file format for storing images. including photographs and line art.1 raster graphics Raster graphics. Vector graphics are scalable. or bitmaps. Linux and more. An XML based vector graphics format supported by many web browsers. it is often packaged by linux distributions as ‘python-wxgtk’ wxWidgets WX is cross-platform GUI and tools library for GTK. vector graphics vector graphics use geometrical primitives based upon mathematical equations to represent images in computer graphics. Primitives can include points. represent an image as an array of pixels which is resolution dependent. curves. which means that they can be resized without suffering from issues related to inherent resolution like are seen in raster graphics.Matplotlib. Widely used on linux. SVG The Scalable Vector Graphics format (SVG). Release 1. and MacOS. Mac OS X.0. It uses native widgets for each operating system. wxpython wxpython provides python wrappers for the wxWidgets library for use with the WX and WXAgg backends. native applications that run unchanged across Windows. so applications will have the look-and-feel that users on that operating system expect. Raster graphics are generally most practical for photo-realistic images. OS-X and windows. MS Windows. 858 . It can produce rich. but do not scale easily without loss of quality. and shapes or polygons. 275 matplotlib.units.backends.polar.backend_qt4agg. 593 matplotlib.mlab. 847 matplotlib. 611 matplotlib. 251 matplotlib.backends. 637 matplotlib. 272 matplotlib.nxutils.mathtext.text. 339 matplotlib.fontconfig_pattern.afm. 848 matplotlib.axes. 616 matplotlib.font_manager. 274 matplotlib.type1font. 559 matplotlib.colorbar. 545 matplotlib. 623 matplotlib.backends.gridspec.cbook.cm. 347 matplotlib.patches. 829 859 . 849 matplotlib.pyplot.path.scale.projections. 319 matplotlib. 831 matplotlib. 383 matplotlib. 817 matplotlib. 327 matplotlib.backend_bases. 395 matplotlib.backend_pdf. 557 matplotlib. 821 matplotlib. 815 matplotlib.axis. 854 matplotlib.ticker. 661 matplotlib.PYTHON MODULE INDEX m matplotlib.legend. 851 matplotlib.spines. 336 matplotlib. 667 matplotlib. 585 matplotlib.lines. 619 matplotlib. 535 matplotlib.collections.backend_wxagg. 573 matplotlib.projections.colors.transforms.figure.dviread. 577 matplotlib.dates. 323 matplotlib.artist. 1 860 Python Module Index .Matplotlib. Release 1.0. text).Axes method).cbook. 327 add_callback() (matplotlib.axes.pyplot). 615 AGG.transforms).cm.BracketAB (class in matplotlib. 262 Affine2DBase (class in matplotlib. 550 allow_rasterization() (in module matplotlib. 847 add_checker() (matplotlib.ArtistInspector method).ArtistInspector method).Axes method). 550 alphaState() (matplotlib.axes.BarAB (class in matplotlib. 401 ArrowStyle (class in matplotlib. 550 allequal() (in module matplotlib.artist. 353 ArrowStyle. 543 Arc (class in matplotlib. 557 add_collection() (matplotlib.XTick method).BracketB (class in matplotlib. 349 arrow() (in module matplotlib.patches).Axes method). 849 amap() (in module matplotlib.colorbar.mlab.axis. 593 add_axobserver() (matplotlib. 641 anchored() (matplotlib. 397 Annotation (class in matplotlib. 253 annotate() (in module matplotlib.BracketA (class in matplotlib.pyplot).axis. 857 aliased_name() (matplotlib.axis. 397 add_subplot() (matplotlib.Figure method).transforms. 396 add_line() (matplotlib.ColorbarBase method).axes.Tick method).CurveA (class in matplotlib. 261 AFM (class in matplotlib. 595 add_callback() (matplotlib. 397 Affine2D (class in matplotlib. 333 aliased_name_rest() (matplotlib. 353 ArrowStyle.Figure method).Colorbar method).cbook). 261 AffineBase (class in matplotlib. 351 ArrowStyle.Axes method). 541 apply_tickdir() (matplotlib. 383 append() (matplotlib.mathtext).TimerBase method).mathtext.patches).axes.RingBuffer method). 353 861 .patches).axes. 623 accent() (matplotlib.artist.ScalarMappable method).backend_bases. 347 arc() (matplotlib. 353 ArrowStyle.Axes method).patches).backends.afm).figure. 574 add_patch() (matplotlib. 639 add_artist() (matplotlib.figure.pyplot).Path class method).patches). 395 add() (matplotlib.colorbar.axes.artist.YTick method).cbook). 323 afmFontProperty() (in module matplotlib.patches). 334 allpairs() (in module matplotlib. 351 ArrowStyle.artist). 595 add_table() (matplotlib. 667 acorr() (matplotlib. 350 ArrowStyle. 668 annotate() (matplotlib.mlab).backend_pdf.cbook).figure.Parser method). 396 add_lines() (matplotlib.patches).Curve (class in matplotlib.BboxBase method).path. 539 apply_tickdir() (matplotlib.Axes method). 573 add_lines() (matplotlib. 399 apply_tickdir() (matplotlib.Artist method).transforms). 671 arrow() (matplotlib.Axes method). 662 Arrow (class in matplotlib. 333 align_iterators() (in module matplotlib.Figure method).cbook).axes.Axes method).font_manager). 396 add_axes() (matplotlib.transforms).INDEX A Accent (class in matplotlib.axes. 547 apply_aspect() (matplotlib. 550 alltrue() (in module matplotlib. 631 acorr() (in module matplotlib.PdfFile method).patches).FIFOBuffer method).patches).axes.Axes method). axes.pyplot).FIFOBuffer method).Axes method).colors. 354 ArrowStyle.collections).patches).CurveAB (class in matplotlib.Fancy (class in matplotlib.CurveFilledAB (class in matplotlib.LogNorm method).colors.ticker.units).Axes method).cm. 826 base_repr() (in module matplotlib. 403 Axis (class in matplotlib.NavigationToolbar2 method). 408 barbs() (in module matplotlib. 355 Artist (class in matplotlib.pyplot). 589 autoscale() (matplotlib. 674 Axes (class in matplotlib.DraggableLegend method).patches).CurveFilledA (class in matplotlib.axes. 673 autoscale() (matplotlib. 841 back() (matplotlib.pyplot).artist).Locator method).patches).cm. 382 BboxBase (class in matplotlib. 824 base() (matplotlib.patches). 588 autofmt_xdate() (matplotlib.ScalarMappable method).Axes method).pyplot).axes.Axes method). 588 AutoDateLocator (class in matplotlib.transforms).LogFormatter method). 641 Bbox (class in matplotlib. 557 862 autoscale_None() (matplotlib. 681 bar() (matplotlib.ticker.mlab. 401 autoscale() (matplotlib.axes.patches).units.RRuleLocator method).axes).pyplot).pyplot). 353 ArrowStyle. 680 axvspan() (matplotlib.axis. 679 axvline() (matplotlib. 256 bbox_artist() (in module matplotlib.pyplot). 269 Index .Stack method).ScalarMappable method).Normalize method). 677 axis() (matplotlib.Parser method).pyplot).Axes method).YearLocator method).Normalize method).ticker. 395 axes() (in module matplotlib.Figure method).Axes method). 327 artist_picker() (matplotlib.Wedge (class in matplotlib. Release 1.backend_bases.Axes method).artist).patches). 674 axhline() (matplotlib.mlab). 582 autoscale() (matplotlib.axes. 588 autoscale() (matplotlib.LogNorm method). 639 AsteriskPolygonCollection (class in matplotlib. 336 ArtistInspector (class in matplotlib.axes. 590 autoscale() (matplotlib. 557 autoscale() (matplotlib.Axis method).mathtext).pyplot). 405 axvspan() (in module matplotlib. 829 axisinfo() (matplotlib.axes.Axes method). 686 barh() (matplotlib. 253 BboxTransform (class in matplotlib. 535 axis() (in module matplotlib.ticker). 623 AutoLocator (class in matplotlib.CurveFilledB (class in matplotlib.legend.axes.dates. 269 BboxTransformTo (class in matplotlib. 623 bar() (in module matplotlib. 410 barh() (in module matplotlib. 623 autumn() (in module matplotlib. 333 asarrays() (matplotlib.pyplot). 826 autoscale() (in module matplotlib.colors.ConversionInterface static method).1 ArrowStyle.dates.dates.axes.mathtext).dates).Axes method).pyplot).dates). 269 BboxTransformFrom (class in matplotlib. 631 AutoDateFormatter (class in matplotlib. 825 autoscale_None() (matplotlib.AutoDateLocator method). 402 axhspan() (in module matplotlib. 581 autoscale_None() (matplotlib.0. 597 autogen_docstring() (in module matplotlib. 582 autoscale_view() (matplotlib.figure.mathtext).Axes method). 402 AutoWidthChar (class in matplotlib.CurveB (class in matplotlib. 548 BakomaFonts (class in matplotlib.colors. 535 AxisInfo (class in matplotlib.transforms). 354 ArrowStyle. 354 ArrowStyle.Matplotlib. 581 autoscale() (matplotlib. 674 axhline() (in module matplotlib.LogLocator method). 559 auto_sized_delimiter() (matplotlib.cbook.patches). 407 B back() (matplotlib.patches). 683 barbs() (matplotlib.Simple (class in matplotlib. 354 ArrowStyle.axis). 354 ArrowStyle.transforms).transforms). 676 axhspan() (matplotlib.axes.pyplot). 673 AutoHeightChar (class in matplotlib. 405 axis_date() (matplotlib. 830 axvline() (in module matplotlib.patches).transforms).mathtext. 353 ArrowStyle. 413 base() (matplotlib. spines. 357 method). 535 357 cla() (matplotlib. 277 plotlib.pyplot). 631 Cairo.ticker. method).Sawtooth (class in matplotlib. 692 BoxStyle. 832 change_geometry() (matplotlib.Stack method).pyplot).pyplot). 548 method). 597 button_release_event() (mat.cbook.projections.mathtext).axes.MaxNLocator C method). can_zoom() (matplotlib.pyplot).Axis method). button_press_event() (mat547 plotlib.cbook.PolarAxes BlendedGenericTransform (class in matmethod).Sorter method).RArrow (class in matplotlib.backend_bases.cbook. 548 Index 863 .transforms). 641 CallbackRegistry (class in matplotlib.BoundMethodProxy (class in matplotlib.transforms).Axes method). 560 cleanup_path() (in module matplotlib.LArrow (class in matplotlib.Sorter method). 545 blended_transform_factory() (in module mat.dviread.Figure method).BboxBase attribute).SubplotBase blit() (matplotlib.Parser method).axis. boxplot() (matplotlib. 548 clear() (matplotlib.axes.cbook.patches). 623 checksum (matplotlib.collections).pyplot).Round4 (class in matplotlib. 818 BoxStyle.Axes method).mathtext.axes. 690 clamp() (matplotlib.patches). Release 1. 357 cla() (in module matplotlib. 548 clf() (in module matplotlib.polar. 267 plotlib.transforms.transforms.ViewVCCachedServer binary_repr() (in module matplotlib. blit() (matplotlib.Round (class in matplotlib. 853 box() (in module matplotlib.ScalarMappable 253 method). 358 BoxStyle.ScalarMappable method). 641 blit() (matplotlib. 418 266 can_zoom() (matplotlib.cbook.Spine class BoxStyle.mathtext.spines. 689 char_over_chars() (matplotlib.cbook).Roundtooth (class in matplotlib.pyplot). 557 Box (class in matplotlib.backends.1 bin_boundaries() (matplotlib.axes.Square (class in matplotlib.Grouper method). 355 CirclePolygon (class in matplotlib. 357 clabel() (in module matplotlib.collections).FigureCanvasBase center_matrix() (in module matplotlib.clear() (matplotlib.patches).patches). 547 plotlib.Stack method). 632 plotlib.mlab.mathtext).Axes method).colors).backend_bases.axes.patches).cm. 358 boxplot() (in module matplotlib. 848 Char (class in matplotlib.backend_wxagg.cm.mathtext. 624 bone() (in module matplotlib.Affine2D method).0.FigureCanvasQTAgg method). 632 bounds (matplotlib.cbook). 418 BoxStyle.FigureCanvasWxAgg 557 method). 689 Circle (class in matplotlib. 357 clabel() (matplotlib.mlab).figure.backend_bases.patches). broken_barh() (matplotlib.Parser method).mlab). cla() (matplotlib. 420 Bunch (class in matplotlib. 847 changed() (matplotlib. 818 BoxStyle. 832 clear() (matplotlib. 641 method). check_update() (matplotlib. 692 BoxStyle.Tfm attribute).patches). 545 clear() (matplotlib. 546 BlendedAffine2D (class in matplotlib.pyplot). 265 center() (matplotlib. 665 bubble() (matplotlib.Spine method).clean() (matplotlib. 417 633 BrokenBarHCollection (class in mat.FigureCanvasBase clear() (matplotlib. 549 binom() (matplotlib.axes.backends.Ship static method). 532 method).cbook.Axes method).MemoryMonitor method). 832 263 byAttribute() (matplotlib. 827 cache_file() (matplotlib.CallbackRegistry. 857 bivariate_normal() (in module matplotlib.backend_qt4agg.Matplotlib.Axes method).patches). 578 method).cbook. 694 byItem() (matplotlib.axes. 418 broken_barh() (in module matplotlib. 689 CircleCollection (class in matplotlib.cbook).mlab).Parser BoundaryNorm (class in matplotlib.Axes method). 641 method).FigureCanvasBase clear() (matplotlib.PCA method). 357 cla() (matplotlib.patches).transforms).patches). 355 circular_spine() (matplotlib.mathtext.path). 416 561 BoxStyle (class in matplotlib. Arc3 (class in matplotlib.patches. 694 method).text. 597 contains() (matplotlib.pyplot).Angle contiguous_regions() (in module matplotlib.Bar close() (in module matplotlib. 704 composite_transform_factory() (in module mat.Patch method).Axes method).patches.Rectangle method). 362 contourf() (matplotlib. 253 connect() (matplotlib. 425 contourf() (in module matplotlib.dviread.collections. 546 method).Angle3 contour() (in module matplotlib.Angle3 (class in matmethod). 709 method). 363 ColorConverter (class in matplotlib.BboxBase connect() (matplotlib.pyplot). 662 ConnectionStyle. plotlib.Figure method).cbook. 424 method).patches. 372 method).transforms).axes. 362 code_type (matplotlib. 425 plotlib.patches. 539 Collection (class in matplotlib. 597 method).ConnectionStyle.patches). 425 cohere_pairs() (in module matplotlib.Axes method).ConnectionStyle. 362 clim() (in module matplotlib.Path method).Matplotlib.Collection Colorbar (class in matplotlib. 851 close_event() (mat.FigureCanvasBase ConnectionStyle. 832 plotlib. 662 contains_point() (matplotlib.backend_pdf. 831 ConnectionStyle.figure.patches). contains() method). 362 connect() (matplotlib.patches.pyplot).RendererBase 362 method).Text method). 573 method).pyplot).figure.Arc (class in matplotlib. 268 (matplotlib.contains_path() (matplotlib.Dvi method). 359 method).patches). 385 contains() (matplotlib.path. 562 colorbar() (in module matplotlib.patches.backend_bases.backends.Bar (class in matplotlib.Axes method).ConnectionStyle. 699 contains() (matplotlib.mlab).pyplot). 328 cohere() (matplotlib.pyplot).axes.mlab).path.Angle (class in matplotlib. 267 config_axis() (matplotlib.YAxis method).artist.patches).LineCollection contains() (matplotlib.figure. 579 contains() (matplotlib. 561 color() (matplotlib. 695 contains() (matplotlib.Figure method). method). 361 close() (matplotlib.patches).pyplot).ConnectionStyle.XAxis method). 599 colorbar() (matplotlib.Ellipse method).Path attribute). 843 CloseEvent (class in matplotlib.Figure method).patches.patches). 573 contains() (matplotlib. 253 connect() (matplotlib.collections). 362 close_group() (matConnectionStyle.Arc3 clf() (matplotlib.Path method).pyplot).contains() (matplotlib.transforms.axis. colormaps() (in module matplotlib.Axes method).Artist method).transforms).colorbar). 361 644 connect() (matplotlib. 641 362 cohere() (in module matplotlib.Tick method).Patch method).ConnectionStyle.axis. cohere() (in module matplotlib.text.pyplot). 540 contains() (matplotlib.BboxBase method). 362 close() (matplotlib.ConnectionStyle. 420 contains() (matplotlib.backend_bases. 574 contains_point() (matplotlib.PdfPages ConnectionPatch (class in matplotlib.patches. 371 Colormap (class in matplotlib.1 connect() (matplotlib.backend_bases).BboxBase CompositeAffine2D (class in matplotlib.Axes method).CallbackRegistry containsy() (matplotlib. 702 377 colors() (in module matplotlib.patches). 662 connect() (in module matplotlib.path.Line2D method).patches.mlab). 361 plotlib.ColorbarBase contains_point() (matplotlib. 253 268 CompositeGenericTransform (class in mat.transforms. 341 ColorbarBase (class in matplotlib.colorbar).colors). 566 contains() (matplotlib.transforms). 430 864 Index . 850 ConnectionStyle (class in matplotlib. 642 contains() (matplotlib. 542 method).axes. 578 contains() (matplotlib.axes. 706 containsx() (matplotlib.axes. 694 connect() (matplotlib.colorbar. 387 plotlib.Arc contour() (matplotlib.colors).Axes method).collections.axes.Annotation method).lines.axis.0. 707 method).transforms. Release 1. mlab).axes. 599 drag_pan() (matplotlib.cbook. 646 depth (matplotlib.dviread.Figure attribute).axes. 837 destroy() (matplotlib.mlab).mathtext.DateLocator method).Figure method).font_manager. 551 disconnect() (in module matplotlib.mlab).pyplot).dviread. 439 disconnect() (matplotlib. 615 cross_from_above() (in module matplotlib.Fonts method). 646 dist_point_to_segment() (in module matplotlib. 830 convert_mesh_to_paths() (matplotlib. 718 delaxes() (matplotlib.mlab). 631 copy_properties() (matplotlib. 644 csd() (in module matplotlib.collections. 550 cool() (in module matplotlib.Axis method). 646 detrend_linear() (in module matplotlib.mlab).pyplot). 665 convert_units() (matplotlib.mlab).State method). 646 distances_along_curve() (in module matplotlib. 254 count_contains() (matplotlib.FigureManagerBase method).TruetypeFonts method). 647 donothing_callback() (in module matplotlib.pyplot). 535 convert_xunits() (matplotlib.figure. 588 date2num() (in module matplotlib. 568 convert_mesh_to_triangles() (matplotlib.BboxBase method). 626 copy() (matplotlib. 646 dict_delall() (in module matplotlib.ConversionInterface static method). 587 DateLocator (class in matplotlib.artist. 718 disconnect() (matplotlib.mathtext.path).cbook).BboxBase method).units). 613 copy() (matplotlib.Parser method).TickHelper method).dates).Matplotlib.units.CallbackRegistry method).Axes method).0. 645 csvformat_factory() (in module matplotlib.FontProperties method).cbook).mathtext.ticker. 328 convert_yunits() (matplotlib. 588 dateutil. 254 count_overlaps() (matplotlib. 632 D datalim_to_dt() (matplotlib.pyplot). 857 DayLocator (class in matplotlib.mlab). 590 dedent() (in module matplotlib.dates).dates). 714 copper() (in module matplotlib.backend_bases).mlab).dates).mathtext. 439 865 . 823 createFontList() (in module matplotlib.mathtext. 644 csd() (in module matplotlib. 625 destroy() (matplotlib.BboxBase method).cbook).font_manager).pyplot). 830 delaxes() (in module matplotlib.1 ConversionInterface (class in matplotlib.transforms.collections.mlab).QuadMesh static method). 551 distances_along_curve() (in module matplotlib.transforms.Tfm attribute). 254 create_dummy_axis() (matplotlib.ConversionInterface static method).artist. 837 corners() (matplotlib.mlab). 714 copy() (matplotlib.QuadMesh method).Parser.Artist method). 714 csd() (matplotlib.mlab). 647 dpi (matplotlib.cbook).mlab). 853 destroy() (matplotlib.backend_bases.units. 829 convert() (matplotlib.dates. 328 converter (class in matplotlib.backend_bases.Axes method). 550 demean() (in module matplotlib. 634 detrend() (in module matplotlib.Axes method).GlueSpec method).GraphicsContextBase method). 587 DateFormatter (class in matplotlib.axis.mlab). 853 design_size (matplotlib. 546 dist() (in module matplotlib. 568 convert_path_to_polygons() (in module matplotlib.cbook). 644 cross_from_below() (in module matplotlib. 831 Index customspace() (matplotlib. 646 Cursors (class in matplotlib.figure.mlab). 599 delete_masked_points() (in module matplotlib.Artist method). 435 csv2rec() (in module matplotlib. Release 1. 550 default_units() (matplotlib. 646 detrend_mean() (in module matplotlib.Tfm attribute).transforms. 646 detrend_none() (in module matplotlib.axes. Collection method). 328 draw_frame() (matplotlib. 719 method).backend_bases.backend_bases.colorbar.backend_bases. 847 method). 599 plotlib.backend_bases.artist.RendererBase method).collections.FigureCanvasBase method).NavigationToolbar2 draw_bbox() (in module matplotlib.backends.Shadow method).0.dviread).FigureCanvasQTAgg draw() (matplotlib.FigureCanvasWxAgg draw_image() (matmethod).RendererBase 562 method). 570 method). 336 draw_event() (matdrange() (in module matplotlib.legend.1 method). 385 Dvi (class in matplotlib. 568 plotlib. 341 method). 372 drawRectangle() (matdraw() (matplotlib. 832 draw() (matplotlib.EllipseCollection draw_path() (matplotlib.collections.figure.text.patches. 844 draw() (matplotlib.backend_qt4agg. 587 plotlib. 851 (matdraw_all() (matplotlib.backend_bases). Release 1. 382 draw_cursor() (matmethod).spines.Figure method).FigureCanvasBase draggable() (matplotlib. 539 plotlib. 574 drag_pan() (matplotlib.backend_bases.backend_bases.Text method).CircleCollection method).legend. 843 draw() (matplotlib.RendererBase method).backend_bases. 843 method). 360 draw() (matplotlib. 380 plotlib.RendererBase draw() (matplotlib.axes. 599 draw_rubberband() (matdraw() (matplotlib.Axis method). 841 drag_zoom() (mat. 851 draw() (matplotlib. 338 plotlib.collections. 831 draw() (matplotlib. 841 plotlib.axis.Tick method).NavigationToolbar2 draw_artist() (matplotlib. draw_markers() plotlib.dviread).patches). 844 method).collections. 841 method).FigureCanvasQTAgg draw_idle() (matplotlib. 847 draw() (matplotlib.legend).Matplotlib.QuadMesh method).Legend method).patches.figure.RegularPolyCollection draw_quad_mesh() plotlib.Axes method).Legend method). 832 draw() (matplotlib.FigureCanvasBase draw() (in module matplotlib.pyplot).backend_bases.backend_bases.RendererBase draw() (matplotlib.axis.backend_qt4agg. 439 method). 841 draw() (matplotlib.RendererBase method).RendererBase method).NavigationToolbar2 draw_gouraud_triangles() plotlib. 387 draw() (matplotlib.lines.PolyCollection draw_path_collection() (matmethod).text.ColorbarBase dynamic_update() 866 Index . 848 plotlib.Arc method).patches.backends. 535 draw_gouraud_triangle() (matdraw() (matplotlib. 348 draw() (matplotlib.RendererBase draw() (matplotlib.backend_bases. 439 338 draw() (matplotlib.Axes method).Line2D method).ConnectionPatch draw_tex() (matplotlib.Legend method). 392 DviFont (class in matplotlib.backend_bases. 843 draw() (matplotlib. 832 (matdraw() (matplotlib. 844 569 (matdraw() (matplotlib. 844 method).text.RendererBase method).legend.patches. 843 method).FancyArrowPatch draw_text() (matplotlib. method). 561 (matdraw() (matplotlib.axes. 844 draw() (matplotlib.Spine method). 565 method). 818 method). draw() (matplotlib. 366 DrawEvent (class in matplotlib.collections.backend_bases.backend_bases.collections.Figure method).backend_bases.Annotation method). 338 method).TextWithDash method).NavigationToolbar2 draw() (matplotlib.Patch method).FigureCanvasBase method).patches.backend_bases.dates).draw_artist() (matplotlib. 832 DraggableLegend (class in matplotlib.backend_wxagg.backend_bases.Artist method).backends.backend_bases. figure).mlab). 732 fill_betweenx() (matplotlib.backends.backend_bases.mlab). 617 class mat- family_unescape() (in module matplotlib.fontconfig_pattern).axes. 725 Figure (class in matplotlib.FigureCanvasBase method).axes. 440 enter_notify_event() (matplotlib.Axes method). 362 EllipseCollection (class in matplotlib.Axes method).patches).backends.backend_wxagg).backends.backend_pdf. 220 PATH. 448 Filll (class in matplotlib. 832 FigureCanvasPdf (class in matplotlib. 624 errorbar() (in module matplotlib.Patch attribute). 336 find() (in module matplotlib. 727 FigureCanvasBase (class in matplotlib.backend_wxagg). 254 extents (matplotlib.Encoding attribute).backend_bases).Stack method).pyplot).backend_qt4agg). 54. 593 figure() (in module matplotlib. 852 encoding (matplotlib. 367 fftsurr() (in module matplotlib.BboxBase attribute).pyplot).mathtext).axes. 850 end_group() (matplotlib.pyplot).pyplot). 832 entropy() (in module matplotlib. 372 fill() (in module matplotlib.DraggableLegend method). 364 FancyBboxPatch (class in matplotlib.backend_pdf.patches).Axes method).patches. 851 fill() (in module matplotlib. 841 E Ellipse (class in matplotlib.mlab). 363 FancyArrowPatch (class in matplotlib.patches). 719 errorbar() (matplotlib.backends.dates).0. 587 EPS.font_manager).figure. 548 Encoding (class in matplotlib.backend_pdf). 831 exception_to_str() (in module matplotlib.mathtext).1 plotlib. 440 Event (class in matplotlib.backend_bases).backends. 551 findfont() (in module matplotlib. 233 epoch2num() (in module matplotlib.dviread. 626 family_escape() (in module plotlib.mathtext).collections).BboxBase method).backend_bases). 647 FIFOBuffer (class in matplotlib.mlab). 849 empty() (matplotlib. 624 Fill (class in matplotlib.backends.legend.backend_pdf).pyplot).mathtext. 849 FigureCanvasQTAgg (class in matplotlib.axes. 632 end_pan() (matplotlib. 551 exp_safe() (in module matplotlib.fontconfig_pattern). 609 figimage() (in module matplotlib. 848 Fil (class in matplotlib. 847 FigureCanvasWxAgg (class in matplotlib.dviread). 731 fill_between() (matplotlib. 728 fill() (matplotlib.PdfFile method). 254 F factory() (matplotlib.cbook). Release 1. 837 FigureManagerQTAgg (class in matplotlib.backend_qt4agg). 647 find_tex_file() (in module matplotlib. 848 FigureFrameWxAgg (class in matplotlib.mathtext. 52.transforms. 647 expanded() (matplotlib.Stream method).backends. 599 figlegend() (in module matplotlib.Matplotlib.pyplot). 722 figimage() (matplotlib.NavigationToolbar2 method). 220 MPLCONFIGDIR. 724 figtext() (in module matplotlib.dviread).mathtext). 857 Error() (in module matplotlib.pyplot).axes.transforms.pyplot). 443 fill_between() (in module matplotlib. 853 finddir() (in module matplotlib. 617 FancyArrow (class in matplotlib.cbook). 852 end() (matplotlib. 647 environment variable HOME. 615 Index 867 .Parser method). 624 finalize_offset() (matplotlib. 564 embedTTF() (matplotlib.backends.patches). 446 fill_betweenx() (in module matplotlib.figure).Figure method).mlab). 639 figaspect() (in module matplotlib.cbook.GlueSpec method).backend_bases. 55 PYTHONPATH.Axes method). 848 FigureManagerBase (class in matplotlib.Axes method). 624 fill (matplotlib. freetype.mlab.mlab).Formatter frozen() (matplotlib.Affine2DBase method).FormatInt method). 616 method). 265 format_data_short() (matplotlib.ticker. 639 Fonts (class in matplotlib.fromstr() (matplotlib.mlab).ticker.mathtext.RendererBase Formatter (class in matplotlib. 734 824 findobj() (matplotlib. 849 (matplotlib. 639 format_coord() (mat.backend_pdf. method).mlab). 640 FixedLocator (class in matplotlib.PolarAxes fromstr() (matplotlib.BlendedGenericTransform method).backends. 261 format_data() (matplotlib.Parser method). 823 method). 640 frozen() (matplotlib.Stack method). 328 findobj() (matplotlib. 631 frame (matplotlib. 263 613 fromstr() (matplotlib.ticker). 551 flipy() (matplotlib.LogFormatter 868 Index .FormatBool method).ScalarFormatter method).0. 611 plotlib. 449 frange() (in module matplotlib.font_manager. 639 finish() (matplotlib.backend_bases.mlab).fontconfig_pattern).pyplot).LinearSegmentedColormap static method).Parser method). 640 method).Axes method).mlab).transforms.mlab.mlab).font_manager).backend_bases. 277 640 format_data() (matplotlib. 449 format_ydata() (matplotlib. 640 method).1 method). from_extents() (matplotlib. format_xdata() (matplotlib.FormatDatetime method).ticker. 640 823 fix_minus() (matplotlib.font_manager).State attribute).axes. 826 FormatStrFormatter (class in matplotlib.transforms.transforms.Affine2D FontProperties (class in matplotlib.artist. 841 flush_events() (matforward() (matplotlib.Axes attribute).artist. 632 method).FontManager format_data_short() (matmethod).transforms.Bbox static method).ticker.FormatBool (class in matplotlib.FormatFloat method). 857 method).PdfFile from_list() (matplotlib. 640 FixedFormatter (class in matplotlib. 615 FormatDatetime (class in matplotlib.mathtext.mlab). 824 254 format_data_short() (matplotlib.mlab.ticker.BboxBase method). 844 forward() (matplotlib. 823 FormatPercent (class in matplotlib.mlab.ticker. 624 format_coord() (matplotlib.NavigationToolbar2 FLTK.FigureCanvasBase frac() (matplotlib.font_manager).transforms. 823 FormatThousands (class in matplotlib.FormatDate method).FormatObj method). 640 823 format_data() (matplotlib.axes.mathtext).backend_bases. from_values() static method). 639 plotlib. FormatFloat (class in matplotlib. 857 from_bounds() (matplotlib. 832 font (matplotlib.mathtext. 581 method).mathtext. 256 611 fontName() (matplotlib.cbook).polar. 647 font() (matplotlib.transforms. 824 flag() (in module matplotlib. 824 FormatObj (class in matplotlib.mlab). 632 FontconfigPatternParser (class in mat.ticker).mlab). method).mlab). 632 fix_minus() (matplotlib. 640 flatten() (in module matplotlib.axes. 611 FontManager (class in matplotlib. 639 plotlib.Axes method). 825 findfont() (matplotlib.cbook. 734 FormatString (class in matplotlib. Release 1. 256 FontEntry (class in matplotlib.font_manager).Artist method).ScalarFormatter FormatInt (class in matplotlib.Parser method).mlab.Formatter method). 548 plotlib.LogFormatter fromstr() (matplotlib.ArtistInspector method).colors.mlab).mlab.Matplotlib. 825 method).ticker). findobj() (in module matplotlib.ticker. fromstr() (matplotlib.mlab). 639 FormatDate (class in matplotlib.projections. 449 334 findSystemFonts() (in module mat.ticker).pyplot).Axes method).Bbox static plotlib.ScalarFormatter frozen() (matplotlib. 639 FormatFormatStr (class in matplotlib.axes. 640 FormatMillions (class in matplotlib. 449 fromstr() (matplotlib.Formatter method).Parser.ticker. transforms. 837 360 fully_contains() (matplotlib.axes. 266 method). 617 get_autoscaley_on() (matplotlib.figure. 632 get_arrowstyle() (matG plotlib.patches.Axes method).ticker). 323 FT2Image() (in module matplotlib. 849 method).IdentityTransform frozen() (matplotlib.pyplot). Release 1.patches.artist.Line2D method).Artist method). 385 get_angle() (matplotlib.Patch method). 264 frozen() (matplotlib.Matplotlib.transforms.TransformWrapper get_aliases() method).BboxBase method). 323 Index 869 .axes.Artist method).IdentityTransform get_affine() method).CompositeGenericTransform (matplotlib. 449 get_axis_bgcolor() (matplotlib. 450 gcf() (in module matplotlib.mathtext. generate_fontconfig_pattern() (in module mat450 plotlib. 335 get_axes() (matplotlib.Axes method).artist.transforms. 624 full_screen_toggle() (mat.ScalarMappable FuncFormatter (class in matplotlib.BlendedGenericTransform get_bbox() (matplotlib. 372 method).Axes method).ArtistInspector frozen() (matplotlib.cbook. 254 fully_overlaps() (matplotlib.FancyArrowPatch method).patches.axes. 260 FT2Font() (in module mat.Axes method).transforms.Axes method). 267 (matplotlib. 264 method). 254 get_array() (matplotlib.Axes method).artist). 254 fully_containsy() (matplotlib. 735 366 gca() (matplotlib.transforms. 261 get_axisbelow() (matplotlib. 547 get_axes() (matplotlib. 334 method).patches.ConnectionPatch method).Parser method).Artist method).patches.Patch method).backend_bases.transforms.FancyBboxPatch method). 557 function() (matplotlib.backend_pdf).transforms. 837 FT2Font() (in module matplotlib. 328 (matplotlib.1 get_affine() (matplotlib.mathtext).transforms.backend_bases.mathtext).pyplot).pyplot).text). gci() (in module matplotlib.transforms. 254 plotlib.lines.artist. gca() (in module matplotlib.Axes method).axes.transforms. 735 450 GDK.afm. get_bbox() method).CompositeGenericTransform method).Figure method). 632 450 get() (in module matplotlib.artist. 253 (matplotlib.0.TransformNode get_agg_filter() (matplotlib.RingBuffer method). 450 get_affine() (matplotlib.Artist method).Transform frozen() (matplotlib. 600 get_aspect() (matplotlib.Axes method).Rectangle method).GraphicsContextBase fully_containsx() (matplotlib. 601 get_aa() (matplotlib. get_affine() (matplotlib. 328 method). 267 377 get_bbox_char() (matplotlib.axes.axes. method). 369 get_affine() (matplotlib.backends. genfrac() (matplotlib. 259 method).Parser method).figure.get_alpha() (matplotlib.transforms.axes. 857 get_autoscalex_on() (matplotlib.AffineBase 450 method).cm. 372 450 get_adjustable() (matplotlib. 341 method).axes.lines.artist. 341 get_axes_locator() (matplotlib. 328 get_alpha() (matplotlib.Figure method).fontconfig_pattern). 823 method).Line2D method). 837 method).patches.transforms.BboxBase get_antialiased() (matplotlib. 328 get() (matplotlib.transforms.AFM method).AFM method).axes.BboxBase get_antialiased() (matmethod).afm.backend_bases. 624 get_anchor() (matplotlib.Axes method).mathtext.BboxBase get_antialiased() (matplotlib. get_aa() (matplotlib.GraphicsContextBase plotlib. 450 FT2Font() (in module matplotlib.get_animated() (matplotlib. 735 get_autoscale_on() (matplotlib.FigureManagerBase get_annotation_clip() plotlib. backend_bases.axes. 369 366 get_c() (matplotlib.TextWithDash 557 method).Collection get_children() (matplotlib.artist.backend_bases.units.GraphicsContextBase get_dashdirection() (matplotlib.artist.text.GraphicsContextBase get_data_interval() (matplotlib.axis.XAxis method).NavigationToolbar2WxAgg get_cursor_props() (matplotlib.DummyAxis method).text. 837 (matget_child_artists() (matplotlib.Line2D method).TextWithDash method).Artist method). 328 get_data() (matplotlib. get_dashes() plotlib.lines.XTick method).axes. 566 get_bounds() (matplotlib. 393 get_children() (matplotlib.get_current_fig_manager() (in module matplotlib.patches.axis.FancyBboxPatch get_connectionstyle() plotlib.Line2D method).TextWithDash 601 method).TextWithDash 338 method).AFM method).axes.axis.afm. 540 method).Polygon method). 393 get_children() (matplotlib. Release 1.backend_wxagg.patches. 376 543 get_cmap() (in module matplotlib.spines. 392 method).Axes method).backend_wxagg.backends.axis.YTick method).get_contains() (matplotlib. 735 plotlib. 328 get_dashes() (matplotlib.lines. get_dashpad() (matplotlib. 341 method).backend_bases.pyplot).axes. 341 get_capstyle() (matplotlib.text. 822 get_color() (matplotlib.Axis method).legend. method). 328 get_clip_path() (matplotlib. 558 (matget_cmap() (matplotlib.patches.artist.cm.lines.GraphicsContextBase get_data_interval() (matplotlib. 845 (matplotlib. get_dashrotation() (matplotlib.ticker.YAxis method).collections. 341 get_clip_on() (matplotlib.Spine method).axis. method). 387 get_color() (matplotlib. 451 method). 328 get_converter() (matplotlib.lines.1 get_bbox_patch() (matplotlib.text.Text method).backends.Artist method). 562 get_children() (matplotlib.Axes method). get_dashpush() (matplotlib.Artist method).text.cm).0. 393 get_clip_box() (matplotlib.Axes method). 557 method).axis.Axis method). 566 870 Index .axis.GraphicsContextBase 450 method). 338 method).TickHelper.TextWithDash get_children() (matplotlib.FancyArrowPatch method).LineCollection get_data_ratio() (matplotlib. 837 get_clip_rectangle() (mat.Legend method).text.legend.RendererBase method).LineCollection method). 393 get_clim() (matplotlib.Legend get_color() (matplotlib.collections.figure. 323 get_dash_joinstyle() method). 837 542 get_closed() (matplotlib.cm.Text method).Line2D get_capheight() (matplotlib.backend_bases. 818 (matget_boxstyle() (matplotlib.Tick method).Artist method). 535 get_clip_path() (matplotlib.artist. 539 method). get_data_interval() (matplotlib.text. plotlib.FigureFrameWxAgg 830 method).artist.Registry method). 848 get_canvas() (mat.ScalarMappable get_data_interval() plotlib.get_data_interval() (matplotlib. 848 450 get_canvas_width_height() (matget_dash_capstyle() (matplotlib.Line2D plotlib. 387 get_colors() (matplotlib.Matplotlib. method).backend_bases.ScalarMappable method). 541 plotlib. 837 get_children() (matplotlib.collections. 450 method). 328 get_data_interval() (matplotlib.Figure method). 535 get_dashlength() (matplotlib.Artist method). 341 get_canvas() (mat.lines.Line2D method). 341 get_bbox_to_anchor() (matplotlib.Axes method). 277 get_data_ratio_log() (matplotlib. 562 get_datalim() (matplotlib.figure.Text method).FontProperties method). 324 get_fontname() (matplotlib.text.axes. 388 get_formatd() (in module matplotlib. 662 get_facecolor() (matplotlib.AFM method).mathtext.afm. 341 get_ec() (matplotlib.figure.lines. 562 get_family() (matplotlib. 387 get_fontstretch() (matplotlib. 562 get_extents() (matplotlib. 628 get_dpi() (matplotlib. 569 get_default_filetype() (matplotlib. 341 get_font_properties() (matplotlib.font_manager.collections. 387 get_fontstyle() (matplotlib.patches.font_manager.afm.font_manager. 329 get_figure() (matplotlib.figure.text. 339 get_frameon() (matplotlib.TransformedPath method).Text method).Figure method).Axes method).polar.Collection method).Axes method). 562 get_facecolor() (matplotlib.collections.AFM method). 388 get_fontweight() (matplotlib.Figure method).FontManager method).patches.1 get_data_ratio() (matplotlib. 832 get_default_size() (matplotlib.Figure method).collections.Patch method). 562 get_edgecolor() (matplotlib.Text method).patches. 387 get_fontconfig_fonts() (in module matplotlib. 372 get_facecolors() (matplotlib.Axes method).Collection method).pyplot).FontProperties Index method). 648 get_frame() (matplotlib.Text method). 614 get_family() (matplotlib.text.collections. 372 get_fillstyle() (matplotlib.text.collections. 451 get_frame() (matplotlib.Collection method). 451 get_frame_on() (matplotlib.Text method). 393 get_figwidth() (matplotlib.TextWithDash method).font_manager. Release 1.FigureCanvasBase method).Text method).Matplotlib.text. 387 get_fontvariant() (matplotlib.axes.artist.Patch method).font_manager.FontProperties method). 451 get_data_transform() (matplotlib.Text method). 366 get_drawstyle() (matplotlib.text. 372 get_datalim() (matplotlib. 612 get_default_weight() (matplotlib.Line2D method).Patch method).Path method).Patch method). 324 get_fully_transformed_path() (matplotlib.QuadMesh method).Patch method).patches.PolarAxes method). 602 get_file() (matplotlib.path. 269 871 .Collection method).figure.text.Figure method). 614 get_fill() (matplotlib. 338 get_frame_on() (matplotlib. 387 get_familyname() (matplotlib.patches.FancyArrowPatch method). 324 get_fc() (matplotlib.patches. 372 get_figheight() (matplotlib. 372 get_edgecolor() (matplotlib.Legend method).Text method).transforms.FontManager method).Patch method).Artist method). 736 get_figure() (matplotlib.Line2D method).Figure method).patches.figure.legend.Text method). 387 get_fontsize() (matplotlib. 602 get_facecolor() (matplotlib. 612 get_depth() (matplotlib.Collection method). 387 get_fontproperties() (matplotlib.AFM method). 601 get_dpi_cor() (matplotlib. 602 get_fignums() (in module matplotlib.collections.mlab). 602 get_fullname() (matplotlib.Patch method).figure.font_manager).text.text.afm.Text method).axes. 614 get_fontext_synonyms() (in module matplotlib.text. 372 get_extents() (matplotlib.lines.legend.MathTextParser method). 601 get_edgecolor() (matplotlib. 615 get_fontconfig_pattern() (matplotlib. 616 get_fontfamily() (matplotlib.font_manager).Legend method).patches.projections.Figure method). 372 get_edgecolors() (matplotlib.0.backend_bases. 387 get_fontname() (matplotlib.text. Patch method).MathtextBackend 341 method).axes.mathtext.mathtext.backend_bases.Collection get_images() (matplotlib. 838 get_horizontal_stem_width() (matplotlib.backend_bases.axis.patches.afm. 629 get_hinting_type() (mat.Axes method).Line2D method). 451 get_legend_handles_labels() (matplotlib.collections. get_linestyle() (matplotlib.axis. 562 get_hinting_type() (matget_linewidth() (matplotlib.patches. 452 377 get_height_char() (matplotlib. 539 872 Index .gridspec.YAxis get_hatch_path() (mat. plotlib.backend_bases. 540 get_hatch() (matplotlib.GridSpecBase get_kern() method). method). 625 method). 629 method).axis. 532 (matplotlib.artist. 838 plotlib.axis.GraphicsContextBase get_label_position() (matplotlib. 329 get_ha() (matplotlib.afm.collections. 838 get_geometry() (matplotlib.AFM method). 619 624 get_gridlines() (matplotlib. 619 (matplotlib.FancyBboxPatch get_legend() (matplotlib.backend_bases.Artist method). 388 get_label() (matplotlib.text.gridspec.SubplotBase get_kern() (matplotlib.artist.Node method).axes.Axes method).backend_bases. 620 get_kern_dist() (matplotlib. 562 get_hinting_type() (matget_linestyle() (matplotlib. 562 get_joinstyle() (matplotlib.get_label_position() method). 542 plotlib.Collection method).Artist method).Fonts method). 562 get_horizontalalignment() (matplotlib.AFM get_linewidth() (matplotlib.Collection 620 method). 634 method).AFM method).mathtext. get_lines() (matplotlib.Line2D method).Text get_linewidth() (matplotlib.axes. 633 method).collections. 838 method).SubplotSpec get_kern() method).axis.Axes method).patches. 388 341 get_image_magnification() (matget_linewidth() (matplotlib.afm. 324 get_gid() (matplotlib.1 method).MathtextBackendAggRender get_linestyles() (matplotlib. 629 method).RendererBase 372 method).MathtextBackendBbox plotlib.Legend method).lines.collections.Text method).SubplotSpec get_kerning() (matplotlib. 324 plotlib. 535 method). 372 plotlib.GridSpecBase method).Char method). 339 get_linestyle() (mat324 plotlib. 324 method).Patch method). get_lines() (matplotlib.Axis method).Patch method).0.lines.GraphicsContextBase method).GridSpecBase method).GraphicsContextBase get_loc() (matplotlib.Axis method).get_kern_dist_from_name() (matplotlib. 845 get_linewidths() (matplotlib.TruetypeFonts get_geometry() (matplotlib.gridspec. 451 get_height() (matplotlib.mathtext.mathtext. 631 method).get_linestyle() (matplotlib.StandardPsFonts get_geometry() (matplotlib. 451 method). 535 get_gridspec() (matplotlib.Tick method).GraphicsContextBase get_label_text() (matplotlib.gridspec. 369 method). 620 get_label() (matplotlib.mathtext. plotlib.Collection method).axes.axes.mathtext. 372 (matplotlib.XAxis method).Rectangle method).gridspec. Release 1.Axis method).backend_bases.mathtext.AFM method).text.patches.patches.Axes method).legend. 329 get_grid_positions() (mat.axis. get_kerning() (matplotlib.Matplotlib.GraphicsContextBase get_height_ratios() (matmethod).afm. 535 get_hatch() (matplotlib. 838 get_height() (matplotlib. lines.axis.transforms. 541 342 get_markevery() (matplotlib.axis.XTick method). get_matrix() (matplotlib.Line2D method).transforms.FancyBboxPatch method). 341 536 get_markerfacecolor() (matplotlib. 263 (matget_matrix() (matplotlib.lines.Axis method).BboxTransformTo get_name() (matplotlib.YTick method). 269 536 get_major_ticks() (matplotlib.transforms.transforms. method).projections.lines. get_matrix() (mat369 plotlib.CompositeAffine2D get_ls() (matplotlib.Axis method).Axis method).0.axis.lines. 543 get_ms() (matplotlib. 276 plotlib. 267 get_locator() (matplotlib.patches. get_minpos() (matplotlib. 269 plotlib.Axis method).lines.dates.Line2D get_minorticklines() (matplotlib. 535 plotlib.lines. 342 536 (matplotlib.Line2D method).Line2D method).text. get_matrix() (mat366 plotlib.transforms. 372 method). method).axis.axis. 341 method). 589 plotlib.Affine2D 366 method). 261 369 get_matrix() (matplotlib.axis.lines.Axis method).Line2D method).patches.axis. 536 625 get_majorticklabels() (matplotlib.lines.Line2D method). 342 536 get_majorticklines() (matplotlib.patches. 536 get_markeredgecolor() (matplotlib. 341 536 get_markeredgewidth() (matplotlib. 268 get_ls() (matplotlib.transforms.YAxis method).Line2D method).lines.AffineBase get_mutation_aspect() plotlib.Axis method). get_minpos() (matplotlib. 388 plotlib.IdentityTransform get_lw() (matplotlib. 342 get_mfcalt() (matplotlib. 536 536 get_marker() (matplotlib.get_minpos() (matplotlib. 614 get_matrix() (matget_name() (matplotlib. get_mfc() (matplotlib.lines.ScaledTranslation get_major_locator() (matplotlib.Fonts method).Axis get_matrix() (matmethod). method).Axis method).Line2D method).font_manager.transforms. method). 341 536 get_markerfacecoloralt() (matplotlib.lines.BboxTransformFrom get_mutation_scale() (matmethod).FontProperties method).PolarAxes.mathtext.axis. 342 plotlib.Axis method).Text method). 269 plotlib.axis.FancyArrowPatch method).patches.Line2D get_minor_ticks() (matplotlib. 372 get_matrix() (matget_lw() (matplotlib. get_minor_formatter() method). 542 342 get_matrix() (mat.polar.lines.axis.axis. 341 536 get_markersize() (matplotlib.Line2D get_minorticklabels() (matplotlib.transforms. 269 method).PolarAffine get_mutation_aspect() (matmethod).transforms. Release 1.patches.1 method).FancyArrowPatch method).patches.Axis method).axis.Patch method).Axis get_majorticklocs() (matplotlib.Line2D method).Matplotlib.XAxis method). 264 get_major_formatter() (matplotlib.axis. method). 341 get_minor_locator() (matplotlib.BlendedAffine2D Index 873 . method).AutoDateLocator get_matrix() (matmethod). 542 get_minpos() (matplotlib.Line2D method).Patch method).lines.Axis method).BboxTransform get_mutation_scale() (matmethod).FancyBboxPatch method). 342 get_metrics() (matplotlib.axis.lines. get_mew() (matplotlib. 341 plotlib. get_mec() (matplotlib.axis.Line2D get_minorticklocs() (matplotlib.Line2D method).axis. Patch method). 329 get_pickradius() (matplotlib.PathPatch method).spines.patches. 818 get_path_collection_extents() (in module matplotlib.patches.transforms. 536 get_pickradius() (matplotlib.Arrow method). 452 get_navigate_mode() (matplotlib. 563 get_pickradius() (matplotlib. 324 get_navigate() (matplotlib. 372 get_patch_transform() (matplotlib.collections.patches.Axis method). 380 get_patch_transform() (matplotlib.transforms.legend.patches.collections. 570 get_offset() (matplotlib. 375 874 get_path() (matplotlib.TextWithDash method).collections. 452 get_numsides() (matplotlib. Release 1.axes.patches. 350 get_path() (matplotlib.AFM method). 379 get_path() (matplotlib. 620 get_position() (matplotlib.Text method). 363 get_patch_transform() (matplotlib. 824 get_offset_text() (matplotlib.patches.ConnectionPatch method). 382 get_path() (matplotlib.Patch method).Axis method). 665 get_path_in_displaycoord() (matplotlib.axis.Wedge method). 393 get_projection_class() (in module matIndex . 377 get_patch_transform() (matplotlib.FancyArrowPatch method).Arrow method). 376 get_path() (matplotlib.patches.Collection method).Axes method).FancyBboxPatch method). 569 get_picker() (matplotlib.Shadow method).Spine method).Rectangle method).path).RegularPolyCollection method).axes.gridspec.Patch method).RegularPolygon method).Line2D method). 562 get_pad() (matplotlib.patches.patches. 379 get_patch_transform() (matplotlib.YAArrow method).Ellipse method).FancyArrowPatch method).Spine method).collections. 380 get_path() (matplotlib.collections. 372 get_path_effects() (matplotlib. 736 get_points() (matplotlib.patches.Tick method).Spine method). 258 get_position() (matplotlib.afm.Collection method).Ellipse method).ticker.patches. 536 get_offsets() (matplotlib.Text method). 382 get_patch_transform() (matplotlib.Polygon method). 388 get_path_extents() (in module matplotlib.patches.patches. 342 get_plot_commands() (in module matplotlib.axis.Line2D method). 363 get_path() (matplotlib. 818 get_patches() (matplotlib.0.FixedFormatter method). 823 get_offset() (matplotlib. 823 get_offset() (matplotlib.YAArrow method).axes. 540 get_patch_transform() (matplotlib.text.axis.patches. 360 get_path_in_displaycoord() (matplotlib. 388 get_position() (matplotlib.Bbox method).patches.Axes method). 372 get_path() (matplotlib.spines.Artist method). 339 get_path() (matplotlib.artist. 381 get_path() (matplotlib.text. 665 get_path_effects() (matplotlib.spines. 369 get_path() (matplotlib.TransformedBbox method).patches.patches.patches. 350 get_patch_transform() (matplotlib.ticker.patches. 367 get_paths() (matplotlib.Tick method).ScalarFormatter method).Axes method).Shadow method).QuadMesh method).Formatter method).SubplotSpec method). 818 get_position() (matplotlib.RegularPolygon method). 377 get_path() (matplotlib. 563 get_paths() (matplotlib.ticker.patches.path). 367 get_path() (matplotlib.1 get_name_char() (matplotlib.patches.Collection method).pyplot). 539 get_pad_pixels() (matplotlib.lines. 452 get_position() (matplotlib.text.Matplotlib.patches.axis.Rectangle method). 342 get_path() (matplotlib. 257 get_points() (matplotlib.lines.Legend method). text).RegularPolyCollection method).mathtext. 551 method).text. 274 329 (matplotlib.artist.axis.TextWithDash get_sample_data() (in module matplotlib.collections.mathtext.Text method).projections).text.axes.Circle method). 275 method).mathtext.text.Artist method).get_sizes() (matplotlib.RegularPolyCollection plotlib. 274 388 get_prop_tup() (matplotlib. 358 get_sample_data() plotlib.get_rgb() (matplotlib. 549 method).Axis method). 630 get_results() (mat.artist.mathtext.get_rotation() plotlib. 838 plotlib.patches. 631 plotlib. 630 get_results() (mat. 570 plotlib. method).mathtext.text.font_manager.FontProperties plotlib. get_results() (mat623 plotlib. 393 (matget_radius() (matplotlib.Figure method). 551 get_renderer_cache() (matplotlib.Matplotlib.mathtext.ArtistInspector get_recursive_filelist() (in module mat.mathtext.mathtext.MathtextBackendSvg Index 875 .mathtext.BakomaFonts method). 630 plotlib. 629 get_results() (mat.projections.UnicodeFonts method).cbook).axes.collections. 630 633 get_results() (matget_sized_alternatives_for_symbol() (matplotlib.projections.mathtext.Text method). 275 get_projection_class() (mat.Axes get_shared_x_axes() (matplotlib. 388 method).mathtext.figure.font_manager. 536 get_scale_docs() (in module matplotlib.MathtextBackendAggRender get_size() (matplotlib.StixFonts method).get_size() (matplotlib.0. 388 plotlib. 602 plotlib.mathtext. 452 method).ViewVCCachedServer get_rasterization_zorder() (matplotlib.cbook. 452 get_rasterized() (matplotlib.text. Release 1.FontProperties method).backend_bases.MathtextBackendCairo get_sized_alternatives_for_symbol() (matmethod).get_size_inches() (matplotlib. 629 (matget_results() (mat.Fonts method). get_shared_y_axes() (matplotlib.MathtextBackendPdf plotlib. 394 method). 334 plotlib.axes.Grouper method). 547 method).Fonts method).Axes method).MathtextBackend get_siblings() (matplotlib. 274 (matget_projection_names() (in module mat. 630 634 get_results() (matget_sizes() (matplotlib.mathtext.collections.cbook.cbook). 561 method). 614 plotlib. 570 get_projection_names() (matget_rotation() (matplotlib.projections). 452 625 get_results() (matplotlib. method). 630 plotlib. 452 get_results() (matplotlib.Text method).Text method).get_size_in_points() plotlib.ProjectionRegistry get_rotation() (in module matplotlib. get_scale() (matplotlib.axes.GraphicsContextBase method). 614 method). method).MathtextBackendBbox method).mathtext.ProjectionRegistry get_rotation_mode() (matplotlib.Axes method).get_setters() method).MathtextBackendBitmapRender get_sized_alternatives_for_symbol() (matmethod).MathtextBackendPs method).Axes method).1 method).MathtextBackendPath plotlib.scale). 388 get_prop_tup() (matplotlib.CircleCollection plotlib. 625 get_results() (matget_sized_alternatives_for_symbol() (matplotlib. font_manager.TransformedPath plotlib.scale.RendererBase get_underline_thickness() (matplotlib.afm.AFM method).get_transforms() (matplotlib.text.Text method).get_title() (matplotlib.scale.axis.axis.TransformedPath plotlib. 536 method).SymmetricalLogScale plotlib.Axis method).Patch method).afm. 453 get_tightbbox() (matplotlib. 342 get_solid_joinstyle() (matplotlib.Axis method). 818 get_text_widths() (matplotlib.axes. 342 get_sparse_matrix() (in module matplotlib. 541 get_spine_transform() (matplotlib. 273 620 (matget_subplot_params() (mat.GridSpecBase method).FontProperties 330 method).font_manager. 330 method).axis. method).collections. 329 542 get_snap() (matplotlib. 339 method). 272 get_subplot_params() (matplotlib. 838 (matplotlib.cbook). 632 get_tightbbox() (matplotlib.figure.YAxis method). 536 get_ticklines() (matplotlib. 536 get_ticks_position() (matplotlib. 324 get_stretch() (mat.Axes method).Parser method).Matplotlib.mathtext.LinearScale get_style() (matplotlib.Figure method). 373 method). 614 541 get_smart_bounds() (matplotlib.axis.axes.backend_bases. 339 get_transform() (matplotlib. 620 (matget_subplotspec() (matplotlib.AFM method). 532 (matget_supported_filetypes() (mat. 614 get_transform() (matplotlib.axes.lines.GridSpec get_transform() (matplotlib.SubplotBase get_transformed_clip_path_and_affine() plotlib. 818 542 get_split_ind() (in module matplotlib.backend_bases. 388 get_text_heights() (matplotlib.backend_bases. Release 1. get_snap() (matplotlib.patches. 269 method).spines.Line2D get_ticklabels() (matplotlib.lines.gridspec.Axis method). 845 876 Index .FontProperties get_transform() (matplotlib.ScaleBase plotlib. 536 method). 551 get_state() (matplotlib.0. 324 602 get_str_bbox_and_descent() (matplotlib.transforms.backend_bases.FontProperties get_text() (matplotlib.Collection method).Text method).XAxis 648 method).Axes method).Artist method).mlab). get_ticklocs() (matplotlib. 388 get_style() (matplotlib. 845 method).GridSpecFromSubplotSpec method). plotlib.axis. 833 get_texmanager() (mat.YAxis method). get_text_width_height_descent() (mat536 plotlib. 537 get_stretch() (matplotlib. 269 method). 453 method). method).FigureCanvasBase method).gridspec.axis.Text method). get_str_bbox() (matplotlib. 619 273 get_subplot_params() (mat(matplotlib.RendererBase get_smart_bounds() (matplotlib.text.get_transform() plotlib.get_transformed_path_and_affine() plotlib.axis.legend.axis. 832 (matget_supported_filetypes_grouped() (mat.font_manager. get_transform() method).Axis method).get_transformed_points_and_affine() plotlib.text.AFM get_title() (matplotlib.artist.scale.LogScale method). 388 method). 274 method).XAxis method).Legend method).Spine get_ticks_position() (matplotlib.FigureCanvasBase method).1 get_slant() (matplotlib.axis.Artist method).afm. 563 plotlib.axis.Artist method).Legend method).GraphicsContextBase get_texts() (matplotlib.legend.Axis get_solid_capstyle() (matplotlib.backend_bases.transforms.gridspec.artist. method).Line2D get_ticklabel_extents() method). 614 get_transform() (matplotlib.Spine method).artist.spines.scale.Axis method). 453 542 get_view_interval() (matplotlib. 386 get_width() (matplotlib.patches. 563 (matget_used_characters() (matplotlib.Line2D method).Axis method). 393 540 (matplotlib.patches.YAxis method). get_weight() (matplotlib.text.patches. get_xaxis_text2_transform() (matplotlib.AFM get_window_extent() (matplotlib.axis.figure. 824 method). 377 get_unit_generic() (matplotlib.FontProperties get_underline_thickness() (matmethod).FontProperties method).0.axis.Legend get_variant() (matplotlib.gridspec. 369 541 get_view_interval() (matplotlib.font_manager.Text method).ticker. 388 634 (matplotlib.axis.XTick method).Patch method).YTick method).ArtistInspector get_window_extent() plotlib.Axes method). 453 get_va() (matplotlib.text. Release 1. 373 get_view_interval() (matplotlib.dates.axes. 324 get_weight() (mat633 plotlib.axes.Rectangle method). 388 (matget_valid_values() (matplotlib.Text get_window_extent() (matplotlib.Matplotlib.Artist method).collections.text.get_width() method).mathtext.ScalarFormatter get_window_extent() (matplotlib.GraphicsContextBase get_width_height() (matmethod).collections.Figure plotlib.FigureCanvasBase get_urls() (matplotlib.patches.Axes method). get_weight() (matplotlib.artist. get_xaxis_text1_transform() (matplotlib. 324 method). 324 get_url() (matplotlib.Text method).TextWithDash method).Text method).axis. get_window_extent() (matplotlib. 373 get_verts() (matplotlib. 453 542 get_view_interval() (matplotlib.get_visible() (matplotlib. 833 method). 339 get_vertical_stem_width() (matplotlib.Text method). 334 563 get_variant() (matget_window_extent() (matplotlib.mathtext.FancyBboxPatch get_view_interval() (matplotlib.ticker. 453 543 Index 877 .axis.text.mathtext.mathtext.Axes method).text. 330 method).axis.Fonts get_width_ratios() plotlib. 838 plotlib. 635 get_unit() (matplotlib.AFM method).RRuleLocator get_width_char() (matplotlib.afm.Collection method).legend.backend_bases.TickHelper.artist. 822 plotlib. method).font_manager. method).XAxis method). 389 537 get_view_interval() (matplotlib.Collection method). 388 method).1 get_view_interval() (matmethod). 369 plotlib. get_window_extent() (matplotlib. 330 plotlib. 614 plotlib. static method).Tick method). 388 method).Artist method).afm.axis.patches. 588 324 get_units() (matplotlib. 625 get_underline_thickness() (mat.FancyBboxPatch get_unicode_index() (in module mat.axes. 342 get_verticalalignment() (matplotlib.AFM get_url() (matplotlib.DummyAxis get_underline_thickness() (matmethod).axes. 626 620 get_useOffset() (matplotlib.Axis method).GridSpecBase method). get_x() method). 377 get_xaxis() (matplotlib.Axes method). get_x() (matplotlib. 537 get_width_from_char_name() (matplotlib.artist.afm.StandardPsFonts method).Patch method). 324 plotlib.OffsetFrom method).text.AFM method).mathtext).TruetypeFonts method).backend_bases.lines.Rectangle method).patches. 614 get_window_extent() (matplotlib. 602 method).Fonts method).afm.text. Axes method).Axes method).axes. 342 get_ygridlines() (matplotlib. 455 get_xy() (matplotlib.Axes method). 737 grid() (matplotlib. 454 get_xbound() (matplotlib. 330 getp() (in module matplotlib.Axes method).pyplot). 460 hatch() (matplotlib.Line2D method).axes.TruetypeFonts method).afm.axes.Axes method). 457 get_ylabel() (matplotlib.Axes method).Axes method).Polygon method).Axis method).axes.axes. 626 GlueSpec (class in matplotlib.mathtext.Node method).Axes method).axes.Axes method).axes.Char method).axes.Rectangle method).axes.Artist method). 737 grid() (in module matplotlib.backend_bases.axes.Axes method). 624 grow() (matplotlib.Axes method). 455 get_yaxis_text1_transform() (matplotlib.dviread.figure.lines.mathtext).axis. 457 get_ylim() (matplotlib.axes.Kern method).Axes method). 620 group() (matplotlib.Figure method).mlab). 455 get_xmajorticklabels() (matplotlib.mathtext. 454 get_xdata() (matplotlib.axes. 457 get_ymajorticklabels() (matplotlib. 377 get_xydata() (matplotlib.artist).Axis method).Axes method).pyplot).Path class method). 335 getpoints() (matplotlib.Axes method).Glue method). 455 get_xticklabels() (matplotlib.axis. 458 get_zorder() (matplotlib.artist.patches.axes.Axes method). 457 get_yticklabels() (matplotlib.YAArrow method).backend_bases).path. 633 get_xheight() (matplotlib.Axes method).gridspec). 634 get_xlabel() (matplotlib.Axes method).axes. 458 grid() (matplotlib. 631 GTK. 627 grow() (matplotlib.AFM method).patches. 456 get_ybound() (matplotlib. 457 get_yscale() (matplotlib. 837 gray() (in module matplotlib.Axes method).mathtext.patches. 254 Index 878 .artist. 626 get_xheight() (matplotlib.mathtext.cbook).gridspec).Accent method).mathtext.lines. 457 get_yticklines() (matplotlib.pyplot).axes.mathtext).Axes method). 857 H has_data() (matplotlib. 324 get_xheight() (matplotlib.Axes method). 627 grow() (matplotlib.Axes method).axes. 626 grab_mouse() (matplotlib.axes.mathtext). 648 GridSpec (class in matplotlib.Axes method). 623 grow() (matplotlib. 454 get_xheight() (matplotlib. 382 GetRealpathAndStat (class in matplotlib. 455 get_yaxis_text2_transform() (matplotlib.mathtext).Fonts method). 833 GraphicsContextBase (class in matplotlib.transforms.axes.Parser method).Artist method). 456 get_yaxis_transform() (matplotlib. 457 get_ydata() (matplotlib. 602 Glue (class in matplotlib.mathtext. 626 HCentered (class in matplotlib.Line2D method). 376 get_xy() (matplotlib.StandardPsFonts method). 853 height (matplotlib.lines. 330 have_units() (matplotlib.BboxBase attribute).axes. 455 get_xminorticklabels() (matplotlib. 626 grow() (matplotlib. 455 get_xticks() (matplotlib.FancyBboxPatch method).Line2D method).patches.Tfm attribute). 624 grow() (matplotlib.mathtext. 342 get_xgridlines() (matplotlib.1 get_xaxis_transform() (matplotlib.axes.mathtext.axes.Box method).patches. Release 1. 537 Hbox (class in matplotlib.axes.cbook).Axes method). 632 Grouper (class in matplotlib. 455 get_xticklines() (matplotlib.0. 546 ginput() (in module matplotlib.mlab). 537 griddata() (in module matplotlib.Axes method).Axes method). 370 get_y() (matplotlib.axes.axes.gridspec). 619 GridSpecBase (class in matplotlib. 619 GridSpecFromSubplotSpec (class in matplotlib. 455 get_xlim() (matplotlib.axes.Matplotlib. 455 get_xscale() (matplotlib.List method).mathtext.axes. 626 height (matplotlib. 457 get_yminorticklabels() (matplotlib. 342 get_xyz_where() (in module matplotlib. 546 grow() (matplotlib.mathtext.axes. 648 get_y() (matplotlib.mathtext.Axes method).Axes method).Rectangle method).FigureCanvasBase method). 457 get_yticks() (matplotlib. 662 have_units() (matplotlib. 378 get_yaxis() (matplotlib. 736 ginput() (matplotlib. ViewVCCachedServer 254 method). 460 imshow() (matplotlib.Normalize method).BboxBase method). 548 interval (matplotlib.PdfPages hold() (in module matplotlib.pyplot).InvertedPolarTrans identity() (matplotlib.1 imread() (in module matplotlib. 267 imageObject() (mat. 549 (mathttp_response() (mat.cbook.colors.pyplot).pyplot).pyplot).axes.axes.Path method).mathtext. 254 hpack() (matplotlib. 263 inverted() (matplotlib.Axes method). 582 method).backend_pdf.Axes method).PolarTransform IdentityTransform (class in matplotlib. 849 inverted() (matplotlib. 590 intervalx (matplotlib.Hlist method).BlendedGenericTransform method). 549 hlines() (matplotlib.Axes method). 839 inverted() (matplotlib.path.Axes method). 739 imshow() (in module matplotlib.artist. 266 IdleEvent (class in matplotlib.colors).Figure method).backend_bases. 746 method). 587 Hlist (class in matplotlib.transforms.Transform Index 879 .transforms.backend_pdf. 470 hist() (matplotlib.BboxBase atHrule (class in matplotlib.projections. 549 http_request() (mat.BboxBase athours() (in module matplotlib.figure. 833 method). 662 method). 648 inverted() (matplotlib. 850 hold() (matplotlib.polar.mathtext).Axes method). 663 home() (matplotlib.cbook.transforms). 463 in_cache_dir() (mathitlist() (matplotlib. 547 method). 582 plotlib. 742 in_axes() (matplotlib. 582 imsave() (in module matplotlib.cbook.ticker).FigureCanvasBase inverted() (matplotlib. 578 method).polar.mathtext.pyplot).ViewVCCachedServer inverse() (matplotlib.transforms. 662 HOME.inverted() (matplotlib.axes.colors.IdentityTransform plotlib.axes.TransformNode hsv_to_rgb() (in module matplotlib.cbook.Bbox method).Axes method). plotlib. 747 hexbin() (in module matplotlib. Release 1.NavigationToolbar2intersects_bbox() (matplotlib.cbook).Path method). 257 method).transforms. 276 264 inverted() (matplotlib. 603 interpolated() (matplotlib. 466 IndexDateFormatter (class in matplotlib.Affine2DBase Idle (class in matplotlib.Affine2D static method). 627 IndexLocator (class in matplotlib.ViewVCCachedServer method). 745 method). 627 tribute).PdfFile method).colors).Path method).NoNorm method).backend_bases.projections.backend_bases).axes.pyplot). 747 hex2color() (in module matplotlib.Axes method).PolarAxes. 253 http_error_304() (matinverse() (matplotlib.transforms. 746 invalidate() (matplotlib. 847 HourLocator (class in matplotlib.Ship method). 467 hist() (in module matplotlib. 633 infodict() (matplotlib.dates).Matplotlib.PolarAxes.TimerBase athot() (in module matplotlib.inverse() (matplotlib.colors.CompositeGenericTransform ignore() (matplotlib.Axes method).LogNorm method). 748 hexbin() (matplotlib.axes. 592 tribute).mathtext).path.axes.transforms.dates).cbook. 471 I invert_yaxis() (matplotlib. 330 plotlib. 746 tribute). 582 method).mlab).colors.0. 264 method). 254 hsv() (in module matplotlib.mlab).transforms. 649 hold() (matplotlib. 841 intersects_path() (matplotlib.axes.transforms.ViewVCCachedServer hlines() (in module matplotlib. 549 invert_xaxis() (matplotlib.pyplot).pyplot).transforms. 627 intervaly (matplotlib.BoundaryNorm plotlib. 262 idle_event() (matplotlib.Stack method).transforms.backends. 471 identity() (in module matplotlib.backends.pyplot).inverse_transformed() plotlib. 220 home() (matplotlib. method).dates).Artist method). 467 inside_poly() (in module matplotlib.path.transforms.backend_bases. 581 inverse() (matplotlib. 275 method). 825 hlist_out() (matplotlib. FigureCanvasBase method).units.FigureCanvasBase method).FigureManagerBase method).spines.Parser method). 839 kwdoc() (in module matplotlib. 837 key_press_event() (matplotlib. 552 is_closed_polygon() (in module matplotlib. 627 key_press() (matplotlib.mlab).FigureCanvasBase method). 751 Index .mathtext. 552 is_math_text() (matplotlib.mlab). 550 is_numlike() (in module matplotlib.converter method).backend_bases.colors).pyplot).BboxBase method).ticker.Line2D method).Axis method).ConversionInterface static method). 833 Legend (class in matplotlib.cbook).mathtext). 833 key_release_event() (matplotlib.mlab). 639 leave_notify_event() (matplotlib. 552 isvector() (in module matplotlib.cbook). 547 joined() (matplotlib.SubplotBase method). 663 iter_ticks() (matplotlib.cbook.axes.mlab.artist. 624 is_slanted() (matplotlib. 389 is_missing() (matplotlib.pyplot). 627 kern() (matplotlib.SubplotBase method).axes.cbook).font_manager). 819 is_gray() (matplotlib.Artist method). 532 is_first_row() (matplotlib. 751 is_alias() (matplotlib.pyplot). 259 ioff() (in module matplotlib. 537 iterable() (in module matplotlib. 751 ion() (in module matplotlib.Axes method). 649 label_minor() (matplotlib. 336 legend() (in module matplotlib. 632 is_scalar() (in module matplotlib. 649 iter_segments() (matplotlib. 552 isvector() (in module matplotlib. 857 K Kern (class in matplotlib. 833 KeyEvent (class in matplotlib.Artist method). 471 isinteractive() (in module matplotlib.mlab). 532 is_math_text() (in module matplotlib. 649 l2norm() (in module matplotlib. 254 is_writable_file_like() (in module matplotlib.backend_bases.cbook).mathtext.cbook.artist.backend_bases. 830 is_opentype_cff_font() (in module matplotlib. 751 join() (matplotlib. 649 is_color_like() (in module matplotlib. 334 is_closed_polygon() (in module matplotlib.Matplotlib. 579 is_last_col() (matplotlib.legend). 330 is_first_col() (matplotlib.pyplot). 616 is_overunder() (matplotlib.Spine method).FIFOBuffer method).axes.text.SubplotBase method).backend_bases.cbook.axes.mathtext. 649 issubclass_safe() (in module matplotlib. 532 last() (matplotlib. 751 ispower2() (in module matplotlib.1 method).cbook).colors.LogFormatter method). 632 is_string_like() (in module matplotlib.Grouper method). 547 JPG. 532 is_last_row() (matplotlib.ArtistInspector method). 751 ishold() (matplotlib.transforms.axis.SubplotBase method). 552 is_scalar_or_string() (in module matplotlib. 552 is_numlike() (matplotlib. 335 L l1norm() (in module matplotlib.cbook).mlab). 552 is_slanted() (matplotlib.artist). 825 label_outer() (matplotlib.Char method).mathtext.cbook).pyplot). 552 ishold() (in module matplotlib. Release 1. 582 is_dashed() (matplotlib. 532 is_frame_like() (matplotlib.Path method). 552 is_sequence_of_strings() (in module matplotlib.backend_bases).path.Parser method). 342 is_dropsub() (matplotlib.Colormap method).axes. 552 is_transform_set() (matplotlib.Parser method). 552 J jet() (in module matplotlib.lines.SubplotBase method).Grouper method).cbook).mathtext.cbook).Text static method). 330 880 is_unit() (matplotlib.cbook).axes.0.cbook).Hlist method).pyplot).artist. 632 is_figure_set() (matplotlib. Release 1. 327 matplotlib. 629 matplotlib (module). 630 MathtextBackendPdf (class in matplotlib.ticker). 840 Locator (class in matplotlib.backends.pyplot). 651 Index M mainloop() (matplotlib.backend_bases.pyplot).cbook).ticker).colors). 826 LinearScale (class in matplotlib. 537 limit_range_for_scale() (matplotlib. 272 logspace() (in module matplotlib.backend_bases). 581 LogScale (class in matplotlib. 824 LogFormatterExponent (class in matplotlib.axes. 565 List (class in matplotlib. 272 LinearSegmentedColormap (class in matplotlib.axes. 630 MathtextBackendPs (class in matplotlib.ShowBase method).mathtext).axes. 629 MathtextBackendBbox (class in matplotlib.backends.figure. 395 matplotlib.mlab).mathtext). 651 longest_ones() (in module matplotlib. 826 loglog() (in module matplotlib.axes.pyplot). 474 LogNorm (class in matplotlib.Axes method).Spine class method).mathtext).colors).ticker).mathtext).afm (module).ticker).axes (module). 323 matplotlib. 552 less_simple_linear_interpolation() (in module matplotlib.Axes method).backend_qt4agg (module).ScaleBase method).colors). 581 listFiles() (in module matplotlib. 846 make_axes() (in module matplotlib.Axes method). 574 make_compound_path() (matplotlib. 475 markerObject() (matplotlib.Axes method).collections).mathtext). 649 levypdf() (in module matplotlib. 663 makeMappingArray() (in module matplotlib.axis (module).backend_pdf. 627 ListedColormap (class in matplotlib. 663 make_compound_path_from_polys() (matplotlib.mathtext).mlab).mathtext).scale).mlab).backend_pdf (module). 755 margins() (matplotlib. 651 longest_contiguous_ones() (in module matplotlib. 603 less_simple_linear_interpolation() (in module matplotlib.Path class method).mlab). 825 LogFormatterMathtext (class in matplotlib.Parser method).scale. 825 LogLocator (class in matplotlib.Axis method). 630 MathtextBackendSvg (class in matplotlib. 473 log2() (in module matplotlib.mlab). 319 matplotlib.path.ticker). 649 liaupunov() (in module matplotlib. 754 loglog() (matplotlib.mathtext).mathtext). 629 MathtextBackendAggRender (class in matplotlib. 630 MathtextBackendBitmapRender (class in matplotlib.mathtext). 627 MathTextWarning.0.backend_bases (module).spines. 650 LocationEvent (class in matplotlib.mathtext).lines). 630 MathtextBackendPath (class in matplotlib.scale. 754 locator_params() (matplotlib.scale). 273 limit_range_for_scale() (matplotlib.backends. 825 locator_params() (in module matplotlib. 579 limit_range_for_scale() (matplotlib. 629 MathtextBackendBitmap() (in module matplotlib. 630 MathTextParser (class in matplotlib.colorbar).artist (module). 630 MathtextBackendCairo (class in matplotlib. 629 MathtextBackendAgg() (in module matplotlib.1 legend() (matplotlib. 632 MathtextBackend (class in matplotlib.mlab).colors).LogScale method).mlab). 849 math() (matplotlib. 339 linear_spine() (matplotlib.ticker).mathtext).mathtext. 649 LightSource (class in matplotlib. 535 matplotlib. 552 load() (in module matplotlib. 273 Line2D (class in matplotlib. 819 LinearLocator (class in matplotlib.mlab). 580 LineCollection (class in matplotlib.path.PdfFile method).mathtext).Path class method).cbook). 582 margins() (in module matplotlib. 847 881 .Matplotlib.axis. 651 LogFormatter (class in matplotlib. 849 matplotlib.colors). 471 legend() (matplotlib.Figure method). 831 matplotlib. backend_bases. 272 matplotlib.FigureCanvasBase method).backend_wxagg).backends. 821 matplotlib.mathtext). 623 matplotlib. 552 MaxNLocator (class in matplotlib. 476 max (matplotlib.dates).text (module). 255 maxdict (class in matplotlib. 262 matshow() (in module matplotlib.patches (module). 545 matplotlib.Affine2DBase static method).Axes method).transforms. 559 matplotlib.legend (module).gridspec.backend_qt4agg).backend_pdf). 637 matplotlib. 757 minorticks_off() (matplotlib.dviread (module). 590 minutes() (in module matplotlib.Bbox method).cbook). 854 matplotlib. 257 mutatedy() (matplotlib.mlab (module). 590 motion_notify_event() (matplotlib.1 matplotlib. 829 matrix_from_values() (matplotlib.backend_bases. 611 matplotlib.Axes method).lines (module).Bbox method).FigureCanvasBase method).mlab).colors (module). 547 min (matplotlib. 849 NavigationToolbar2 (class in matplotlib.axes.mathtext).backend_bases. 616 matplotlib.NavigationToolbar2 method).BboxBase attribute).scale (module).dates). 845 new_subplotspec() (matplotlib. 592 mkdirs() (in module matplotlib. 631 new_figure_manager() (in module matplotlib.backend_wxagg (module). 255 minorticks_off() (in module matplotlib.transforms. 661 matplotlib.type1font (module). 257 mx2num() (in module matplotlib. Release 1.BboxBase attribute).Axes method). 833 mouse_move() (matplotlib. 477 minorticks_on() (in module matplotlib.transforms. 336 matplotlib. 840 NavigationToolbar2QTAgg (class in matplotlib.projections.backends. 851 matplotlib.backend_qt4agg).cbook).transforms (module).axes. 477 MinuteLocator (class in matplotlib. 620 882 Index . 756 matshow() (matplotlib.gridspec (module).Bbox method).transforms.GridSpecBase method).fontconfig_pattern (module). 841 MouseEvent (class in matplotlib.colorbar (module).backends.RendererBase method). 826 MemoryMonitor (class in matplotlib. 557 matplotlib. 848 NavigationToolbar2WxAgg (class in matplotlib.pyplot). 848 new_gc() (matplotlib.mathtext (module).FigureCanvasBase method). 651 mpl_connect() (matplotlib. 851 new_figure_manager() (in module matplotlib.dates (module). 631 NegFilll (class in matplotlib. 339 matplotlib.backend_bases).spines (module). 817 matplotlib.projections (module). 833 mpl_disconnect() (matplotlib.transforms.backends. 275 matplotlib.ticker). 826 mutated() (matplotlib.backend_pdf).cm (module).dates). 834 MPLCONFIGDIR.backend_wxagg). 274 matplotlib. 631 NegFill (class in matplotlib.path (module). 619 matplotlib.cbook). 587 N Name (class in matplotlib.polar (module).backends.backends.pyplot (module).backend_bases. 220 MultipleLocator (class in matplotlib. 577 matplotlib.Matplotlib.nxutils (module).cbook (module). 848 matplotlib.font_manager (module).axes. 667 matplotlib. 815 matplotlib. 757 minorticks_on() (matplotlib.ticker).0.pyplot). 552 MonthLocator (class in matplotlib.dates).pyplot). 251 matplotlib. 593 matplotlib.mathtext). 585 matplotlib.figure (module).ticker (module). 848 new_figure_manager() (in module matplotlib. 840 movavg() (in module matplotlib. 347 matplotlib.backend_bases). 383 matplotlib.units (module).backends.backend_bases. 848 NegFil (class in matplotlib. 257 mutatedx() (matplotlib. 573 matplotlib.transforms.collections (module). 854 onHilite() (matplotlib.patches). 757 method). 841 NullLocator (class in matplotlib. 552 parts (matplotlib.PathCollection (class in matplotlib.axes.backend_qt4agg.State (class in matplotlib. 553 plotlib.pcolormesh() (matplotlib.colors).NavigationToolbar2 NullFormatter (class in matplotlib.Locator method). 386 Parser.backend_pdf).PCA (class in matplotlib.FigureCanvasBase plotlib.mathtext). 834 over() (in module matplotlib.transforms).path).backend_bases.VertexSelector method). 379 OSXFontDirectory() (in module mat. 661 path_in_path() (in module matplotlib.1 OSXInstalledFonts() (in module matnew_timer() (matplotlib.mathtext). 631 method). 566 PATH.cbook).BboxBase method). 651 paintEvent() (matNormalize (class in matplotlib. 480 PDF.transforms.pyplot). 845 Operator (class in mat. 587 parse() (matplotlib.mlab).BboxBase attribute).mathtext.axes. 615 Index 883 . 583 method).dates).ticker).pcolor() (matplotlib. 825 num2date() (in module matplotlib. 759 method). 270 p0 (matplotlib.type1font. 583 overlaps() (matplotlib.backends.MathTextParser numvertices (matplotlib. 849 plotlib.Type1Font attribute).0. 845 orientation (matplotlib.mlab). 582 plotlib. method). 324 Parser (class in matplotlib.Matplotlib.transforms. 374 plotlib. 847 normpdf() (in module matplotlib.Axis method).RendererBase pcolor() (in module matplotlib. 587 method).PdfFile (class in matplotlib.backends.collections).Path (class in matplotlib. 537 Null (class in matplotlib.patches. 330 plotlib.mathtext.RegularPolygon at.mathtext.backend_bases. 632 P NoNorm (class in matplotlib. 631 onetrue() (in module matplotlib.mlab). 834 665 open_group() (matpath_length() (in module matplotlib.mathtext).backends.backend_bases. 547 pan() (matplotlib.ticker). 632 O parse_afm() (in module matplotlib.mlab). 55 347 onRemove() (mat. 757 no_norm (in module matplotlib.axis.font_manager).ticker.pyplot).Axes method). 631 OffsetFrom (class in matplotlib.FontconfigPatternParser num2epoch() (in module matplotlib.backend_bases.dates.lines. 255 non_math() (matplotlib. 826 pan() (matplotlib. 371 method).artist.colors). 588 255 norm_flat() (in module matplotlib.backend_bases. 255 nonsingular() (matplotlib. 255 padded() (matplotlib. Release 1.Axes method). 479 plotlib.RegularPolygon at.cbook). 651 method). 834 onpick() (matplotlib.afm). 823 method).backend_bases.FigureCanvasQTAgg normalize (in module matplotlib.FigureCanvasBase Patch (class in matplotlib.patches). 640 pchanged() (matplotlib.text).path).dates). 665 plotlib.DateLocator p1 (matplotlib.colors).transforms. method).BboxBase Node (class in matplotlib.RendererBase path_length() (in module matplotlib.FigureCanvasBase path_intersects_path() (in module matplotlib. 857 (matplotlib. PatchCollection (class in matplotlib. 54. 651 pan() (matplotlib.collections).transforms. 477 pcolorfast() (matplotlib.backend_pdf).path). 615 method). 567 PathPatch (class in matplotlib.font_manager).parse() method).fontconfig_pattern.RendererBase pcolormesh() (in module matplotlib. 379 parse() (matplotlib.Parser method).colors).pyplot). 857 tribute). 616 numpy. 581 nonsingular() (in module matplotlib.BboxBase attribute).axes. 849 option_image_nocomposite() (mat.cbook).Axes method).patches. 628 tribute). 845 option_scale_image() (mat. 52.backend_bases.Artist method).Parser method). 275 PolarAxes.polar).Artist method).polar).backend_qt4agg.backend_bases.Axes method).Axes method).cbook).backends. 848 print_pdf() (matplotlib. 275 PolarAxes. 567 Polygon (class in matplotlib.FigureCanvasBase method). 850 pdfRepr() (in module matplotlib.artist.FigureCanvasBase method).artist. 835 pick_event() (matplotlib. 330 pick() (matplotlib.FigureCanvasBase method).RendererBase method).MemoryMonitor method).ScalarFormatter method).pyplot).backends.patches). 553 pprint_getters() (matplotlib.projections.backend_bases.FigureCanvasQTAgg method). 483 plot() (matplotlib.path).1 PdfPages (class in matplotlib. 845 polar() (in module matplotlib.Artist method). 486 plotfile() (in module matplotlib. 334 pprint_setters_rest() (matplotlib.ArtistInspector method).backend_bases. 482 pick() (matplotlib.mlab).font_manager). 334 pprint_val() (matplotlib. 841 press_zoom() (matplotlib. 652 prepca() (in module matplotlib.0.NavigationToolbar2 method).mlab).NavigationToolbar2 method). 275 PolarAxes.InvertedPolarTransform (class in matplotlib.cbook.projections.RadialLocator (class in matplotlib.path).projections. 835 print_figure() (matplotlib. 616 pie() (in module matplotlib.projections.PolarTransform (class in matplotlib.pyplot).projections.backend_bases. 768 PNG.backend_pdf).pyplot).mlab). 482 pieces() (in module matplotlib.backends. 651 poly_between() (in module matplotlib.axes.pyplot). 825 pprint_val() (matplotlib. 767 plotting() (in module matplotlib. 835 Index 884 .ticker.polar).backend_bases. 665 points_to_pixels() (matplotlib. 616 pickle_load() (in module matplotlib.Axes method).projections.backend_bases.FigureCanvasBase method). 851 pick() (matplotlib.pyplot).LogFormatter method). 761 pie() (matplotlib.FigureCanvasBase method).backend_bases.backend_bases). 652 press() (matplotlib. 842 pickle_dump() (in module matplotlib.polar).ArtistInspector method).mlab).ThetaFormatter (class in matplotlib. 276 PolarAxes.cbook). 375 pop_state() (matplotlib.pyplot). 835 print_figure() (matplotlib.pyplot). 824 prctile() (in module matplotlib. Release 1. 553 print_emf() (matplotlib.ticker. 277 poly_below() (in module matplotlib.collections).artist.Matplotlib.ArtistInspector method).FigureCanvasBase method). 330 PickEvent (class in matplotlib.FigureCanvasBase method).backends. 847 print_figure() (matplotlib.NavigationToolbar2 method).mathtext.artist.polar). 765 plot_date() (matplotlib. 857 point_in_path() (in module matplotlib. 334 pprint_setters() (matplotlib. 835 pickable() (matplotlib. 276 PolarAxes.mlab).Axes method). 841 print_bmp() (matplotlib.polar). 762 plot() (matplotlib.artist.axes.backend_wxagg. 841 press_pan() (matplotlib. 652 prctile_rank() (in module matplotlib.backend_pdf).backend_bases. 651 PolyCollection (class in matplotlib.FigureCanvasWxAgg method). 547 plot_date() (in module matplotlib.backend_bases.backend_bases. 835 print_eps() (matplotlib.Parser method). 632 popall() (in module matplotlib. 769 PolarAxes (class in matplotlib.font_manager).PolarAffine (class in matplotlib. 665 point_in_path_collection() (in module matplotlib.cbook).backend_bases. 835 print_cycles() (in module matplotlib. 553 pink() (in module matplotlib. 762 plot() (in module matplotlib.axes.axes. 654 psd() (in module matplotlib. 835 quiverkey() (in module matplotlib. 835 print_rgb() (matplotlib.Locator method).dviread).backend_bases. 641 (matprojection_factory() (in module mat. 857 plotlib.patches). 655 psd() (in module matplotlib. pyfltk. 835 radius (matplotlib.collections). 775 print_raw() (matplotlib. 857 rc() (in module matplotlib). 589 pytz. 379 print_svgz() (matplotlib.lines.lines. 835 quiver() (in module matplotlib.cbook).FIFOBuffer method).pyplot).FigureCanvasBase QuadMesh (class in matplotlib. 358 print_svg() (matplotlib. 568 method). 842 push_state() (matplotlib.ticker.1 quad2cubic() (in module matplotlib.FigureCanvasBase raise_if_exceeds() (matplotlib.artist.patches.pyplot). 376 method). 825 prism() (in module matplotlib. 654 rec_append_fields() (in module matplotlib.artist.ProjectionRegistry Qt. 490 method).cbook.backend_bases.mathtext.mlab).pyplot).ViewVCCachedServer plotlib.Circle attribute). 857 refresh() (matplotlib.axes.axes. 275 method).read_cache() plotlib.projections.FigureCanvasBase quiverkey() (matplotlib.patches. push() (matplotlib. 653 274 prop (matplotlib. 334 rec_groupby() (in module matplotlib.cbook.Type1Font attribute). 548 342 push_current() (matplotlib.backend_bases.ticker. 655 psd() (matplotlib.pyplot).backends. 546 process_selected() (matplotlib. 770 process() (matplotlib.projections). 825 Q register() (matplotlib.Locator method). Release 1.backend_bases.lines.FigureCanvasBase quiver() (matplotlib.mlab).cbook.Axes method).backend_bases.FigureCanvasBase R method). recursive_remove() (in module matplotlib. 770 rec_summarize() (in module matplotlib.mlab).CallbackRegistry raster graphics.Parser method). 772 print_ps() (matplotlib.mlab). 776 rcdefaults() (in module matplotlib).axes.backend_pdf).pyplot). 857 refresh() (matplotlib.mlab.ArtistInspector rec_drop_fields() (in module matplotlib.Artist method). 777 project() (matplotlib.Axes method).cbook). 835 method). 857 method).VertexSelector rc() (in module matplotlib.mlab). 857 rec_join() (in module matplotlib.FigureCanvasBase radius (matplotlib. 342 PsfontsMap (class in matplotlib. rec2csv() (in module matplotlib. 320 method).mlab). 652 rec_keep_fields() (in module matplotlib. 857 494 pygtk.axes. 654 PS. 654 method).NavigationToolbar2 recs_join() (in module matplotlib. 653 print_png() (matplotlib. 639 register() (matplotlib. 850 python. 330 654 properties() (matplotlib.Matplotlib.mlab).backend_bases. 835 tribute).mlab). 655 Rectangle (class in matplotlib. 852 recache_always() (matplotlib.type1font.Stack method).mlab).mlab.projections). properties() (matplotlib. 553 632 redraw_in_frame() (matplotlib. 493 method). 549 ProjectionRegistry (class in matplotlib.0. 321 method).backend_bases.Axes method). 553 Index 885 .Axes method). 347 rcdefaults() (in module matplotlib.PCA method). 488 recache() (matplotlib.AutoDateLocator PYTHONPATH. 854 rec2txt() (in module matplotlib. 857 quad2cubic() (in module matplotlib.mlab).RegularPolygon atmethod). 857 Reference (class in matpyqt.Line2D method).Line2D method). 233 method).mlab).pyplot). 275 Qt4.dates. MathtextBackendCairo plotlib. 569 method).mathtext.MathtextBackendPath plotlib.Axes method). 630 method). 630 method). 830 (matRegularPolyCollection (class in mat. 624 render_rect_filled() (matrender() (matplotlib.FigureCanvasBase method).scale).Node method).backend_bases. 626 843 render_glyph() (matreport() (matplotlib.Box method). 274 method).NavigationToolbar2 method).mathtext. 623 plotlib.MathtextBackendSvg method).report_memory() (in module matplotlib. 630 render() (matplotlib. 378 render_glyph() (matrelativedelta (class in matplotlib. 549 render_rect_filled() (matrender() (matplotlib.MathtextBackendPdf release() (matplotlib. 842 (matrelease_mouse() (mat.artist.backend_bases).backend_bases.mathtext.mathtext.mathtext.Accent method). 631 method).mathtext.MathtextBackendCairo register_scale() (in module matplotlib.MathtextBackend method).Char method).cbook. 842 plotlib. 630 330 (matremove_callback() (mat. 633 method).MemoryMonitor plotlib.MathtextBackendPs plotlib. 630 Registry (class in matplotlib.cm). 629 register_axis() (matplotlib. 548 plotlib.mathtext.mathtext. 631 render_glyph() (matplotlib.mathtext.axes.mathtext. render_glyph() (mat819 plotlib.MathtextBackendAggRender relim() (matplotlib.MathtextBackend plotlib.MathtextBackendPs render() (matplotlib.Artist method). 630 RegularPolygon (class in matplotlib. 847 render_glyph() (matregister_cmap() (in module matplotlib.mathtext. 631 plotlib. 629 render_glyph() (mat. 553 (matplotlib.spines. 591 plotlib.MathtextBackendPath plotlib.MathtextBackendSvg plotlib. 626 plotlib.mathtext.Artist method).MathtextBackendBbox remove_callback() (matplotlib.patches).Stack method).mathtext. 630 847 (matremove_stale_files() (mat.cbook.artist. 836 (matrelease_pan() (mat.mathtext. 330 render_rect_filled() (matremove() (matplotlib.backend_bases.MathtextBackendPdf render() (matplotlib. method).backend_bases.dates). 630 method).mathtext.0.backend_bases.TimerBase method).MathtextBackendAggRenderreserveObject() 886 Index . 624 method). RendererBase (class in matplotlib. 842 (matplotlib.cbook).mathtext.1 method). 629 remove() (matplotlib.mathtext.mathtext.render_glyph() plotlib.mathtext.mathtext.render_rect_filled() method).backend_bases).render_rect_filled() plotlib.ViewVCCachedServer method). 494 method).mathtext.Rule method). Release 1.render_glyph() plotlib.NavigationToolbar2 method).Spine method).cbook.Matplotlib.mathtext.units).render_rect_filled() plotlib. 629 method).mathtext.NavigationToolbar2 render_rect_filled() (matmethod). 547 method).MathtextBackendBbox register_backend() (in module matmethod).Fonts release_zoom() (mat. 558 plotlib.Fonts method). 630 render_filled_rect() (matrender_rect_filled() (matplotlib.render_glyph() plotlib.collections). method). 630 plotlib. mlab).mlab).figure.FontManager rotate() (matplotlib.font_manager.Axis method). 656 656 semilogx() (in module matplotlib.PdfPages method).mlab).cbook). 836 safe_isnan() (in module matplotlib. 604 resize() (matplotlib. 588 score_weight() (matRule (class in matplotlib. scale() (matplotlib.backend_bases. 612 RRuleLocator (class in matplotlib.1 save_figure() (matplotlib.FigureCanvasBase ScalarMappable (class in matplotlib. 591 safe_masked_invalid() (in module mat.dates). 347 safezip() (in module matplotlib.Normalize method). 273 method). 558 ScaledTranslation (class in matplotlib.PdfFile plotlib.FontManager rrule (class in matplotlib. score_variant() (mat255 plotlib.pyplot). 632 plotlib. 656 method). 777 Scheduler (class in matplotlib.FontManager run() (matplotlib. 824 plotlib. 583 scatter() (matplotlib.colors).colors).font_manager. 263 (matrotate_deg() (matplotlib. 537 resize() (matplotlib. 547 sci() (in module matplotlib. 582 revcmap() (in module matplotlib. 850 method).backend_pdf.transforms.pyplot).transforms.scale). 606 ScalarFormatter (class in matplotlib. 549 scroll_event() (matS plotlib.axis. 849 method).Figure method).cbook.lines). 837 resize_event() (mat.GraphicsContextBase ScaleBase (class in matplotlib. 553 269 rgb2hex() (in module matplotlib.backends.figure.Affine2D method).ticker).mlab).axes.dates). 494 savefig() (in module matplotlib. 836 savefig() (matplotlib. 612 263 rotate_around() (matplotlib. 553 segments_intersect() (in module matplotlib.backends.seconds() (in module matplotlib.transforms.FontManager 263 method). 838 scaled() (matplotlib.cm).transforms. Release 1.cbook.backend_bases.transforms.backend_bases.Matplotlib.backend_bases.Idle method).Affine2D method). 612 run() (matplotlib. 547 RingBuffer (class in matplotlib. 781 rk4() (in module matplotlib.FigureCanvasBase safe_isinf() (in module matplotlib.Figure method).Axes method). 655 score_family() (matrms_flat() (in module matplotlib. 553 segment_hits() (in module matplotlib.mlab).0.font_manager. 263 method).cbook). 612 method).backend_bases). 263 846 scale_factory() (in module matplotlib. 494 rgrids() (in module matplotlib.scale).Axes method).FontManager method). method).mathtext).backend_bases. reverse_dict() (in module matplotlib.dates).FigureCanvasBase savefig() (matplotlib.font_manager. 274 restore() (matplotlib.transforms.cbook). score_style() plotlib.FontManager method).pyplot).backend_pdf. 836 ResizeEvent (class in matplotlib.Affine2D score_size() (matplotlib. 842 reset_position() (matplotlib. 656 plotlib.sca() (matplotlib.BboxBase method).transforms). 612 rotated() (matplotlib. 547 method).Affine2D score_stretch() plotlib. 583 scatter() (in module matplotlib.dates). 591 method).cbook). 781 Index 887 .colors.cm).font_manager.pyplot). 778 method). 592 plotlib.FigureManagerBase sca() (in module matplotlib.font_manager. 612 rotate_deg_around() (mat(matplotlib. 656 SecondLocator (class in matplotlib.axes.backend_bases.cbook).pyplot). save() (in module matplotlib. 557 method). 777 reset_ticks() (matplotlib.Affine2D method).mlab).Timeout method).pyplot). 778 rgb_to_hsv() (in module matplotlib.NavigationToolbar2 method). 563 (matplotlib.axes. 838 367 set_children() (matset_aspect() (matplotlib.legend. 823 method).Collection set_canvas_size() (matmethod). 331 set_axis_on() (matplotlib. 838 set_alpha() (matplotlib.lines.Axes method).pyplot).Axes method).patches.axes. 370 method).TickHelper method).Axes method).ticker. method).FancyBboxPatch method).axes.ConnectionPatch method).Spine method). 331 set_backgroundcolor() (matplotlib.Axes method).Patch method).spines.axes. 563 (matplotlib.Axes method). 339 method).Line2D method).TransformWrapper set_axis() (matplotlib.Artist method). 501 set_agg_filter() (matplotlib.FancyArrowPatch method).collections.1 set_axes() (matplotlib.Axes method).mathtext.Text set_alpha() (matplotlib.cm.axes.patches. 342 501 set_aa() (matplotlib. semilogy() (matplotlib.backend_bases. 389 method).axes.figure.0.Artist method).ticker.MathtextBackend 373 method).collections.axes.lines.GraphicsContextBase set_boxstyle() (matplotlib.transforms.axes. 331 set_clip_on() (matplotlib. 497 set_axes() (matplotlib. 331 (matplotlib.lines.patches.axes.Collection set_c() (matplotlib.Patch method).patches. 782 set_axes_locator() (matplotlib. 373 set_adjustable() (matplotlib.Artist method). 819 set_bounds() (matplotlib. 606 method).lines.Rectangle set_animated() (matplotlib. 574 set_bounds() (matplotlib.artist.patches. set_clim() (matplotlib. set_aa() (matplotlib.Axes method).patches.axes. 626 342 (matset_antialiased() (matplotlib. 331 set_bounds() method). set_clip_box() (matplotlib.dates.ScalarMappable method).colors. 389 method).text. 501 set_alpha() (matplotlib.Line2D method).MathtextBackendAggRender set_array() (matplotlib. 343 set_canvas() (matplotlib. 501 set_axisbelow() (matplotlib.transforms.GraphicsContextBase plotlib.artist. 589 set() (matplotlib.Artist method).Axes method). 579 set_bbox() (matplotlib. 370 set_anchor() (matplotlib.cm.Matplotlib. set_canvas_size() plotlib.Collection set_bad() (matplotlib.Patch method). method).collections.artist.Colormap method). 253 500 set_autoscalex_on() (matplotlib. 331 501 888 Index . method). 563 plotlib.patches.axes.TransformNode set_autoscale_on() (matplotlib.backend_bases. set_bounds() (matplotlib. 629 557 (matset_arrowstyle() (mat. 499 set_axis_off() (matplotlib.Fonts set_antialiased() (matplotlib.Axes method). 360 823 set_antialiased() (matplotlib. 498 501 set() (matplotlib.axes. 257 set() (matplotlib.Figure method).mathtext. 264 set_axis() method).Line2D method).Artist method).Artist method). 373 method).Axes method).ColorbarBase set_bbox_to_anchor() method).artist.backend_bases.Axes method).text. 838 set_antialiased() (matplotlib.FancyBboxPatch set_alpha() (matplotlib.Affine2D method). 557 500 set_autoscaley_on() (matplotlib.artist.artist.GraphicsContextBase method). 500 (matplotlib.Legend set_alpha() (matplotlib.Line2D method). 629 set_antialiaseds() (matplotlib.colorbar. 378 set_annotation_clip() (matplotlib.Axes method).mathtext. set_canvas_size() method).Text method).axes.transforms.Bbox method).Axes method). Release 1.TickHelper method).artist.patches.set_capstyle() plotlib.transforms. 260 set_axis_bgcolor() (matplotlib. 343 semilogy() (in module matplotlib. 331 semilogx() (matplotlib.Artist method).AutoDateLocator set() (matplotlib. 500 plotlib.ScalarMappable method). figure. 823 method).Line2D method). 393 set_dashpad() (matplotlib.YAxis method).Figure method).cm.backend_bases. 393 set_clip_path() (matplotlib.lines. 537 set_color() (matplotlib.axis.FancyArrowPatch method).GraphicsContextBase 343 method).collections.pyplot).patches.Collection set_data_interval() plotlib. 537 plotlib.TickHelper set_cmap() (matplotlib. 274 501 (matset_dash_capstyle() (matplotlib.GraphicsContextBase set_data_interval() (matplotlib.ScaleBase method).Spine method). 542 set_colorbar() (matplotlib.scale.YAxis 501 method).Line2D method).ticker.ScalarMappable set_default_locators_and_formatters() (matmethod).XAxis set_color() (matplotlib.Figure method).Line2D method). Release 1.lines. 558 (matset_color() (matplotlib.Collection method).Patch method). 331 set_default_locators_and_formatters() plotlib. 537 method). 613 set_dash_joinstyle() (matplotlib.GraphicsContextBase set_data() (matplotlib. 533 set_color() (matplotlib.TextWithDash set_clip_path() (matplotlib. 393 set_drawstyle() (matplotlib. 842 plotlib.artist.Axis method). set_default_locators_and_formatters() plotlib.backend_bases.axis. 373 set_edgecolor() (matplotlib.axis.patches.axes).text.TextWithDash set_dpi_cor() (matplotlib. 784 (matplotlib.axis. method).ticker.Polygon method).Axes method). 823 set_color() (matplotlib.LogScale method). 343 set_dashlength() (matplotlib.patches. 541 set_color_cycle() (matplotlib.text. 373 method).patches. 393 set_clip_path() (matplotlib.spines.collections. 367 method).text.TextWithDash set_clip_path() (mat. 563 method).scale.Axis method).backend_bases.0. 838 541 set_closed() (matplotlib. 558 plotlib.ScalarMappable set_data_interval() method). 838 set_clip_rectangle() (mat.lines. 343 set_default_intervals() (matplotlib.figure. 343 method).collections.Text method).text.Tick method).artist.axis.collections.LinearScale method). 272 set_connectionstyle() (mat(matplotlib.lines. 389 method).axes.Matplotlib. 273 367 (matset_contains() (matplotlib.Axes method).Collection set_ec() (matplotlib.font_manager. 343 method). 839 set_dashes() (matplotlib.set_dashrotation() method).Patch method).1 method).axis. 819 set_default_intervals() (matplotlib.text. 606 method). 563 set_dashes() (matplotlib. 274 set_cursor() (matplotlib.scale. set_dashes() (matplotlib.FontManager method). set_default_intervals() (matplotlib. Index 889 .axis.cm. 331 set_dashpush() (matplotlib.NavigationToolbar2 set_default_locators_and_formatters() (matmethod).lines.Line2D method).Artist method). method).axis.Patch method).Axis set_color() (matplotlib.Line2D set_dpi() (matplotlib. 376 542 set_cmap() (in module matplotlib.patches.FancyArrowPatch method). 563 method).TextWithDash set_edgecolor() (matplotlib.SymmetricalLogScale set_cursor_props() (matplotlib.XAxis method).Line2D set_default_weight() plotlib.patches.TickHelper.backend_bases. set_data_interval() (matplotlib. 394 plotlib.scale.TextWithDash set_edgecolor() (matplotlib. 606 method). 343 set_dashdirection() (matplotlib. 540 (matplotlib.Artist method). 566 plotlib.axes.text.lines.DummyAxis method).LineCollection set_default_color_cycle() (in module matmethod).set_data_interval() (matplotlib. Index . 614 set_fill() (matplotlib.text.axis.Patch method).backend_bases.Line2D method). 540 set_label2() (matplotlib.Annotation method).GraphicsContextBase method).figure.Collection method). 842 set_horizontalalignment() (matplotlib. 839 set_label() (matplotlib. 540 set_label_coords() (matplotlib.artist. 378 set_height_ratios() (matplotlib.Tick method). 390 set_foreground() (matplotlib. 390 set_linestyle() (matplotlib.Text method). 537 set_linespacing() (matplotlib. 839 set_hatch() (matplotlib.backend_bases.NavigationToolbar2 method). 839 set_linestyle() (matplotlib.font_manager.TextWithDash method). 606 set_figure() (matplotlib.lines.Text method).figure. 390 set_fontweight() (matplotlib.patches.FontProperties method).text.backend_bases.Matplotlib.GraphicsContextBase method). 390 set_fontproperties() (matplotlib. 385 set_figure() (matplotlib.GraphicsContextBase method).Patch method).Tick method).text.text. 542 set_label_text() (matplotlib.artist.Figure method). 839 set_ha() (matplotlib.Figure method).Axis method).Artist method). 332 set_figure() (matplotlib.patches. 563 set_facecolor() (matplotlib.0. Release 1.axis.legend.Rectangle method).1 373 set_edgecolors() (matplotlib.GraphicsContextBase method).patches. 390 set_fontstretch() (matplotlib.axes.collections.Line2D method). 606 set_facecolor() (matplotlib.text.text.Text method).patches.Text method).Collection method). 389 set_fc() (matplotlib.LinearSegmentedColormap method).GraphicsContextBase method).Text method).Axis method).text. 537 set_label_position() (matplotlib. 339 890 set_frameon() (matplotlib. 581 set_gid() (matplotlib. 373 set_height() (matplotlib.Collection method). 370 set_height() (matplotlib. 390 set_fontstyle() (matplotlib.Patch method). 501 set_figure() (matplotlib. 373 set_fillstyle() (matplotlib.XAxis method).Text method).backend_bases.axis.Collection method).collections.FancyBboxPatch method). 541 set_label_position() (matplotlib.Figure method).Axes method).text. 564 set_linestyle() (matplotlib. 620 set_history_buttons() (matplotlib.Tick method).figure. 390 set_fontvariant() (matplotlib.axis.FontProperties method). 501 set_frame_on() (matplotlib.font_manager.Legend method).axis.gridspec.Text method).lines.Text method).backend_bases.axes. 332 set_graylevel() (matplotlib.Text method).YAxis method). 394 set_figwidth() (matplotlib. 606 set_gamma() (matplotlib.backend_bases.ColorbarBase method). 540 set_label() (matplotlib.text.text. 564 set_family() (matplotlib.GridSpecBase method).Axes method).Text method). 614 set_family() (matplotlib.Patch method). 563 set_facecolor() (matplotlib.text. 343 set_font_properties() (matplotlib. 574 set_label1() (matplotlib.Text method). 390 set_hatch() (matplotlib. 390 set_fontsize() (matplotlib.patches.axis.Artist method).FontProperties method). 390 set_joinstyle() (matplotlib. 614 set_fontname() (matplotlib.font_manager.text.figure.axis.Text method). 332 set_label() (matplotlib.Figure method).colors.colorbar. 389 set_fontconfig_pattern() (matplotlib. 606 set_file() (matplotlib.patches. 373 set_figheight() (matplotlib.collections. 373 set_facecolors() (matplotlib.collections.text. 839 set_frame_on() (matplotlib.artist.Artist method).text. Text method).text.patches. 537 set_major_locator() (matplotlib.Axes method). 345 set_markerfacecoloralt() (matplotlib. 264 set_mec() (matplotlib.Line2D method). 346 set_minor_formatter() (matplotlib.Collection method).patches. 344 set_ls() (matplotlib. 558 set_offset_position() (matplotlib.patches.transforms. 345 set_markersize() (matplotlib. 827 set_patch_circle() (matplotlib. 390 set_mutation_aspect() (matplotlib.Collection method).Text method).Colormap method).lines.Axis method).Patch method).Line2D method). 374 set_linestyles() (matplotlib. 345 set_markevery() (matplotlib.lines.ticker. 345 set_matrix() (matplotlib.ticker.lines.axis.1 343 set_linestyle() (matplotlib. 615 set_name() (matplotlib.Line2D method). 823 set_locs() (matplotlib.Collection method).0.lines.lines.FontProperties method).lines.Artist method).Line2D method). 542 set_offset_string() (matplotlib.Line2D method).Spine method).collections. 345 set_markerfacecolor() (matplotlib.axis.Matplotlib.colors.lines.text. 367 set_mutation_scale() (matplotlib.lines.MaxNLocator method).patches.text.spines. 501 set_navigate_mode() (matplotlib. 540 set_params() (matplotlib. 332 set_ls() (matplotlib. 538 set_ms() (matplotlib.Line2D method). 823 set_offsets() (matplotlib.artist.patches.Patch method). 344 set_linewidth() (matplotlib.Text method).ticker.Axis method).lines.Axis method). 346 set_mfc() (matplotlib.lines.Line2D method).backend_bases.Spine method). 374 set_lw() (matplotlib. 390 set_navigate() (matplotlib. 346 set_message() (matIndex plotlib. 839 set_linewidth() (matplotlib.FancyBboxPatch method).collections.Collection method). 390 set_major_formatter() (matplotlib.Line2D method).Line2D method). 370 set_mutation_scale() (matplotlib.Patch method).patches.Axes method). 344 set_lw() (matplotlib. 579 set_pad() (matplotlib. 374 set_ma() (matplotlib. 370 set_name() (matplotlib.Collection method). 564 set_over() (matplotlib.collections.Line2D method).Line2D method). 538 set_minor_locator() (matplotlib.Line2D method).FancyArrowPatch method).backend_bases.collections.patches. 346 set_mfcalt() (matplotlib. 824 set_lod() (matplotlib.axes.Formatter method). 344 set_markeredgecolor() (matplotlib.Line2D method).Line2D method).axis.lines.Tick method).collections.patches. Release 1. 538 set_marker() (matplotlib. 819 set_patchA() (matplotlib. 564 set_lw() (matplotlib.spines. 367 set_mutation_aspect() (matplotlib.FixedFormatter method). 564 set_linewidth() (matplotlib.ScalarFormatter method).axes.ScalarMappable method). 564 set_linewidth() (matplotlib.cm. 842 set_mew() (matplotlib.lines.lines.Affine2D method). 345 set_markeredgewidth() (matplotlib.FancyArrowPatch method). 564 set_locs() (matplotlib.FancyBboxPatch method).Line2D method). 501 set_norm() (matplotlib.ticker.Axis method). 374 set_linewidths() (matplotlib.patches.axis.lines.YAxis method).font_manager.NavigationToolbar2 method). 819 set_patch_line() (matplotlib.FancyArrowPatch 891 .Patch method).axis. 346 set_multialignment() (matplotlib.lines.axis.GraphicsContextBase method). ColorbarBase method).TextWithDash method).LineCollection method). 538 set_pickradius() (matplotlib.FontProperties method).text.Text method).polar.collections. 332 set_picker() (matplotlib.0. 538 set_ticklabels() (matplotlib. 819 set_snap() (matplotlib.FontProperties method).FontProperties method).axis.text. Release 1.colorbar.Artist method).PolarAxes method).GraphicsContextBase method).XAxis method).ticker.Axis method).Line2D method). 615 set_style() (matplotlib. 358 set_rasterization_zorder() (matplotlib. 367 set_patchB() (matplotlib.artist.collections.axis. 367 set_path_effects() (matplotlib. 391 set_rotation_mode() (matplotlib.Text method).Patch method).collections. 615 set_stretch() (matplotlib.LineCollection method).lines. 538 set_scientific() (matplotlib.collections.collections. 279 set_scale() (matplotlib.text.text. 566 set_paths() (matplotlib.axis.artist.polar. 567 set_paths() (matplotlib.ticker. 538 set_ticklabels() (matplotlib. 277 set_rotation() (matplotlib. 564 set_paths() (matplotlib.Axis method). 533 set_text() (matplotlib. 374 set_path_effects() (matplotlib.projections.backend_bases.Axes method).lines.ScalarFormatter method). 390 set_paths() (matplotlib. 391 set_style() (matplotlib.Figure method). Index .PolarAxes 892 method). 391 set_size_inches() (matplotlib. 839 set_solid_capstyle() (matplotlib. 333 set_snap() (matplotlib.patches.Collection method).projections.Axis method).Axes method).text.collections.collections.axis.polar. 346 set_pickradius() (matplotlib.Spine method).PolyCollection method).Line2D method).Text method).artist. 332 set_rgrids() (matplotlib. 568 set_paths() (matplotlib.Text method).text.spines.ScalarFormatter method). 824 set_segments() (matplotlib. 502 set_position() (matplotlib.SubplotBase method). 574 set_ticks() (matplotlib.Text method).axes. 346 set_points() (matplotlib.axis.Circle method).lines. 391 set_subplotspec() (matplotlib.PolarAxes method).QuadMesh method).text.Spine method).Line2D method).Text method). 615 set_size() (matplotlib.patches. 566 set_size() (matplotlib.Axis method).axis. 346 set_stretch() (matplotlib. 278 set_rticks() (matplotlib.Collection method). 569 set_picker() (matplotlib.Bbox method). 502 set_rasterized() (matplotlib.lines.PatchCollection method). 346 set_solid_joinstyle() (matplotlib.patches.colorbar. 279 set_tick_params() (matplotlib. 606 set_slant() (matplotlib.projections.text.collections.font_manager.axes.FancyArrowPatch method).polar.transforms.FancyArrowPatch method).Line2D method).Artist method).ColorbarBase method).Axis method). 567 set_paths() (matplotlib. 538 set_ticks() (matplotlib. 819 set_position() (matplotlib.Matplotlib.font_manager.patches. 367 set_powerlimits() (matplotlib.1 method).axis. 391 set_rscale() (matplotlib.text.PathCollection method). 824 set_radius() (matplotlib.projections.axes.Text method). 574 set_ticks_position() (matplotlib.Axis method).font_manager. 564 set_pickradius() (matplotlib.Artist method).Text method). 394 set_positions() (matplotlib.FontProperties method). 391 set_thetagrids() (matplotlib. 538 set_smart_bounds() (matplotlib. 390 set_position() (matplotlib.spines.PolarAxes method). 257 set_position() (matplotlib. 615 set_smart_bounds() (matplotlib.figure.font_manager. Axes method).text.ticker.Artist method). 394 (matplotlib.Axis method).Text method). set_width() (matplotlib. 394 plotlib.text.artist.axes.dates. 378 set_va() (matplotlib. 615 set_transform() (matplotlib.Text method).backend_bases.patches.XTick method).collections. 824 set_x() (matplotlib.TickHelper.Axes method).axes.text.FontProperties 346 method).Artist method). 394 set_ybound() (matplotlib.Text method). 587 set_tzinfo() (matplotlib.gridspec.axis. 538 plotlib.0.Tick method). 391 set_verticalalignment() (matplotlib.set_x() (matplotlib. set_xy() (matplotlib.DateLocator method).Legend method).axes.FancyBboxPatch set_tzinfo() (matplotlib. 370 method).axes.patches. set_y() (matplotlib. 566 set_verts() (matplotlib.Axes method).lines.Colormap method).FancyBboxPatch set_useOffset() (matplotlib.patches.axis.lines.lines.axes.axes.TextWithDash method). 333 333 (matset_transform() (matplotlib. 346 set_ylabel() (matplotlib.axes.patches.Axes method).axis. 839 plotlib. set_weight() plotlib. 509 Index 893 .XAxis method).axis.text.Artist method).FontProperties set_xbound() (matplotlib.font_manager.Rectangle method).collections. set_ydata() (matplotlib.Text method).Collection method). 391 set_verts() (matplotlib.ticker. 339 method).OffsetFrom method).patches. 505 method).FigureCanvasBase set_url() (matplotlib. set_width_ratios() plotlib. Release 1.Polygon method).Axes method). 502 plotlib. set_visible() (matplotlib.GraphicsContextBase set_window_title() (matmethod). 346 set_variant() (matplotlib.artist.FancyBboxPatch set_view_interval() (matplotlib. 503 set_xlim() (matplotlib.Axes method). set_ylim() (matplotlib.ScalarFormatter set_x() method).FigureManagerBase set_urls() (matplotlib.DummyAxis set_title() (matplotlib. 507 method). 823 set_transform() (matplotlib.TextWithDash set_weight() (matplotlib.PolyCollection set_xticklabels() (matplotlib. set_y() method).Axis method).legend.axis. 564 (matplotlib.1 543 541 (matplotlib.axis.patches. 579 620 set_unit() (matplotlib. 376 set_xy() (matplotlib. 507 543 set_view_interval() (matplotlib.YAxis method).patches.text. 568 set_view_interval() (matplotlib. 391 method). 506 set_xticks() (matplotlib. 392 541 set_view_interval() (matplotlib.axes. 370 method). 505 set_xscale() (matplotlib. 333 method). 378 588 (matset_under() (matplotlib.text. 507 542 set_view_interval() (matplotlib.LineCollection set_xmargin() (matplotlib.TextWithDash method).Axes method).font_manager.ticker.backend_bases. set_view_interval() method).collections.Matplotlib. 505 method).text.Text method).Line2D method). 378 set_y() (matplotlib. 503 method).Line2D method).artist.DateFormatter set_width() method).Axes method). 371 540 set_view_interval() (matplotlib. 391 set_x() (matplotlib.Rectangle method). 615 set_xdata() (matplotlib. 823 542 set_view_interval() (matset_title() (matplotlib.backend_bases.Rectangle method).Axes method).text.Axes method).Text set_xlabel() (matplotlib.YAxis method).GridSpecBase method).Line2D method).axis.text.dates. 837 method).colors.YTick method).patches.axis.axes. 386 set_window_title() (matset_units() (matplotlib. 378 538 (matplotlib.TickHelper set_ticks_position() (matplotlib.Rectangle method). 836 set_url() (matplotlib.axes. 391 set_variant() (mat.axes. set_y() (matplotlib.Axes method).text. Char method).Axes method).transforms.mlab). 852 size (matplotlib. 580 Shadow (class in matplotlib. 379 Ship (class in matplotlib. 548 Sorter (class in matplotlib.DviFont attribute).FigureManagerBase method).mathtext.Axes method).cbook.axes. 837 ShowBase (class in matplotlib.0. 561 specgram() (in module matplotlib.Box method).mlab).TimerBase attribute). 632 SsGlue (class in matplotlib.Scheduler method).BboxBase method). 788 step() (matplotlib.Node method).pyplot). 632 start_pan() (matplotlib. 255 spring() (in module matplotlib.Parser method).pyplot).transforms.backend_bases. 845 start_group() (matplotlib.colors. 633 StixSansFonts (class in matplotlib.RendererBase method).Sorter method).backend_bases.transforms.mathtext.backend_bases.mathtext).backend_bases. 509 set_yscale() (matplotlib.RendererBase method).mathtext). 633 StarPolygonCollection (class in matplotlib. 255 slopes() (in module matplotlib. 548 stop_event_loop() (matplotlib.Artist method).LightSource method).spines).backend_bases. 509 set_yticklabels() (matplotlib.mathtext. 788 stem() (matplotlib.cbook).backend_bases.backend_bases. 786 spy() (in module matplotlib. 511 set_zorder() (matplotlib. 836 start_filter() (matplotlib. 255 shrunk_to_aspect() (matplotlib.axes.mathtext.mathtext.colors.pyplot). 847 start_event_loop() (matplotlib. 553 space() (matplotlib. 817 894 splitx() (matplotlib. 633 stop() (matplotlib. 627 shrink() (matplotlib.dviread.Axes method).axes.TimerBase method). 633 show_popup() (matplotlib. 836 start_event_loop_default() (matplotlib. 335 setp() (in module matplotlib.TimerBase method).LightSource method). 579 shade_rgb() (matplotlib.mathtext).cbook).mathtext. 570 start() (matplotlib.collections.artist).axes.axes. 515 stineman_interp() (in module matplotlib.Parser method).cbook).Parser method). 510 set_yticks() (matplotlib.Kern method).1 set_ymargin() (matplotlib.axes. 333 setp() (in module matplotlib.mlab).Axes method). 255 splity() (matplotlib.mathtext). 548 soundex() (in module matplotlib.axes.BboxBase method).pyplot).mathtext. 624 shrink() (matplotlib. 784 shade() (matplotlib.BboxBase method). 514 start_rasterizing() (matplotlib. 632 StandardPsFonts (class in matplotlib. 511 spectral() (in module matplotlib.backend_bases.Accent method). 513 sqrt() (matplotlib.Axes method).FigureCanvasBase method).mathtext. 786 Spine (class in matplotlib.transforms. 632 span_where() (matplotlib.BboxBase method).backend_bases). 845 stem() (in module matplotlib. 623 shrink() (matplotlib.Glue method).backend_bases. 624 shrink() (matplotlib. 657 specgram() (in module matplotlib. 515 step() (in module matplotlib.pyplot).patches).backend_bases.RendererBase method). Release 1.BboxBase attribute).cbook. 255 silent_list (class in matplotlib. 785 specgram() (matplotlib.Matplotlib.FigureCanvasBase method). 847 stop() (matplotlib. 845 Index . 627 shrink() (matplotlib.Axes method).mathtext.Axes method).pyplot). 786 spy() (matplotlib.axes. 836 stop_event_loop_default() (matplotlib.collections).cbook).Axes method).mathtext.FigureCanvasBase method).axes.BrokenBarHCollection static method). 553 simple_linear_interpolation() (in module matplotlib.List method). 658 StixFonts (class in matplotlib. 631 shrunk() (matplotlib. 657 sort() (matplotlib.backend_bases. 847 size (matplotlib. 836 stop_filter() (matplotlib.FigureCanvasBase method). 633 Stack (class in matplotlib.transforms.artist.cbook). 553 single_shot (matplotlib.mathtext). 626 shrink() (matplotlib. 846 shrink() (matplotlib.Parser method). 548 stackrel() (matplotlib.mathtext.Axes method).pyplot). RendererBase tick_top() (matplotlib.axes.colors.Figure method). 516 Index 895 .colors.FigureCanvasBase to_rgba() (matplotlib.path. 628 method).cbook).axis. 543 strip_math() (in module matplotlib.backend_bases).text).axes.figure.ColorConverter method).text).pyplot).Axes method). SVG. 790 subplots_adjust() (in module matplotlib. 543 587 string_width_height() (matplotlib.backends. ticklabel_format() (in module matplotlib. 579 274 to_values() (matplotlib.afm.pyplot).RendererBase Tfm (class in matplotlib. 796 Tk. 858 SubplotParams (class in matplotlib. 392 plotlib.axes.cbook).axes).0.cbook). 796 533 ticklabel_format() (matplotlib.dates. 541 Ticker (class in matplotlib. 578 plotlib. 262 table() (in module matplotlib. 795 tick_params() (matplotlib.pyplot).figure. thetagrids() (in module matplotlib.DummyAxis (class in matplotlib.pyplot).XAxis method). 663 summer() (in module matplotlib. 792 todate (class in matplotlib.axes).ticker. title() (in module matplotlib.LogLocator method). 792 to_rgb() (matplotlib. 554 text() (in module matplotlib. 554 texname (matplotlib.ScalarMappable method). 539 850 strftime() (matplotlib. 792 578 suptitle() (matplotlib.mathtext. 789 822 subplot2grid() (in module matplotlib. 822 Subplot (in module matplotlib. 548 subplots() (in module matplotlib.Figure method).Axes method).mathtext).ticker).mathtext.pyplot). 554 text() (matplotlib.backend_pdf).Path method).YAxis method). 531 TIFF.Affine2DBase T method). 845 Stream (class in matplotlib. 792 (matplotlib.figure.figure). 632 SymmetricalLogScale (class in matplotlib.Parser method). 324 tick_right() (matplotlib.dviread. 790 518 SubplotBase (class in matplotlib.YAxis method).cbook).1 stop_rasterizing() (mat. 634 (matplotlib.MathTextParser subsuperscript() (matplotlib.mathtext. 620 to_mask() (matplotlib. 607 TextWithDash (class in matplotlib. 793 tostr (class in matplotlib. 852 tofloat (class in matplotlib. 540 method).axis). suptitle() (in module matplotlib.pyplot). 826 method).pyplot).cbook).scale). 541 tick_left() (matplotlib. 846 subplots_adjust() (matplotlib. 628 SubSuperCluster (class in matplotlib. tick_bottom() (matplotlib. 531 TickHelper.ColorConverter switch_backends() (mat.pyplot).transforms. Release 1. 607 to_rgba() (matplotlib. 386 toint (class in matplotlib. 853 method). 789 subplot_class_factory() (in module matplotlib.to_rgba() method).ColorConverter method). 553 SubplotSpec (class in matplotlib. 553 strip_math() (matplotlib.cbook). 554 Text (class in matplotlib.Parser to_png() method).backend_bases.MathTextParser subs() (matplotlib. subplot() (in module matplotlib.Axes method).axes).MathTextParser method).cbook).mathtext. 858 607 to_filehandle() (in module matplotlib.axis.backend_bases.pyplot).pyplot). 858 558 switch_backend() (in module matplotlib. 515 todatetime (class in matplotlib.axes.Matplotlib.pyplot).backend_bases.ticker).pyplot).Axes method). 794 Tick (class in matplotlib.text() (matplotlib.colors.Figure method).DateFormatter method).mathtext.cm. 837 method).DviFont attribute). 846 TickHelper (class in matplotlib. 628 symbol() (matplotlib.gridspec). 553 table() (matplotlib.pyplot). subplot_tool() (in module matplotlib.axis).AFM tick_params() (in module matplotlib.dviread).XAxis method).pyplot).cbook). 608 Timeout (class in matplotlib.axis. to_rgba_array() (matplotlib.axis. 632 to_polygons() (matplotlib. 791 TimerBase (class in matplotlib. 517 method). IdentityTransform transform_non_affine() (mat896 Index .mlab.polar. 266 method). 267 plotlib.FormatObj method).PolarAxes.Affine2DBase method). 276 transform_affine() (matplotlib.projections. 276 method).mlab.transforms. 265 method).transforms.Transform method).FormatString method). 268 transform_path_non_affine() (matmethod).PolarAxes.transforms. 640 transform_non_affine() (mattoval() (matplotlib.PolarTransform transform() (matplotlib.transforms.projections.Matplotlib.mlab.mlab.FormatInt method).Transform method).transforms.FormatDate method).polar. 640 plotlib. 262 transform_path() (mattransform() (matplotlib. 640 method).Transform method).polar.transforms.FormatObj method).transforms.PolarTransform method). method).transforms. 259 (mattransform() (matplotlib.CompositeGenericTransform plotlib.transforms. 267 260 transform_affine() (mattransform_path_non_affine() (matplotlib.Transform method).transforms.AffineBase method).PolarTransform method).transforms.IdentityTransform method). transform_angles() (mat261 plotlib.transforms.transforms.Type1Font transform_path_affine() plotlib.transforms.PolarTransform transform_path() (matmethod). 260 method).projections.AffineBase method).BlendedGenericTransform tostr() (matplotlib.mlab. 264 transform() (matplotlib.transforms.CompositeGenericTransform transform_non_affine() (matplotlib.transforms.transforms).IdentityTransform toval() (matplotlib.mlab. 261 640 transform_non_affine() (mattostr() (matplotlib.CompositeGenericTransform method). 268 toval() (matplotlib.FormatFormatStr method).transforms.0. 265 method).InvertedPolarTransform plotlib.BlendedGenericTransform transform_path_affine() plotlib. transform_path_affine() plotlib.polar. 639 method).mlab. method).FormatFloat method).transforms. 268 transform_affine() (mat(matplotlib.transforms.1 plotlib. 640 plotlib.PolarAxes.mlab.transforms.Transform transform_path() (matplotlib.transforms.AffineBase method). 265 Transform (class in matplotlib. 265 transform_affine() (mattransform_path_affine() (matplotlib. 259 plotlib. 639 plotlib.type1font. 640 method). method). 266 tostr() (matplotlib.transforms. 258 transform_non_affine() (mattransform() (matplotlib.IdentityTransform transform() (matplotlib.CompositeGenericTransformmethod).BlendedGenericTransform plotlib. 854 261 transform_affine() (mat(matplotlib. transform_path_non_affine() (mat259 plotlib.mlab.transforms.CompositeGenericTransform 262 method).polar.PolarAxes.transforms. Release 1.projections.transforms. 276 plotlib.PolarAxes.transforms.Affine2DBase method). tostr() (matplotlib. 266 transform() (matplotlib.IdentityTransform method). 275 259 transform() (matplotlib.IdentityTransform plotlib.FormatInt method). 268 transform_path() (matmethod).FormatBool method).projections. 276 plotlib.Transform transform_path_non_affine() (matmethod). 640 transform_non_affine() (mattoval() (matplotlib.CompositeGenericTransform toval() (matplotlib. ArrowStyle.Affine2D method).transforms.Annotation method).path.SubplotParams method). 252 TransformWrapper (class in matplotlib. 554 unit() (matplotlib.cbook).Sawtooth method).CachedFont (class in matplotlib.ArrowStyle. 663 transformed() (matplotlib.pyplot). 609 update() (matplotlib. 257 unit_circle() (matplotlib.Path class method). 333 update() (matplotlib.Round method). 800 tricontourf() (matplotlib.Transform method).pyplot). 357 transmute() (matplotlib.Path method). 634 ttfdict_to_fnames() (in module matplotlib.path.Axes method). 357 transmute() (matplotlib.Axes method).Axes method). 264 translated() (matplotlib.GridSpec method).0. 255 TransformedBbox (class in matplotlib.BoxStyle.cbook).path.transforms.Transform method).transforms.path.transforms. 521 tripcolor() (in module matplotlib.Axes method).artist. 634 union() (matplotlib.axes.Simple method).Square method). 616 twinx() (in module matplotlib. 355 transmute() (matplotlib.patches. 526 TruetypeFonts (class in matplotlib.mathtext). 269 TransformNode (class in matplotlib.Roundtooth method). 357 transmute() (matplotlib.transforms.BoxStyle.transforms).ArrowStyle.transforms).patches.BoxStyle.mathtext). 260 transformed() (matplotlib.Fancy method).Affine2DBase method). 804 triplot() (matplotlib. 664 unit_regular_polygon() (matplotlib.Path class method). 260 transform_point() (matplotlib.Wedge method).patches.BoxStyle. 664 unit_regular_star() (matplotlib. 554 UnicodeFonts (class in matplotlib. 527 Type1Font (class in matplotlib.font_manager).transforms).BboxBase method). 357 transmute() (matplotlib.Artist method).Axes method).NavigationToolbar2 method). 803 Index tripcolor() (matplotlib.Round4 method). 519 tricontourf() (in module matplotlib. 265 transform_path_non_affine() (matplotlib.path.path.patches.BboxBase static method). 357 transmute() (matplotlib.pyplot). 616 ttfFontProperty() (in module matplotlib.BoxStyle.1 method). 260 translate() (matplotlib. 554 update() (matplotlib. 665 unmasked_index_ranges() (in module matplotlib. 262 transform_point() (matplotlib. 805 twinx() (matplotlib.patches. 256 unique() (in module matplotlib.pyplot).Matplotlib.Path class method). 357 tricontour() (in module matplotlib. 664 unit_rectangle() (matplotlib.axes.Path class method). 634 TruetypeFonts. 664 unit_regular_asterisk() (matplotlib. 805 twiny() (matplotlib. 635 unicode_safe() (in module matplotlib. 842 update() (matplotlib.Axes method).axes.RArrow method).gridspec. Release 1.backend_bases. 256 transmute() (matplotlib.path.cbook). 664 unit_circle_righthalf() (matplotlib. 796 tricontour() (matplotlib.transforms.Bbox static method). 258 TransformedPath (class in matplotlib.figure. 854 U unichr_safe() (in module matplotlib.patches.BoxStyle.patches.transforms). 527 twiny() (in module matplotlib.type1font).patches. 619 update_bbox_position_size() (matplotlib.transforms.BoxStyle.axes.pyplot).Path class method). 354 transmute() (matplotlib.Path class method).pyplot). 354 transmute() (matplotlib. 525 triplot() (in module matplotlib.BboxBase method).patches.axes. 385 897 .text.mathtext).LArrow method).mathtext). 357 transmute() (matplotlib.font_manager).transforms.patches.axes. 257 update_from_data_xy() (matplotlib.transforms. 858 vector_lengths() (in module matplotlib. 635 W waitforbuttonpress() (in module matplotlib.fontconfig_pattern).text.0.patches). 807 waitforbuttonpress() (matplotlib.mathtext).ticker.LogLocator method).LinearLocator method). 592 weight_as_number() (in module matplotlib. 347 Vf (class in matplotlib. 394 update_datalim() (matplotlib.TextWithDash method). 564 update_ticks() (matplotlib.mathtext.artist. 392 update_from_data() (matplotlib.path. 564 update_from() (matplotlib.cbook). 634 VCentered (class in matplotlib. 321 898 useOffset (matplotlib.ColorbarBase method).mathtext).Line2D method). Release 1.ticker.figure.ScalarFormatter tribute). 659 VertexSelector (class in matplotlib. 853 view_limits() (matplotlib.Collection method).collections.dates).mlab). 533 update_position() (matplotlib.lines). 385 update_scalarmappable() (matplotlib.1 update_bbox_position_size() (matplotlib. 347 update_from() (matplotlib.Matplotlib. 633 vpack() (matplotlib.SubplotBase method). 574 update_units() (matplotlib.ticker. 824 at- V value_escape() (in module matplotlib.axis.Colorbar method). 590 weeks() (in module matplotlib. 528 Vlist (class in matplotlib.text. 380 wedge() (matplotlib. 333 update_from() (matplotlib. 827 view_limits() (matplotlib.dviread. 608 Wedge (class in matplotlib.mathtext).axes.YTick method). 528 update_datalim_to_current() (matplotlib.mathtext.Ship method).Bbox method). 549 vlines() (in module matplotlib.fontconfig_pattern).colorbar.lines.Figure method). 542 update_position() (matplotlib. 258 update_normal() (matplotlib. 617 Vbox (class in matplotlib. 634 Vrule (class in matplotlib.Collection method). 616 width (matplotlib.cbook).dates. 613 update_from() (matplotlib. 853 Index .colorbar. 527 update_datalim_bounds() (matplotlib. 538 use() (in module matplotlib).mathtext).ticker.patches.dates).pyplot). 573 update_params() (matplotlib.Bbox method).axis.Annotation method).Vlist method).Path class method).colorbar.font_manager.FontManager method).dviread). 634 vlist_out() (matplotlib.Text method). 617 value_unescape() (in module matplotlib. 805 vlines() (matplotlib.text.Tfm attribute).axes.collections.Colorbar method). 392 update_bruteforce() (matplotlib. 639 update_fonts() (matplotlib. 374 update_from() (matplotlib. 573 update_coords() (matplotlib.transforms.Axis method).transforms.Artist method).Axes method).Axes method). 543 update_positions() (matplotlib.ticker. 665 WeekdayLocator (class in matplotlib. 257 update_from_path() (matplotlib.XTick method).Axes method).axes.ticker.Axes method).Patch method). 554 vector_lengths() (in module matplotlib. 634 vector graphics.axes.font_manager).MaxNLocator method).DateLocator method).Locator method).MultipleLocator method).FIFOBuffer method).axes.mlab. 588 ViewVCCachedServer (class in matplotlib. 826 viewlim_to_dt() (matplotlib. 826 view_limits() (matplotlib.Bbox method). 528 update_datalim_numerix() (matplotlib. 826 view_limits() (matplotlib. 825 view_limits() (matplotlib.pyplot).Text method).axis.text. transforms. 529 xaxis_inverted() (matplotlib. 812 method).BboxBase attribute).font_manager). plotlib. 811 method).patches). widths (matplotlib.backend_pdf.ticker. 809 xlat() (matplotlib.cbook.backend_pdf.Locator method). 543 yticks() (in module matplotlib. 851 write_cache() (mat.NavigationToolbar2 method).mlab). 659 y1 (matplotlib.mlab). 256 xscale() (in module matplotlib.BboxBase attribute).0.axis).patches. 849 writeTrailer() (mat.DviFont attribute).cbook).axis. xy (matplotlib. 530 xlabel() (in module matplotlib.backends.pyplot).PdfFile 256 method).Axes method).Polygon attribute).MemoryMonitor method). 256 x11FontDirectory() (in module matplotlib.ymin (matplotlib. 811 Index 899 .transforms. 256 zoom() (matplotlib.BboxBase attribute).Xlator method). 381 wrap() (in module matplotlib. 256 window_none() (in module matplotlib. 539 X zoom() (matplotlib.backend_pdf.axes. 550 Xlator (class in matplotlib. plotlib. 807 xcorr() (matplotlib.axes.patches.BboxBase attribute).dates).PdfFile YTick (class in matplotlib.axis).ViewVCCachedServer ylabel() (in module matplotlib.transforms. 616 547 win32InstalledFonts() (in module matplotlib.transforms.cbook. 256 xmin (matplotlib.patches.pyplot). 659 Y y0 (matplotlib.transforms. 549 xlim() (in module matplotlib. Release 1. 555 write() (matplotlib.BboxBase attribute).backends.BboxBase attribute). 842 x0 (matplotlib.pyplot). 531 YearLocator (class in matplotlib. 812 method). 825 x1 (matplotlib.pyplot). 376 xy (matplotlib.backends. 812 ymax (matplotlib.Axes method).axes.Axis method). 541 xticks() (in module matplotlib.yaxis_inverted() (matplotlib.Axes method).backends. 616 window_hanning() (in module matplotlib. 849 writeXref() (matplotlib.transforms. 858 Z wxWidgets. 378 256 xy (matplotlib.BboxBase attribute). 849 wxpython.BboxBase attribute). 542 yaxis_date() (matplotlib. 549 writeInfoDict() (mat.pyplot).font_manager).axes.pyplot).axis). 540 xaxis_date() (matplotlib.transforms.ylim() (in module matplotlib. 531 method).axes.BboxBase attribute).transforms. 810 XTick (class in matplotlib.transforms.RegularPolygon attribute).backend_pdf.PdfFile yscale() (in module matplotlib. 256 plotlib.Matplotlib.cbook). 852 379 win32FontDirectory() (in module matxy() (matplotlib. 256 winter() (in module matplotlib.1 width (matplotlib.axis).pyplot).Stream YAxis (class in matplotlib. 858 zoom() (matplotlib. 810 xmax (matplotlib.Axes method).Axes method). 807 YAArrow (class in matplotlib.dviread. 529 xcorr() (in module matplotlib.pyplot).Rectangle attribute).pyplot). 589 plotlib.pyplot). 616 XAxis (class in matplotlib.cbook.font_manager).backend_bases.