Release 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 ﬁgures 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 ﬁle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 oﬀset transforms to create a shadow eﬀect 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 eﬀect between Axes . . . . . . . . . . . . . 15.7 Deﬁne 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 ﬁne, 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 conﬁguration 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 ﬁgure 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 deﬁciencies as a programming language, but I was having diﬃculty ﬁnding 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 ﬁxed user interface (the pylab interface) has been very useful, because the guts of the code base can be redesigned without aﬀecting 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 ﬁgure generating code (Pyplot tutorial). The matplotlib frontend or matplotlib API is the set of classes that do the heavy lifting, creating and managing ﬁgures, 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 ﬁgure and embed it a Gtk+ application, and so on for PDF, WxWidgets, Tkinter etc. matplotlib is used by many people in many diﬀerent contexts. Some people want to automatically generate PostScript ﬁles 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 diﬀerent 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 ﬁrst need to ﬁnd out if you have python installed on your machine, and if not, install it. The oﬃcial 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 suﬃces 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 conﬁguration 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 diﬃcult to build matplotlib from source. Grab the latest tar.gz release ﬁle from sourceforge, or if you want to develop matplotlib or just need the latest bugﬁxed version, grab the latest svn version Install from svn. Once you have satisﬁed 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 ﬁle 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 ﬁle 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 ﬁrst 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” postﬁx) 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 ﬁles (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 ﬁles. 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 pyﬂtk 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 aﬀect 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 :ﬁle:‘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, ﬁnk, /usr/X11R6) and the diﬀerent architectures (x86, ppc, universal) and the diﬀerent 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 Makeﬁle which will automatically grab the zlib, png and freetype dependencies from the web, build them with the right ﬂags to make universal libraries, and then build the matplotlib source and binary installers.

8

Chapter 2. Installing

decorate the plot with labels. and the plotting functions are directed to the current axes import matplotlib.5 2.0 0. in that it keeps track of the current ﬁgure and plotting area.5 some numbers 3.0 3. matplotlib.CHAPTER THREE PYPLOT TUTORIAL matplotlib.5 2. etc.0 0.0 1.pyplot is a collection of command style functions that make matplotlib work like MATLAB.pyplot as plt plt. create a plotting area in a ﬁgure.3.4]) plt.0 2.ylabel(’some numbers’) plt.0 9 .5 3. plot some lines in a plotting area..pyplot is stateful.0 1. create a ﬁgure.5 1.0 2.2.show() 4...plot([1.5 1. Each pyplot function makes some change to a ﬁgure: eg.

1 You may be wondering why the x-axis ranges from 0-2 and the y-axis from 1-3. plot() is a versatile command. [1.4]. you can issue the command: plt. all sequences are converted to numpy arrays internally. Generally.1.0.4. the default x vector has the same length as y but starts with 0.axis([0. For example.plot([1. y pair of arguments. to plot x versus y. and automatically generates the x values for you.plot([1. and you concatenate a color string with a line style string. there is an optional third argument which is the format string that indicates the color and line type of the plot.pyplot as plt plt. 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. 0.9. it would be fairly useless for numeric processing.16]) For every x. ymax] and speciﬁes the viewport of the axes. In fact. Since python ranges start with 0.16]. you would issue import matplotlib.2].9. which is a solid blue line. you will use numpy arrays. matplotlib assumes it is a sequence of y values.4]. The axis() command in the example above takes a list of [xmin. The default format string is ‘b-‘. If you provide a single list or array to the plot() command. 6.2. to plot the above with red circles. ymin.Matplotlib.2. Release 1. [1. and will take an arbitrary number of arguments.3. The letters and symbols of the format string are from MATLAB. 10 Chapter 3. xmax. Hence the x data are [0. ’ro’) plt.4. The example below illustrates a plotting several lines with diﬀerent format styles in one command using arrays. For example. If matplotlib were limited to working with lists.3. Pyplot tutorial .

matplotlib.1. ’g^’) 120 100 80 60 40 20 00 1 2 3 4 5 3. Release 1.0) see • Use the setter methods of the Line2D instance..lines. etc. t.plot(t. t.2) # red dashes. I use tuple unpacking in the line.arange(0.1 Controlling line properties Lines have many attributes that you can set: linewidth. 5.Line2D. y. plot returns a list of lines. t**3.1 import numpy as np import matplotlib. ’bs’. blue squares and green triangles plt.Matplotlib. linewidth=2. dash style. t. t**2. line2 = plot(x1.. eg line1.0. antialiased. Controlling line properties 11 .plot(x.y1. 0. There are several ways to set line properties • Use keyword args: plt.x2). Below I have only one line so it is a list of length 1. y. ’o’) to get the ﬁrst element of the list: 3. = plot(x. ’r--’.pyplot as plt # evenly sampled time at 200ms intervals t = np.x2.

Property alpha animated antialiased or aa clip_box clip_on clip_path color or c contains dash_capstyle dash_joinstyle dashes data ﬁgure 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 ﬂoat [True | False] [True | False] a matplotlib.transform. color=’r’.array xdata. a Patch any matplotlib color the hit testing function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points (np.Transform instance [True | False] np. The example below uses a MATLAB-style command to set multiple properties on a list of lines.1 line.’ | ‘. ’-’) line.plot(x1. ’color’. stride) used in interactive line selection the line pick selection radius [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.0.array np. ’linewidth’. You can either use python keyword arguments or MATLAB-style string/value pairs: lines = plt.Figure instance any string [ ‘-‘ | ‘–‘ | ‘-.’ | ‘1’ | ‘2’ | ‘3’ | ‘4’ any matplotlib color ﬂoat value in points any matplotlib color ﬂoat None | integer | (startind. Release 1.array any number 12 Chapter 3.Bbox instance [True | False] a Path instance and a Transform instance.transforms.array ydata) a matplotlib.Matplotlib.plot(x. = plt. linewidth=2.’ | ‘:’ | ‘steps’ | . Pyplot tutorial . setp works transparently with a list of objects or a single object. x2. y1.] ﬂoat value in points [True | False] [ ‘+’ | ‘.setp(lines. y.set_antialiased(False) # turn off antialising • Use the setp() command.ﬁgure. 2. np..0) Here are the available Line2D properties.0) # or MATLAB style string value pairs plt.setp(lines.. ’r’. y2) # use keyword args plt.

The function gca() returns the current axes (a matplotlib.2. So subplot(211) is identical to subplot(2.0.. You can create multiple ﬁgures by using multiple figure() calls with an increasing ﬁgure number.0. Of course. All plotting commands apply to the current axes.0. fignum where fignum ranges from 1 to numrows*numcols.3]) In [70]: plt.subplot(211) # the first subplot in the first figure plt. height]) where all values are in fractional (0 to 1) coordinates.figure.1.0. t2.figure(1) # the first figure plt. just as a subplot(111) will be created by default if you don’t manually specify an axes. Working with multiple ﬁgures and axes 13 . bottom. width. ’k’) plt.figure(1) plt. use the axes() command.Matplotlib. ie. See pylab_examples-axes_demo for an example of placing axes manually and pylab_examples-line_styles for an example with lots-o-subplots. If you want to place an axes manually.plot(t2.cos(2*np. have the concept of the current ﬁgure and the current axes. and gcf() returns the current ﬁgure (matplotlib.axes.plot(t1. ’bo’.2 Working with multiple ﬁgures and axes MATLAB. because it is all taken care of behind the scenes.3]) 3. The commas in the subplot command are optional if numrows*numcols<10. ’r--’) The figure() command here is optional because figure(1) will be created by default. Release 1. 0. call the setp() function with a line or lines as argument In [69]: lines = plt.plot([1.setp(lines) alpha: float animated: [True | False] antialiased or aa: [True | False] .1). and pyplot.pi*t2).subplot(212) plt. np.plot([1. f(t1).2.exp(-t) * np.snip 3. import numpy as np import matplotlib. f(t2).0.1) t2 = np. numcols. 5.Figure instance). not on a rectangular grid.2.pyplot as plt def f(t): return np. The subplot() command speciﬁes numrows. which allows you to specify the location as axes([left.subplot(211) plt. 0.1 To get a list of settable line properties. You can create an arbitrary number of subplots and axes.pyplot as plt plt. you don’t have to worry about this.arange(0.cos(2*np. Normally.Axes instance). Below is a script to create two subplots.02) plt. each ﬁgure can contain as many axes and subplots as your heart desires: import matplotlib. 5.pi*t) t1 = np.arange(0..

0 0.2 0.subplot(211) plt.figure(2) plt.80 1. Release 1.figure(1) plt.5.4 0. and/or using the window manager to kill the window in which the ﬁgure appears on the screen.subplot(212) plt. Pyplot tutorial .5 1.0 0. you need to be aware of one more thing: the memory required for a ﬁgure is not completely released until the ﬁgure is explicitly closed with close().6]) 1 2 3 4 5 1 2 3 4 5 # the second subplot in the first figure plt. Deleting all references to the ﬁgure.6]) plt.1 1.plot([4. annoying. because pyplot maintains internal references until close() is called.title(’Easy as 1.0 0.4 0.0 0. 14 Chapter 3.5.5 0. is not enough. don’t despair. which you can use instead (see Artist tutorial) If you are making a long sequence of ﬁgures.00 plt.2 0. this is just a thin stateful wrapper around an object oriented API.6 0.2.6 0.3’) # a second figure # creates a subplot(111) by default # figure 1 current.8 0. If you ﬁnd this statefulness. subplot(212) still current # make subplot(211) in figure1 current # subplot 211 title You can clear the current ﬁgure with clf() and the current axes with cla().Matplotlib.plot([4.0.

σ =15 80 100 120 Smarts 140 160 All of the text() commands return an matplotlib.1 3.ylabel(’Probability’) plt.xlabel(’Smarts’) plt.025.text. r’$\mu=100. 50.000 40 60 Histogram of IQ µ =100.030 0.010 0.hist(x.75) plt.text(60. sigma = 100. and the xlabel(). normed=1.3 Working with text The text() command can be used to add text in an arbitrary location. facecolor=’g’. alpha=0. you can customize the properties by passing keyword arguments into the text functions or using setp(): 3. Release 1.005 0. Working with text 15 .random. 0. 160. 15 x = mu + sigma * np. patches = plt.\ \sigma=15$’) plt.axis([40.3.03]) plt.020 Probability 0.grid(True) 0.Matplotlib. 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.pyplot as plt mu.0.025 0.title(’Histogram of IQ’) plt.Text instance. Just as with with lines above.randn(10000) # the histogram of the data n. 0.015 0. . bins.

05). For those who have LaTeX and dvipng installed. = plt.Matplotlib. and ships its own math fonts – for details see Writing mathematical expressions.3.arange(0.1 Using mathematical expressions in text matplotlib accepts TeX equation expressions in any text expression.annotate(’local max’. 3. shrink=0.ylim(-2. xy=(2.2 Annotating text The uses of the basic text() command above place text at an arbitrary position on the Axes. Pyplot tutorial . fontsize=14. 0.xlabel(’my data’.1 t = plt. arrowprops=dict(facecolor=’black’. 16 Chapter 3. lw=2) plt.0. Thus you can use mathematical text across platforms without requiring a TeX installation.pi*t) line.plot(t. Both of these arguments are (x. For example to write the expression σi = 15 in the title.pyplot as plt ax = plt.2) plt. both the xy (arrow tip) and xytext locations (text location) are in data coordinates.3. More examples can be found in pylab_examples-annotation_demo. and the annotate() method provides helper functionality to make annotations easy. you can also use LaTeX to format your text and incorporate the output directly into your display ﬁgures or saved postscript – see Text rendering With LaTeX.subplot(111) t = np. 5. import numpy as np import matplotlib. matplotlib has a built-in TeX expression parser and layout engine. In an annotation.y) tuples.cos(2*np.01) s = np. s. 1.show() In this basic example. ) plt.0. color=’red’) These properties are covered in more detail in Text properties and layout. 1). 3. there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. A common use case of text is to annotate some feature of the plot.title(r’$\sigma_i=15$’) The r preceeding the title string is important – it signiﬁes that the string is a raw string and not to treate backslashes and python escapes. There are a variety of other coordinate systems one can choose – see Annotating text and Annotating Axes for details. Release 1.0.5). xytext=(3. you can write a TeX expression surrounded by dollar signs: plt.

5 0.0.5 1.5 1.0 1.0 0. Release 1.Matplotlib.0 0.0 1.00 1 2 3 4 5 local max 3. Working with text 17 .5 2.1 2.3.

1 18 Chapter 3.0.Matplotlib. Release 1. Pyplot tutorial .

They have no meaning unless you have already navigated somewhere else using the pan and zoom buttons. the data under the point where you pressed will be moved to the point where you released. ‘y’ or ‘CONTROL’ to constrain the zoom to the x axis. The radius scale can be zoomed in and out using the right mouse button. Ditto for the y axis and up/down motions. or aspect ratio preserve. The radius axis labels can be dragged using the left mouse button. For Home. The point under your mouse when you begin the zoom remains stationary. This is analogous to trying to click Back on your web browser before visiting a new page –nothing happens. Click the toolbar button to activate panning and zooming. Press the right mouse button to zoom. allowing you to zoom to an arbitrary point in the ﬁgure. They are used to navigate back and forth between previously deﬁned views. respectively. the y axis. dragging it to a new position. 19 . Forward and Back. Use the pan and zoom to rectangle to deﬁne new views. You can use the modiﬁer keys ‘x’. think web browser where data views are web pages. which can be used to navigate through the data set. If you press ‘x’ or ‘y’ while panning the motion will be constrained to the x or y axis.CHAPTER FOUR INTERACTIVE NAVIGATION All ﬁgure windows come with a navigation toolbar. With polar plots. the pan and zoom functionality behaves diﬀerently. When you release it. then put your mouse somewhere over an axes. 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. dragging it to a new position. Press the left mouse button and hold it to pan the ﬁgure. Home always takes you to the ﬁrst. The x axis will be zoomed in proportionate to the rightward movement and zoomed out proportionate to the leftward movement. default view of your data. The Pan/Zoom button This button has two modes: pan and zoom. respectively.

Put your mouse somewhere over and axes and press the left mouse button. 4. 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.0. Drag the mouse while holding the button to a new location and release. eps. top.*). There is also an experimental ‘zoom out to rectangle’ in this mode with the right button. You can save ﬁles with the following extensions: png. Interactive navigation . The Subplot-configuration button Use this tool to conﬁgure the parameters of the subplot: the left. space between the rows and space between the columns. The exact syntax depends on 20 Chapter 4. bottom.pyplot the toolbar will be created automatically for every ﬁgure. svg and pdf. you can add the toolbar as a widget. which will place your entire axes in the region deﬁned by the zoom out rectangle. The axes view limits will be zoomed to the rectangle you have deﬁned. If you are writing your own user interface code.Matplotlib. right. Release 1. ps. which can be overwritten by use of your matplotlibrc (#keymap.1 Navigation Keyboard Shortcuts The following table holds all the default keys. The Save button Click this button to launch a ﬁle save dialog.1 The Zoom-to-rectangle button Click this toolbar button to activate this mode.

Navigation Keyboard Shortcuts 21 .pack_start(canvas) toolbar = NavigationToolbar(canvas.connect("destroy".set_default_size(400.1.add_subplot(111) ax. Release 1.backends.VBox() win.backends.1 your UI. dpi=100) ax = fig.3]) canvas = FigureCanvas(fig) # a gtk. Here is some example code for GTK: from matplotlib.2. lambda x: gtk.DrawingArea vbox.Matplotlib.pack_start(toolbar.300) win.show_all() gtk.0. but we have examples for every supported UI in the matplotlib/examples/user_interfaces directory.figure import Figure from matplotlib.main_quit()) win. False. win) vbox.add(vbox) fig = Figure(figsize=(5.main() 4. False) win.set_title("Embedding in GTK") vbox = gtk.plot([1.4).backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar win = gtk.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas from matplotlib.Window() win.

Matplotlib. Interactive navigation .0. Release 1.1 22 Chapter 4.

this ﬁle will be overwritten.matplotlib/matplotlibrc. and maybe C:\Python25\Lib\site-packages on Windows.matplotlib directory location. where INSTALL is something like /usr/lib/python2. for example: import matplotlib as mpl mpl.rcParams[’lines. in the following order: 1.color’] = ’r’ 23 . for the user’s default customizations. axes.2 Dynamic rc settings You can also dynamically change the default rc settings in a python script or interactively from the python shell. usually used for speciﬁc customizations that you do not want to apply elsewhere.rcParams.matplotlib/matplotlibrc’ See below for a sample matplotlibrc ﬁle. To display where the currently active matplotlibrc ﬁle was loaded from.CHAPTER FIVE CUSTOMIZING MATPLOTLIB 5. 3. which we call rc settings or rc parameters. which is global to the matplotlib package. one can do the following: >>> import matplotlib >>> matplotlib.5/site-packages on Linux. 2. matplotlibrc in the current working directory. matplotlib looks for matplotlibrc in three locations.linewidth’] = 2 mpl. text and font properties and so on. please move this ﬁle to you .matplotlib_fname() ’/home/foo/. Every time you install matplotlib.rcParams[’lines. line width. . All of the rc settings are stored in a dictionary-like variable called matplotlib. INSTALL/matplotlib/mpl-data/matplotlibrc. color and style. axis and grid properties. rcParams can be modiﬁed directly. See .1 The matplotlibrc ﬁle matplotlib uses matplotlibrc conﬁguration ﬁles to customize all kinds of properties. You can control the defaults of almost every property in matplotlib: ﬁgure size and dpi. 5. so if you want your customizations to be saved.matplotlib directory.

If you edit it there. color=’r’) There matplotlib. or lines starting with a comment symbol. such as ff00ff or #ff00ff . please note that it will be overridden in your next install. This file is best viewed in a editor which supports python mode syntax highlighting. 0. or b . Other lines must have the format key : val # optional comment Colors: for the color values below. There is some degree of validation when setting the values of rcParams.0.Matplotlib. using keyword arguments: import matplotlib as mpl mpl. 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.rc() command can be used to modify multiple settings in a single group at once. linewidth=2.matplotlib/matplotlibrc (unix/linux like systems) and C:\Documents and Settings\yourname\.5. k. eg red. 0.1 A sample matplotlibrc ﬁle ### MATPLOTLIBRC FORMAT # # # # # # # # # # # # # # # # # # # # This is a sample matplotlib configuration file . Blank lines.1 Matplotlib also provides a couple of convenience functions for modifying rc settings. 5.a matplotlib color string. blue. see matplotlib.a legal html color name. Customizing matplotlib . you can either use .rcdefaults() command will restore the standard matplotlib default settings.rc(’lines’. as are trailing comments. 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. such as (1.75 . Release 1. If you want to keep a permanent local copy that will not be over-written.2. The matplotlib.you can find a copy of it on your system in site-packages/matplotlib/mpl-data/matplotlibrc.a hex string.0. place it in HOME/.0) . darkslategray #### CONFIGURATION BEGINS HERE # the default backend. are ignored.a scalar grayscale intensity such as 0.an rgb tuple.rcsetup for details.matplotlib (win32 systems). such as r.

Matplotlib.lines for more # information on line properties. This is where the matplotlib fonts.Text.g.0. Release 1.color : blue #lines.sourceforge. if it is not # present.g.g. or about 83% of the current font # size.facecolor : blue #patch. like polygons or # circles.edgecolor : black #patch.solid_joinstyle : miter # miter|round|bevel #lines. ’cursive’ (e.html for more # information on font properties. # ’fantasy’ (e. The 6 font properties used for font # matching are given below with their default values. and ’monospace’ (e.g.5 # the line width around the marker symbol #lines.sourceforge.patches # information on patch properties #patch. italic # or oblique. Helvetica). in points #lines.antialiased : True # render patches in antialised (no jaggies) ### FONT # # font properties used by text. # ’sans-serif’ (e.sourceforge. For # TrueType fonts. #lines. bitmaps.net/api/artist_api.markeredgewidth : 0. See # http://matplotlib. See # http://matplotlib. Courier). Zapf-Chancery).0 # line width in points #lines. Dynamic rc settings 25 .linewidth : 1. etc reside #datapath : /home/jdhunter/mpldata ### LINES # See http://matplotlib.linewidth : 1.antialiased : True # render lines in antialised (no jaggies) ### PATCHES # Patches are graphical objects that fill 2D space. # # The font.marker : None # the default marker #lines. Each of # these font families has a default list of font names in decreasing # order of priority associated with them. eg US/Central or Europe/Paris # Where your matplotlib data lives if you installed to a non-default # location.solid_capstyle : projecting # butt|round|projecting #lines.html#module-matplotlib.markersize : 6 # markersize.variant property has two values: normal or small-caps.style property has three values: normal (or roman).2.0 # edge width in points #patch. Times).dash_capstyle : butt # butt|round|projecting #lines. # # The font. Western). The oblique style will be used for italic. 5.g. which are scalable fonts.1 #timezone : UTC # a pytz timezone string.linestyle : # solid line #lines.net/api/artist_api.net/api/font_manager_api. # # The font.html#module-matplotlib.family property has five values: ’serif’ (e.dash_joinstyle : miter # miter|round|bevel #lines. small-caps is equivalent # to using a font size of ’smaller’.

. # computer modern sans serif. # 12pt is the standard value. Textile. PLEASE DO NOT ASK FOR HELP # IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO. palatino. Zapf Chancery. Charcoal.1 # # The font. Ava #font. ultra-expanded. bold. fantasy #font.size controls default text sizes. or smaller #font. # small. monospace.sourceforge.cursive : Apple Chancery. 900. See http://www.size. x-small. and narrower. semi-condensed. 300. computer modern roman. Impact. larger.text for more # information on text properties #text. Fixed ### TEXT # text properties used by text. # #font.serif : Bitstream Vera Serif. Customizing matplotlib . serif. bookman. wider. # zapf chancery. large. Lucid.variant : normal #font. Sand. times. semi-expanded. computer modern typewriter # If another font is desired which can loaded using the # LaTeX \usepackage command.Matplotlib.Text. ITC B #font. using the following values: xx-small. # expanded. etc. extra-expanded. axes. labels.usetex : False # use latex for all text handling. normal. # bolder. Arial. See # http://matplotlib.unicode : False # use "ucs" and "inputenc" LaTeX packages for handling # unicode strings. Verdana. medium. Geneva.size : 12.html#module-matplotlib. Courier..size property is the default font size for text.scipy.weight property has effectively 13 values: normal. courier. helvetica. This # property is not currently implemented. #text. Release 1.weight : medium #font. and bold is 700. see the rc # settings for axes and ticks. Andale Mono. Chicago. 26 Chapter 5.monospace : Bitstream Vera Sans Mono. Special text sizes can be defined # relative to font. given in pts. # # The font. title. Western.stretch : normal # note that font. bolder and lighter are relative values with # respect to the current weight. lighter. New Century Schoolbook. 200.preamble : # IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES # AND IS THEREFORE UNSUPPORTED. To configure # special text sizes tick labels. # # The font.color : black ### LaTeX customizations. xx-large. Nimbus Mono L. # extra-condensed.0 #font. Utopia. 100. condensed. Lucida Grande.org/Wiki/Cookbook/Matplotlib/UsingTex #text.sans-serif : Bitstream Vera Sans.latex. The following fonts # are supported through the usual rc parameter settings: # new century schoolbook. sans-serif. charter. Courier New.fantasy : Comic Sans MS... cursive #font. Helvetica. # avant garde.stretch property has 11 values: ultra-condensed.0. Normal is the same as # 400.net/api/artist_api.style : normal #font. x-large. please inquire at the # matplotlib mailing list #text.latex.family : sans-serif #font. Century Schoolbook L.

An example: text. depending on your font settings # # # # # # some versions of dvipng don’t handle alpha channel properly. Use True to correct and flush ~/.matplotlib/tex.fallback_to_cm : True # When True. so beware of package collisions: color.preamble : \usepackage{bm}.default : it # # # # The default font to use for math.html#module-matplotlib.rm : serif #mathtext.axes #axes. textcomp.2.dvipnghack : None preamble is a comma separated list of LaTeX statements that are included in the LaTeX document preamble.it : serif:italic #mathtext.labelcolor : black 5. # They map from a TeX font name to a fontconfig font pattern.fontset : cm # Should be ’cm’ (Computer Modern). default tick sizes.titlesize : large # fontsize of the axes title #axes. text will be hinted. ’stix’. See # http://matplotlib.edgecolor : black # axes edge color #axes.net/api/axes_api.facecolor : white # axes background color #axes.hinting : True # If True. use symbols from the Computer Modern # fonts when a symbol can not be found in one of # the custom math fonts.cache before testing and False to force correction off.Matplotlib. # These settings are only used if mathtext. Can be any of the LaTeX font names.labelsize : medium # fontsize of the x any y labels #axes. # affects the Agg backend.0. #mathtext. # The following settings allow you to select the fonts in math mode. # ’stixsans’ or ’custom’ #mathtext.1 # # # # # # # # #text. type1cm.sf : sans #mathtext.\usepackage{euler} The following packages are always loaded with usetex.sourceforge. otherwise not. # Note that this "custom" mode is unsupported and may go away in the # future.0 # edge linewidth #axes. Dynamic rc settings 27 .linewidth : 1. including the special name "regular" for the same font used in regular text. graphicx.hold : True # whether to clear the axes by default on #axes. #mathtext. Adobe Postscript (PSSNFS) font packages may also be loaded.bf : serif:bold #mathtext.cal : cursive #mathtext. geometry.grid : False # display grid or not #axes. # default fontsizes for ticklabels. None will try and guess based on your dvipng version This only #text. Release 1.fontset is ’custom’.latex. ### AXES # default face and edge color.tt : monospace #mathtext. and so on.

long name.size #ytick. y.axisbelow # whether axis gridlines and ticks are below # the axes elements (lines.5 #legend.direction : in # direction: in or out #ytick.major.fontsize : large #legend. r.size : 4 # major tick size in points #xtick.handletextsep : 0. k # color cycle for plot lines # as list of string colorspecs: # single letter.labelsize #ytick. use a rounded box for the # legend.size #ytick.isaxes : True #legend.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.size : 2 # minor tick size in points #xtick.grid #axes3d.minor. else a rectangle # the number of points in the legend line # deprecated.02 #legend.pad : 0. 7 # use scientific notation if log10 # of the axis range is smaller than the # first or larger than the second #axes.major.minor.05 #legend.labelsize : medium # fontsize of the tick labels #xtick.Tick #xtick.1 #axes.major.color_cycle : b.fancybox : : : black : 0.labelsep : 0. text. the fractional whitespace inside the legend border # border whitspace in fontsize units # the relative size of legend markers vs. 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. m.pad : 4 # distance to major tick label in points #xtick.handlelen : 0.minor. Release 1. etc) #axes.color #ytick.minor.net/api/axis_api.numpoints : 2 #legend.pad #ytick.major.color #grid.0 #legend.grid : True : True # display grid on polar axes # display grid on 3d axes : False ### TICKS # see http://matplotlib. c.markerscale : 1.Matplotlib.org/wiki/Plus_sign#Plus_sig #axes.pad : 4 # distance to the minor tick label in points #xtick.color : k # color of the tick labels #xtick.sourceforge. See http://en.unicode_minus : True # use unicode for the minus symbol # rather than hypen.axis.pad #ytick.linewidth ### Legend #legend.borderpad : 0. Customizing matplotlib .010 #legend.02 28 Chapter 5.0.5 # grid color # dotted # in points : False # if True. g. or # web-style hex #polaraxes.axespad : 0.0 # the following dimensions are #legend.formatter.wikipedia.linestyle #grid.html#matplotlib.limits : -7.

simplify : True # When True. 0.2 #figure.cmap : jet #image. 6 # figure size in inches #figure.0.1 #figure.125 #figure. values in the range # 10000 to 100000 can improve speed slightly # and prevent an Agg rendering failure # when plotting very large data sets.shadow : False ### FIGURE # See http://matplotlib.figsize : 8.subplot.2 ### IMAGES #image. Dynamic rc settings 29 . though. # the default savefig params can be different from the display params # Eg.resample : False ### CONTOUR PLOTS #contour. # especially if they are very gappy.bottom : 0.top : 0. When False.wspace : 0. you may want a higher resolution.9 #figure.subplot. Release 1.9 #figure.lut : 256 #image.figure.left : 0.75 is scalar gray #figure..subplot.Figure #figure. # paths will never be snapped. 2008/10/10 #agg.1 # The threshold of similarity below which # vertices will be removed in the simplification # process #path. or to make the figure # background white 5.right : 0. # figure width or height #figure. # A value of 20000 is probably a good # starting point.simplify_threshold : 0.subplot.origin : upper #image.dpi : 80 # figure dots per inch #figure.subplot.chunksize : 0 # 0 to disable.1 #legend.facecolor : 0..edgecolor : white # figure edgecolor # The figure subplot parameters.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.path. # It may cause minor artifacts. the size of the colormap lookup table lower | upper dashed # dashed | solid ### Agg rendering ### Warning: experimental. ### SAVING FIGURES #path.subplot. simplify paths by removing "invisible" # points to reduce file size and increase rendering # speed #path.75 # figure facecolor.interpolation : bilinear #image.snap : True # When True.sourceforge.2. rectilinear axis-aligned paths will be snapped to # the nearest pixel when certain criteria are met.Matplotlib.net/api/figure_api.html#matplotlib.aspect : equal #image.hspace : 0.

fonttype : 3 # Output Type 3 (Type3) or Type 42 (TrueType) # svg backend params #svg. pdf. If your setting is "debug". svg # tk backend params #tk.0. legal. Any level is # inclusive of all the levels below it.useafm : False #ps.stderr 30 Chapter 5. debug-annoying.facecolor #savefig.fileo : sys.edgecolor #savefig.compression : 6 # integer from 0 to 9 # 0 disables compression (good for debugging) #pdf. This controls how much information # matplotlib gives you at runtime and where it goes. # # The "fileo" gives the destination for any calls to verbose. eg --verbose-helpful. debug. A0-A10.usedistiller : False # Maintain shell focus for TkAgg #ps.distiller.image_noscale : False #svg. or a filehandle like sys. # you’ll get all the debug and helpful messages.stdout. helpful. letter.papersize : letter #ps. debug.res #ps. #verbose.stdout or sys.image_inline : True #svg.Matplotlib.level : silent # one of silent. debug-annoying #verbose. ghostscript or xpdf # Experimental: may produce smaller files. # but requires ghostscript.embed_char_paths : True # docstring params #docstring. Customizing matplotlib . B0-B10 # use of afm fonts. The verbosity # levels are: silent. # # You can access the verbose instance in your code # from matplotlib import verbose. sys.stdout # a log filename. xpdf and ps2eps # dpi # Output Type 3 (Type3) or Type 42 (TrueType) # pdf backend params #pdf. Release 1.1 #savefig. results in small files # can be: None. # xpdf intended for production of publication quality files. ps. or ’auto’ : png # png. # # 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. # These objects can a filename.report.window_focus : False # ps backend params #ps. please set verbose to "helpful" or "debug" # and paste the output into your report.fonttype : 6000 : 3 # auto. ledger. helpful.format : : : : 100 white white auto # # # # figure dots per inch figure facecolor when saving figure edgecolor when saving what extension to use for savefig(’foo’).dpi #savefig.extension #cairo.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. When submitting # problems to the mailing-list.

save : s #keymap. r. backspace #keymap. (i.yscale : l #keymap.download : True #examples.Matplotlib.pan : p #keymap. Release 1.grid : g #keymap. Dynamic rc settings 31 ..directory : ’’ 5. # Leave the field(s) empty if you don’t need a key-map.fullscreen : f #keymap.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.2.xscale : L.directory to the directory where you have a checkout of https://matplotlib. but sometimes you want to avoid that. Various examples download some data from the Matplotlib svn repository to avoid distributing extra files.0.zoom : o #keymap. In that case set examples.home : h.forward : right.sourceforge.back : left. k #keymap.svn.1 # Event keys to interact with figures/plots via keyboard. fullscreen : ’’) #keymap. home #keymap.e. v #keymap. # Customize these settings according to your needs.download to False and examples. c.net/svnroot/matplotlib/trunk/sample_data # False to bypass downloading mechanism # directory to look in if download is false #examples.

Customizing matplotlib .0.Matplotlib.1 32 Chapter 5. Release 1.

and you may not want to update the plot every time a single property is changed. ipython also turns on interactive mode for you.0 -. type ’help(pylab)’. because matplotlib is a graphical user interface application under the hood. 09:09:16) IPython 0. johnh@flag:~> ipython -pylab Python 2. Note in the example above that we did not import any matplotlib names because in pylab mode. an enhanced interactive python shell. and there are some tricks to make the applications work right in a python shell. In [1]: x = randn(10000) In [2]: hist(x. in practice it can be tricky. so when you start ipython in the pylab mode.CHAPTER SIX USING MATPLOTLIB IN A PYTHON SHELL By default. 6. ipython will turn oﬀ interactive mode during a run command. But when working from the python shell. For more information. ipython.5 (#4. a matplotlib-based Python environment. or the marker style of a line. after changing the xlabel(). Apr 12 2008. eg. and then restore the interactive state at the end of the run so you can continue tweaking the ﬁgure manually. and is matplotlib aware. which causes every pyplot command to trigger a ﬁgure update. ipython will import them automatically. call plot() and your data appears in the ﬁgure window. 33 . Call figure() and a ﬁgure window pops up. matplotlib defers drawing until the end of the script because drawing can be an expensive operation. and also provides a matplotlib aware run command to run matplotlib scripts eﬃciently. Welcome to pylab. has ﬁgured out all of these tricks.4. 100) it sets everything up for you so interactive plotting works as you would expect it to.1 Ipython to the rescue Fortunately.An enhanced Interactive Python. you usually do want to update the plot with every command. While this is simple in concept. only once after all the properties have changed.9.

then the ﬁgure state is updated on every plot command. with pylab support. interactive mode can be slow since it redraws the ﬁgure with each command. but will only be drawn on explicit calls to draw().1 There has been a lot of recent work to embed ipython. When interactive is True. The pyplot interface provides 4 commands that are useful for interactive control. isinteractive() returns the interactive setting True|False ion() turns interactive mode on ioff() turns interactive mode oﬀ draw() forces a ﬁgure redraw When working with a big ﬁgure in which drawing is expensive. color=’green’) draw() # force a draw savefig(’alldone’.0. 6. and still want to use matplotlib/pylab from an interactive python shell. you may want to turn matplotlib’s interactive setting oﬀ temporarily to avoid the performance hit: >>> >>> >>> >>> >>> >>> #create big-expensive-figure ioff() # turn updates off title(’now how much would you pay?’) xticklabels(fontsize=20. Using matplotlib in a python shell . eg the plainole standard python interactive interpreter. you are going to need to understand what a matplotlib backend is What is a backend?. Note. 6. then every pyplot command triggers a draw. ie when making ﬁgures from scripts. If interactive is False. so check on the ipython mailing list for the latest status. or the interpreter in your favorite IDE. Just set your backend : TkAgg and interactive : True in your matplotlibrc ﬁle (see Customizing matplotlib) and ﬁre up python. For other user interface toolkits and their corresponding matplotlib backends. into various GUI applications. the situation is complicated by the GUI mainloop which takes over the entire process.2 Other python interpreters If you can’t use ipython.2. and this is the tricky part that ipython solves for all the major toolkits that matplotlib supports.3 Controlling interactive updating The interactive property of the pyplot interface controls whether a ﬁgure canvas is drawn on every pyplot command. Then: >>> from pylab import * >>> plot([1. So you may want to think carefully before making this the default behavior. There are reports that upcoming versions of pygtk will place nicely with the standard python shell. Release 1. that uses the Tkinter user interface toolkit. in batch mode. With the TkAgg backend. dpi=300) 34 Chapter 6.Matplotlib. The solution is to run the GUI in a separate thread.3]) >>> xlabel(’hi mom’) should work out of the box. so stay tuned. you can use matplotlib from an arbitrary python shell.

mew=4. Controlling interactive updating 35 . ls=’--’. mfc=’g’. mec=’r’.0.Matplotlib.1 >>> close() >>> ion() # turn updating back on >>> plot(rand(20).3. ms=40. Release 1. lw=3) 6.

Using matplotlib in a python shell .1 36 Chapter 6.Matplotlib.0. Release 1.

• title() . The example below shows all of these commands in action. matplotlib. newline separated text with arbitrary rotations.annotate() in the API.axes.Figure. to support mathematical expressions anywhere in your ﬁgure.set_xlabel() in the API.Axes. and unicode support. text location and color. • figtext() .add a title to the Figure.font_manager.axes. including mathematical expressions. You have total control over every text property (font size. • ylabel() . what you see on the screen is what you get in the hardcopy.suptitle() in the API.Axes. truetype support for raster and vector outputs.2 Basic text commands The following commands are used to create text in the pyplot interface • text() .figure. 7. matplotlib.Axes.CHAPTER SEVEN WORKING WITH TEXT 7. matplotlib implements a large number of TeX math symbols and commands.axes.Text() instance. W3C compliant font ﬁnding algorithm.add an annotation.Figure.axes.text. matplotlib.Axes. • suptitle() . etc) with sensible defaults set in the rc ﬁle.add text at an arbitrary location to the Axes. font weight. matplotlib. matplotlib. that look good even at small raster sizes.add text at an arbitrary location to the Figure.text() in the API.1 Text introduction matplotlib has excellent text support. matplotlib.text() in the API. matplotlib includes its own matplotlib. • annotate() . which implements a cross platform.set_title() in the API.Axes. which can bew conﬁgured with a variety of font and other properties. matplotlib.figure. to the Axes . with optional arrow. Because we embed the fonts directly in the output documents.add an axis label to the x-axis.add a title to the Axes.add an axis label to the y-axis. freetype2 support produces very nice.set_ylabel() in the API. eg for postscript or PDF. thanks to Paul Barrett. And signiﬁcantly for those interested in mathematical or scientiﬁc ﬁgures. • xlabel() .axes. antialiased fonts. All of these functions create and return a matplotlib. 37 .

text(3.plot([2].text(0.95.axis([0.add_subplot(111) fig. unicode(’unicode: Institut f\374r Festk\366rperphysik’.annotate(’annotate’. 38 Chapter 7. Release 1. fontweight=’bold’) ax = fig. 10. 0.set_ylabel(’ylabel’) ax.suptitle(’bold figure suptitle’. horizontalalignment=’right’. 10]) plt. ’o’) ax. shrink=0.pyplot as plt fig = plt. ’pad’:10}) ax. xy=(2.coding: utf-8 -*import matplotlib.transAxes.01.show() 7.05)) ax.5. verticalalignment=’bottom’.3 Text properties and layout The matplotlib. [1].set_title(’axes title’) ax.Text instances have a variety of properties which can be conﬁgured via keyword arguments to the text commands (eg title(). ’boxed italics text in data coords’. Working with text . 2. 8. 4). 0.text(3.set_xlabel(’xlabel’) ax. fontsize=14. xlabel() and text()).0. transform=ax. fontsize=15) ax. arrowprops=dict(facecolor=’black’. 1). ’colored text in axes coords’. style=’italic’.text. ’latin-1’)) ax.text(2. r’an equation: $E=mc^2$’.1 # -*. 6. ’alpha’:0. xytext=(3.85) ax. bbox={’facecolor’:’red’.Matplotlib. fontsize=15) ax.figure() fig. color=’green’.subplots_adjust(top=0.

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 ﬂoat 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’..transform.FontProperties instance horizontalalignment or ha [ ‘center’ | ‘right’ | ‘left’ ] label any string linespacing ﬂoat multialignment [’left’ | ‘right’ | ‘center’ ] name or fontname string eg. Release 1.transform transformation instance variant [ ‘normal’ | ‘small-caps’ ] verticalalignment or va [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] visible [True 7.3. ‘x-large’ ] style or fontstyle [ ‘normal’ | ‘italic’ | ‘oblique’] text string or anything printable with ‘%s’ conversion transform a matplotlib.Bbox instance clip_on [True | False] clip_path a Path instance and a Transform instance..0.font_manager. a Patch color any matplotlib color family [ ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] fontproperties a matplotlib.Matplotlib.] picker [None|ﬂoat|boolean|callable] position (x. [’Sans’ | ‘Courier’ | ‘Helvetica’ . Text properties and layout | False] weight or fontweight [ ‘normal’ | ‘bold’ | ‘heavy’ | ‘light’ | ‘ultrabold’ | ‘ultralight’] x ﬂoat y ﬂoat 39 .

1 the upper right. ’center top’. .text(right.transAxes) ax. verticalalignment=’top’. top. horizontalalignment=’left’. verticalalignment controls whether the y positional argument for the text indicates the bottom.Rectangle( (left. height.add_axes([0.patches as patches # build a rectangle in axes coords left.5 right = left + width top = bottom + height fig = plt.transAxes) ax. transform=ax.1]) # axes coordinates are 0.25. width = . transform=ax.0.add_patch(p) ax. transform=ax. fill=False. verticalalignment=’top’.pyplot as plt import matplotlib. transform=ax.transAxes) ax.figure() ax = fig.Matplotlib. ’right top’.transAxes) 40 Chapter 7.transAxes throughout the code indicates that the coordinates are given relative to the axes bounding box. Release 1. ’right bottom’.5 bottom.1 is upper right p = patches. verticalalignment. ’left top’. with 0. clip_on=False ) ax. bottom). import matplotlib. ’left bottom’. bottom. Here is an example which uses the text() command to show the various alignment possibilities. transform=ax. Working with text . center or right justiﬁed. horizontalalignment=’left’.1. . verticalalignment=’bottom’.text(left. verticalalignment=’top’. The use of transform=ax.1 You can layout text with the alignment arguments horizontalalignment.text(right. and multialignment. verticalalignment=’bottom’. center or top side of the text bounding box. controls whether the diﬀerent lines are left. horizontalalignment=’center’.0 being the lower left of the axes and 1. horizontalalignment controls whether the x positional argument for the text indicates the left.text(right. top. transform=ax.text(left. width. multialignment.25. horizontalalignment=’right’. height = . center or right side of the text bounding box.transAxes) ax. horizontalalignment=’right’.transAxes. bottom. for newline separated strings only.0 is bottom left and 1.0. bottom.

text(right.5*(bottom+top). layout engine and fonts.text(left. The layout engine is a fairly direct adaptation of the layout algorithms in Donald Knuth’s TeX. ’left center’. if you use the STIX fonts you should also set ps.text(left. ’right center’. Regular text and mathtext can be interleaved within the same string. horizontalalignment=’center’. top. verticalalignment=’center’. rotation=’vertical’.5*(bottom+top).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 ($). ’rotated\nwith newlines’. rotation=’vertical’. ’middle’. You should use raw strings (preceed the quotes with an ’r’). rotation=’vertical’.transAxes) ax. verticalalignment=’center’. 0.5*(bottom+top). Mathtext can use the Computer Modern fonts (from (La)TeX). 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). 0.fonttype to 3 (the default).0. rotation=45. verticalalignment=’center’.transAxes) ax.transAxes) ax. as in TeX.5*(left+right). Otherwise some characters will not be visible. Any text element can use math text.set_axis_off() plt. not 42. Note that you do not need to have TeX installed.text(0. 0. horizontalalignment=’center’. horizontalalignment=’center’.4. horizontalalignment=’left’.1 ax. transform=ax. The mathtext font can be selected with the customization variable mathtext. 7. transform=ax.show() 7.Matplotlib. color=’red’.5*(bottom+top). verticalalignment=’center’.fonttype and pdf. and surround the math text with dollar signs ($). Writing mathematical expressions 41 .transAxes) ax. verticalalignment=’center’. fontsize=20. transform=ax.fontset (see Customizing matplotlib) Note: On “narrow” builds of Python. ’centered’. transform=ax. transform=ax. since matplotlib ships its own TeX expression parser.transAxes) ax.text(left. horizontalalignment=’right’. STIX fonts (with are designed to blend well with Times) or a Unicode font that you provide. 0. Release 1.

Working with text centered . To make it easy to display monetary values.title(r’$\alpha > \beta$’) produces “α > β”.00”. Release 1. if a single dollar sign is present in the entire string. Note: Mathtext should be placed between a pair of dollar signs ($). the text outside does not. This is a small change from regular TeX. Whereas this: # math text plt. “$100.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. See the usetex tutorial for more information. it will be displayed verbatim as a dollar sign.title(’alpha > beta’) produces “alpha > beta”. 42 Chapter 7. these characters will behave diﬀerently depending on the rcParam text. where the dollar sign in non-math text would have to be escaped (‘$’). Therefore.g.Matplotlib.usetex ﬂag. characters such as: # $ % & ~ _ ^ \ { } \( \) \[ \] have special meaning outside of math mode in TeX. In particular. Note: While the syntax inside the pair of dollar signs ($) aims to be TeX-like. e.0.

Matplotlib. to write the sum of xi from 0 to ∞. For example.2 Fractions.4.\frac{1}{x}}{4}$’ (7. Writing mathematical expressions (7.2) 7. Release 1. Doing things the obvious way produces brackets that are too small: r’$(\frac{5 .6) 43 .4. \binom{}{} and \stackrel{}{} commands.0.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})$’ 5− 1 x ) (7. you could do: r’$\sum_{i=0}^\infty x_i$’ ∞ xi i=0 (7.1) Some symbols automatically put their sub/superscripts under and over the operator. binomials and stacked numbers Fractions.4) 4 Note that special care needs to be taken to place parentheses and brackets around fractions.3) produces 5− 1 x (7. binomials and stacked numbers can be created with the \frac{}{}.1 7. 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 .4.1 Subscripts and superscripts To make subscripts and superscripts.\frac{1}{x}}{4}\right)$’ 1 x 5 − 4 7. use the ’_’ and ’^’ symbols: r’$\alpha_i > \beta_i$’ αi > βi (7.

to use the same font as regular non-math text for math text. Note in the example above the caligraphy A is squished into the sin. For example: r’$\sqrt{2}$’ √ 2 (7.9) More conveniently.1 7.4.Matplotlib. for example.0.3 Radicals Radicals can be produced with the \sqrt[]{} command. Release 1. This is useful.7) Any base can (optionally) be provided inside square brackets. and the amplitude “A” is in calligraphy font.4 Fonts The default font is italics for mathematical symbols.default rcParam. and can not contain layout commands such as fractions or sub/superscripts: r’$\sqrt[3]{x}$’ √ 3 x (7. many commonly used function names that are typeset in a Roman font have shortcuts. eg.10) Here “s” and “t” are variable in italics font (default). To change fonts. by setting it to regular. Note that the base must be a simple expression. enclose the text in a font command: r’$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$’ s(t) = Asin(2ωt) (7.11) Result Roman Italic Typewriter CALLIGRAPHY Chapter 7. 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. “sin” is in Roman font.8) 7.4. to write “sin” in a Roman font. 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. Note: This default can be changed using the mathtext. Working with text .

There are a number of limitations to this approach. which are selected using the mathtext. you can then set the following parameters. which control which font ﬁle to use for a particular set of math characters. Writing mathematical expressions 45 . By setting the rcParam mathtext.fontset parameter in matplotlibrc.. 7. cm: Computer Modern (TeX) stix: STIX (designed to blend well with Times) stixsans: STIX sans-serif Additionally. Release 1. 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. and should be considered an experimental feature for patient users only. you can use \mathdefault{.4. This method is fairly tricky to use.1 When using the STIX fonts.fontset to custom.} or its alias \mathregular{. but it can be useful to make math expressions blend well with other text in the plot.} to use the font used for regular text outside of mathtext.Matplotlib.0.... Custom fonts mathtext also provides a way to use custom fonts for math. most notably that far fewer symbols will be available.

Note that the math glyphs speciﬁed in Unicode have evolved over time.12) 7. The fonts used should have a Unicode mapping in order to ﬁnd any non-Latin characters. such as Greek. If you want to use a math symbol that is not contained in your custom fonts.it mathtext.tt mathtext. \leftarrow. There are long and short forms for some of them.0.5 Accents An accent command may precede any symbol to add an accent above it. 7. \int.1 Parameter mathtext.Matplotlib. 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. Command \acute a or \’a \bar a \breve a \ddot a or \"a \dot a or \.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 fontconﬁg font descriptor (as deﬁned in the yet-to-be-written font chapter). you can set the rcParam mathtext.4. Working with text .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. 46 Chapter 7.cal mathtext.rm mathtext.6 Symbols You can also use a large number of the TeX symbols.4. and many fonts may not have glyphs in the correct place for mathtext.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. Note that in the following \imath is used to avoid the extra dot over the i: r"$\hat i\ \ \hat \imath$" ˆ ı i ˆ (7.bf mathtext. Release 1. as in \infty. \sum.

Release 1.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.Matplotlib.0. Writing mathematical expressions 47 .

Release 1. Working with text .0.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.

Writing mathematical expressions . Release 1.4.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.

0. \vdots . . Unicode characters can also be used: ur’$\u23ce$’ 50 Chapter 7.. Release 1.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 . . \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 . .Matplotlib. Working with text . \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).

title(r’$\alpha_i > \beta_i$’. r’$\sum_{i=0}^\infty x_i$’.01) s = np.text(1. fontsize=20) plt.arange(0.0 0. Release 1.5 2.5 Text rendering With LaTeX Matplotlib has the option to use LaTeX to manage all text layout.xlabel(’time (s)’) plt. 2. fontsize=20) plt.6. fontsize=20) plt.4.5 1. 0.0 7.pyplot as plt t = np. r’$\mathcal{A}\mathrm{sin}(2 \omega t)$’.0 time (s) xi 1. import numpy as np import matplotlib.s) plt.Matplotlib.5.0.0 0. Text rendering With LaTeX 51 .plot(t.5 volts (mV) 0.0 0.pi*t) plt.sin(2*np.text(0. This option is available with the following backends: • Agg 7. 0.ylabel(’volts (mV)’) 1.1 7. -0.0.7 Example Here is an example illustrating many of these features in context.6.6.0 αi >βi Asin(2ωt) ∞ i =0 0.5 1.0.

savefig. the Computer Modern fonts are used by default.cursive font. Release 1. xlabel.sf.**{’family’:’serif’. the run may be silent.’sans-serif’:[’Helvetica’]}) ## for Palatino and other serif fonts use: #rc(’font’. which can be changed using rc settings. since diﬀerent LaTeX packages (font packages. show 52 Chapter 7.net/matplotlib. \ grid.html properly installed on your system. dvipng (which may be included with your LaTeX installation).60 or later is recommended).tex.pyplot import figure. If the fonts are not speciﬁed. Computer Modern Typewriter : true The ﬁrst valid font in each family is the one that will be loaded.py: #!/usr/bin/env python """ You can use TeX to render all of your matplotlib text if the rc parameter text. and Ghostscript (GPL Ghostscript 8.’serif’:[’Palatino’])) rc(’text’. Text handling with matplotlib’s LaTeX support is slower than matplotlib’s very capable mathtext. Here is an example matplotlibrc ﬁle: font. Times and Palatino each have their own accompanying math fonts. There are a couple of options to mention.usetex is set. This works currently on the agg and ps backends. plot. ylabel. but is more ﬂexible. The results can be striking. as a lot of the information is cached in ~/.family font. title. Avant Garde. without editing matplotlibrc use: from matplotlib import rc rc(’font’.**{’family’:’sans-serif’. while the other Adobe serif fonts make use of the Computer Modern math fonts.monospace text.Matplotlib.texmanager.) can be used. The next time.serif font. To use LaTeX and select Helvetica as the default font. math packages. axes. Working with text .sans-serif font. All of the other fonts are Adobe fonts. pi from matplotlib. See the PSNFSS documentation for more details. New Century Schoolbook. usetex=True) Here is the standard example.usetex : : : : : serif Times. and requires that you have tex and the other dependencies described at http://matplotlib. tex_demo.usetex : True in your rc settings. cos. Matplotlib’s LaTeX support requires a working LaTeX installation.0. The executables for these external dependencies must all be located on your PATH. Bookman. etc. especially when you take care to use the same fonts in your ﬁgures as in the main document. Computer Modern Sans serif Zapf Chancery Courier.cache """ from matplotlib import rc from numpy import arange.1 • PS • PDF The LaTeX option is activated by setting text. The first time you run a script you will see a lot of output from tex and associated tools. Computer Modern Roman Helvetica. Palatino.

Matplotlib. Release 1.1.fontsize=16) title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!".0. will produce the same results. figsize=(6.py.7]) t = arange(0. Note: Certain characters require special escaping in TeX.8 1.4)) ax = axes([0. but adding the command \displaystyle. 0.0 1. 0. s) xlabel(r’\textbf{time (s)}’) ylabel(r’\textit{voltage (mV)}’. as in tex_demo.1 rc(’text’.0. usetex=True) rc(’font’.01. these characters will behave diﬀerently depending on the rcParam text.0+0. fontsize=16. 7.0 ∞ n=1 −eiπ ! 2n voltage (mV) 2. 0.6 0. such as: # $ % & ~ _ ^ \ { } \( \) \[ \] Therefore.4 time (s) 0. Text rendering With LaTeX 53 .5 1. color=’r’) grid(True) savefig(’tex_demo’) show() TEX is Number 3.5.2 0. 0.usetex ﬂag.1.0 0. family=’serif’) figure(1. 1.0 0.5 2.0 Note that display math mode ($$ e=mc^2 $$) is not supported.01) s = cos(2*2*pi*t)+2 plot(t.8.

ylabel. xlabel. color=’r’) grid(True) show() 7.Matplotlib.5. can be edited in Adobe Illustrator.5.1.5.py: #!/usr/bin/env python # -*.0. """ from matplotlib import rcParams rcParams[’text. One workaround is to to set ps. cos. fontsize=16) title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!". axes.py modified to have unicode. See that file for more information.0.res to a higher value (perhaps 6000) in your rc settings. 0. which are not scalable like standard postscript. 54 Chapter 7. 0. and searched text in pdf documents. the default behavior of matplotlib is to distill the output.usetex’]=True rcParams[’text. \ grid. figsize=(6. fontsize=16.7]) t = arange(0. Working with text . so it scales properly. which will produce larger ﬁles but may look better and scale reasonably.01.0+0. can be activated by changing the ps. savefig. 7. This step produces results which may be unacceptable to some users. 0.3 Possible hangups • On Windows. which requires Poppler or Xpdf. plot. which removes some postscript operators used by LaTeX that are illegal in an eps ﬁle.distiller. 1.1. This alternative produces postscript without rasterizing text. See environment-variables and setting-windowsenvironment-variables for details.2 Postscript options In order to produce encapsulated postscript ﬁles that can be embedded in a new LaTeX document.latex. pi from matplotlib.coding: utf-8 -*""" This demo is tex_demo. 0. s) xlabel(r’\textbf{time (s)}’) ylabel(ur’\textit{Velocity (\u00B0/sec)}’. show figure(1. because the text is coarsely rasterized and converted to bitmaps.unicode’]=True from numpy import arange.1 7.4)) ax = axes([0. here is an example taken from tex_unicode_demo. the PATH environment variable may need to be modiﬁed to include the directories containing the latex. A better workaround.8. and the text is not searchable. dvipng and ghostscript executables.01) s = cos(2*2*pi*t)+2 plot(t. Release 1.1 usetex with unicode It is also possible to use unicode strings with the LaTeX text manager.usedistiller rc setting to xpdf. title.pyplot import figure.

This allows latex to be used for text layout with the pdf and svg backends. 7.1 TEX is Number 3.5.4 Troubleshooting • Try deleting your . go to MiKTeX/Options and update your format ﬁles • The fonts look terrible on screen.dvipnghack : True in your matplotlibrc ﬁle.5. see . please try upgrading to the latest release before reporting problems to the list.cache directory. a latex installation may be the only external dependency. and there is some funny business with older versions of dvipng on the mac.0 0. Set text. If possible. if you get odd *Agg and PNG results.2 0.0. • On Ubuntu and Gentoo. Release 1.5 2.6 0. • Most problems reported on the mailing list have been cleared up by upgrading Ghostscript.Matplotlib.0 0. In the future.matplotlib directory location. • Some progress has been made so matplotlib uses the dvi ﬁles directly for text layout.0 ∞ n=1 −eiπ ! 2n Velocity (°/sec) 2.0 1. You are probably running Mac OS. that your LaTeX syntax is valid and that you are using raw strings if necessary to avoid unintended escape sequences.4 time (s) 0. If you don’t know where to ﬁnd • Make sure LaTeX. . as well as the *Agg and PS backends. • Make sure what you are trying to do is possible in a LaTeX document. dvipng and ghostscript are each working and on your PATH.matplotlib/tex. 7.5 1. You may need to install some of the extra packages to get all the goodies that come bundled with other latex distributions.8 1.0 • Using MiKTeX with Computer Modern fonts. Text rendering With LaTeX 55 . the base texlive install does not ship with the type1cm package.matplotlib.

both the xy (arrow tip) and xytext locations (text location) are in data coordinates. Both of these arguments are (x.show() In this example.0.6 Annotating text For a more detailed introduction to annotations.arange(0. arrowprops=dict(facecolor=’black’. 0. In an annotation. xycoords=’data’. please see Report a problem 7. and the annotate() method provides helper functionality to make annotations easy.0. right points from lower left corner of axes pixels from lower left corner of axes 0.0 is lower left of ﬁgure and 1.8.set_ylim(-2. import numpy as np import matplotlib. shrink=0.1 is upper. there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext.figure() ax = fig. xytext=(3.95).1 is upper right use the axes data coordinate system For example to place the text coordinates in fractional axes coordinates. see Annotating Axes. one could do: ax.cos(2*np. The uses of the basic text() command above place text at an arbitrary position on the Axes. 56 Chapter 7. xytext=(0.plot(t. shrink=0.5). xy=(2. lw=2) ax.pi*t) line. textcoords=’axes fraction’.pyplot as plt fig = plt.1 is lower left of axes and 1.01) s = np. xy=(3. ) ax.2) plt. Working with text .add_subplot(111) t = np.latex. 5.05).Matplotlib. 1.1 • The text.0. Release 1. • If you still need help. Please disable this option before reporting problems to the mailing list. and lots of ways to cause problems. 0.preamble rc setting is not oﬃcially supported. A common use case of text is to annotate some feature of the plot. 1).05).annotate(’local max’. = ax. s. This option provides lots of ﬂexibility.y) tuples. 1). arrowprops=dict(facecolor=’black’.annotate(’local max’. 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 ‘ﬁgure points’ ‘ﬁgure pixels’ ‘ﬁgure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ coordinate system points from the lower left corner of the ﬁgure pixels from the lower left corner of the ﬁgure 0.

verticalalignment and fontsize are passed from the ‘~matplotlib. radius) space.0 0.5 0.0 0.0 1.pyplot as plt 7. Release 1.annotate‘ to the ‘‘Text instance import numpy as np import matplotlib. For a polar axes.Axes.Text keyword args like horizontalalignment. 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. matplotlib.g. however. The text in this example is placed in the fractional ﬁgure coordinate system.text. e. top) of the ﬁgure or axes.1 2. Optionally. this is in (theta. facecolor In the example below. left) of the ﬁgure or axes.5 2.0 1.00 1 2 3 4 5 local max horizontalalignment=’right’. the xy point is in native coordinates (xycoords defaults to ‘data’).6.patches. verticalalignment=’top’. 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. If the value is negative.Polygon.5 1. Annotating text 57 .0. analogous to negative indexing of sequences.Matplotlib. the origin is from the (right.5 1. ) For physical coordinate systems (points or pixels) the origin is the (bottom.

58 Chapter 7. color=’#ee8d18’.Matplotlib. verticalalignment=’bottom’. # theta. shrink=0. theta[ind] ax.pi*r line.0.0. radius xytext=(0. [thisr].figure() ax = fig.1 fig = plt. = ax.05). Release 1.1.arange(0. ’o’) ax. horizontalalignment=’left’.add_subplot(111. including fancy arrows.4 225° a polar annotation 270° 315° For more on all the wild and wonderful things you can do with annotations. fraction textcoords=’figure fraction’. thistheta = r[ind].2 0.plot([thistheta].6 45° 0.05. Working with text .show() 90° 135° 0.0 0° 180° 0. xy=(thistheta.05). 0.annotate(’a polar annotation’. thisr).001) theta = 2*2*np. polar=True) r = np. see Annotating Axes and pylab_examples-annotation_demo.plot(theta. ) plt.8 1. # fraction. lw=3) ind = 800 thisr. arrowprops=dict(facecolor=’black’. r.

The commands shown below fall back on PIL if the native read fails. Natively. you’ll need to have access to the imshow() function. 8.1 Startup commands At the very least. The more expressive. but keep that PIL requirement in mind for your own data. etc. See also Pyplot tutorial.. matplotlib only supports PNG images.” preﬁxes.pyplot as plt In [2]: import matplotlib. There are a couple of ways to do it.2 Importing image data into Numpy arrays Plotting image data is supported by the Python Image Library (PIL). The image used in this example is a PNG ﬁle. The easy way for an interactive environment: $ipython -pylab The imshow function is now directly accessible (it’s in your namespace).. if you use the -pylab method. In [1]: import matplotlib. Here’s the image we’re going to play with: 59 .” and “plt. . you can skip the “mpimg.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. In these examples.CHAPTER EIGHT IMAGE TUTORIAL 8. for clarity.

0.42745098].42745098]. 0.. 0.40784314].0. . 0.. 0.40784314]. [ 0. [ 0.41176471. Depending on where you get your data.41176471. 60 Chapter 8..40784314. 0. 0. [ 0.42745098. 0. [ 0. And here we go. which allow for transparency.42745098. [ 0. Release 1. In [4]: img=mpimg..42745098].41176471]. 0. [ 0.42745098]].42745098.41176471.41176471.41176471].41176471]. 0. 0. 0.1 It’s a 24-bit RGB PNG image (8 bits for each of R. Image tutorial .42745098.42745098. 0.Matplotlib.42745098. 0. .40784314. 0. B). 0. 0. [ 0. [ 0. 0.40784314].40784314.41176471.png’) Out[4]: array([[[ 0.41176471.42745098..40784314. 0. G.42745098. 0.40784314.42745098..40784314. or singlechannel grayscale (luminosity) images.imread(’stinkbug. 0. [ 0.42745098]. [ 0.. 0.42745098..42745098]].42745098. 0. the other kinds of image that you’ll most likely encounter are RGBA images. 0. [[ 0.42745098. You can right click on it and choose “Save image as” to download it to your computer for the rest of this tutorial.

43137255.43137255]]. Plotting numpy arrays as images 61 .4509804 . [ 0.43137255. 0.44705883.44705883]. not a 3-D array). dtype=float32) Note the dtype there . 0.41568628. [[ 0. 0. 0. 0.43137255.44313726]]]. As a side note. [ 0. 0. 0. 0. with an RGB image.44313726]. you need to rescale it. In Matplotlib. [ 0. 0. 0. 0.43921569]. 0. [ 0.4509804 . Here.43137255. For grayscale. If your array data does not meet one of these descriptions. 0. This object 8.43921569.4509804 ]].4509804 . For RGB and RGBA images.45490196. 0.44705883]].44705883]. Release 1.0. 0.4509804 .44313726. 0.44705883. [ 0.44313726. [ 0. Since it’s a black and white image. 0.41568628]. you have your data in a numpy array (either by importing it.. 0.44313726. 0. [ 0.4509804 . More here (from a photography standpoint): Luminous Landscape bit depth tutorial.44705883.41568628. and B are all similar.4509804 .44705883. 0.4509804 . Matplotlib plotting can handle ﬂoat32 and uint8..43921569]. 0. Here we’ll grab the plot object. [ 0. Each inner list represents a pixel. [ 0.44313726. 0. 0..43137255.3. Why can they only render 8 bits/channel? Because that’s about all the human eye can see.44705883]. 0.4509804 ].. or by generating it).. 0.44705883.43921569. 0.44313726. [[ 0.. . or transparency). [ 0. the only datatype that PIL can work with is uint8. 0. 0. [[ 0.44313726]. 0. 0. 0.43137255.45490196]. 0.41568628]. 0.. 0.3 Plotting numpy arrays as images So.ﬂoat32.44313726]. R.43137255]. 0. . [ 0.4509804 ]. there are 3 values. but image reading/writing for any format other than PNG is limited to uint8 data. [ 0.43529412. 0. 0.. and a simple luminance image just has one value (and is thus only a 2-D array.0 and 1.43529412.. 0.Matplotlib. this is performed using the imshow() function.0.41568628.44313726...4509804 . .43137255.43921569. 0. [ 0. 8. [ 0. has 4 values per inner list.44705883.4509804 ]. [ 0. 0.41568628.4509804 ]. 0. Let’s render it. Why 8 bits? Most displays can only render 8 bits per channel worth of color gradation. Matplotlib has rescaled the 8 bit data from each channel to ﬂoating point data between 0.43921569.. 0. 0. . 0.43137255. An RGBA (where A is alpha.45490196. [ 0. 0. 0.4509804 .1 [[ 0. [ 0.41960785.41960785.44705883... [ 0.4509804 . . [ 0.41960785]. 0. 0.43529412]. matplotlib supports only ﬂoat32.44313726. [ 0.44313726.44705883.43137255]. matplotlib supports ﬂoat32 and uint8 data types. G..43137255].

1 Applying pseudocolor schemes to image plots Pseudocolor can be a useful tool for enhancing contrast and visualizing your data more easily.imshow(lum_img) 62 Chapter 8. Pseudocolor is only relevant to single-channel. This is especially useful when making presentations of your data using projectors .:.0. We currently have an RGB image.1 gives you an easy way to manipulate the plot from the prompt.just remember that the datatype must be ﬂoat32 (and range from 0. Since R. luminosity images. In [7]: imgplot = mpimg.0) or uint8. grayscale. Release 1.imshow(img) 0 50 100 150 200 250 300 350 0 100 200 300 400 You can also plot any numpy array . In [5]: imgplot = plt. Image tutorial . 8.0] This is array slicing. You can read more in the Numpy tutorial. we can just pick on channel of our data: In [6]: lum_img = img[:. G.their contrast is typically quite poor.0 to 1.3.Matplotlib. and B are all similar (see for yourself above or in your data).

1 0 50 100 150 200 250 300 350 0 100 200 300 400 Now. Release 1. LUT). the default colormap (aka lookup table.you have to re-create your plot. We can do that by adding color bars.set_cmap(’spectral’) There are many other colormap schemes available.3. 8. is applied. See the list and images of the colormaps. with a luminosity image. It’s as easy as one line: In [10]: plt. 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. and add in the colorbar again.colorbar() This adds a colorbar to your existing ﬁgure. The default is called jet.set_cmap(’hot’) In [9]: imgplot.0.3. 8.Matplotlib. Plotting numpy arrays as images 63 . This won’t automatically change if you change you switch to a diﬀerent colormap .2 Color scale reference It’s helpful to have an idea of what value a color represents.

In our histogram. Image tutorial . or expand the contrast in a particular region while sacriﬁcing the detail in colors that don’t vary much.7) 8. but you want the same information. Interpolation is how you ﬁll that space. Release 1.flatten(). ec=’k’) Most often. 256.0.3 Examining a speciﬁc data range Sometimes you want to enhance the contrast in your image. In[11]: imgplot.Matplotlib. the “interesting” part of the image is around the peak. so that we eﬀectively “zoom in on” part of the histogram.set_clim=(0.3. The number of pixels change.1. Let’s adjust the upper limit.hist(lum_img. and you can get extra contrast by clipping the regions above and/or below the peak. Since pixels are discrete.0. fc=’k’. it looks like there’s not much useful information in the high end (not many white things in the image).4 Array Interpolation schemes Interpolation calculates what the color or value of a pixel “should” be. One common place that this happens is when you resize an image. there’s missing space. A good tool to ﬁnd interesting regions is the histogram. This is why your images sometimes come out looking pixelated when you blow them up.0. range=(0. The eﬀect is more pronounced when the diﬀerence between the original image and the expanded image 64 Chapter 8. To create a histogram of our image data.3. or don’t matter. according to diﬀerent mathematical schemes.0. We do this by calling the set_clim() method of the image plot object.1 0 50 100 150 200 250 300 350 0 100 200 300 400 8.0). In[10]: plt. we use the hist() function.

size[1]/10)) # Use PIL to resize [11]: rsizeArr = np. We’re eﬀectively discarding pixels.people tend to prefer blurry over pixelated.Matplotlib.resize((img. and the computer has to draw in pixels to ﬁll that space. bilinear. that data gets blown up to the size on your screen.0.img. The old pixels aren’t there anymore. Let’s take our image and shrink it. 8. Plotting numpy arrays as images 65 . since we did not give imshow() any interpolation argument.set_interpolation(’nearest’) In [10]: imgplot.imshow(rsizeArr) Here we have the default interpolation.3. Release 1.size[0]/10.open(’stinkbug.set_interpolation(’bicubic’) Bicubic interpolation is often used when blowing up photos . Let’s try some others: In [10]: imgplot.asarray(rsize) # Get array back [12]: imgplot = mpimg.1 0 50 100 150 200 250 300 350 0 100 200 300 400 is greater. In In In In In [8]: import Image [9]: img = Image. only keeping a select few.png’) # Open image as PIL image object [10]: rsize = img. Now when we plot it.

7 0. Image tutorial .1 0 50 100 150 200 250 300 350 0 0.0 66 Chapter 8.4 0.5 0.3 0.8 0.0.2 100 200 300 400 0.1 0.Matplotlib.6 0. Release 1.

3.1 10000 8000 6000 4000 2000 0 0. Release 1.0.0 8.Matplotlib.8 1.4 0.2 0. Plotting numpy arrays as images 67 .6 0.0 0.

7 68 Chapter 8.5 0.Matplotlib.1 0.3 0. Release 1.0.1 0.7 After 0 50 100 150 200 250 300 350 0 100 200 300 400 0. Image tutorial .5 0.1 Before 0 50 100 150 200 250 300 350 0 100 200 300 400 0.3 0.

Plotting numpy arrays as images 69 . Release 1.Matplotlib.0.1 0 5 10 15 20 25 30 35 0 10 20 30 40 8.3.

Release 1. Image tutorial .1 0 5 10 15 20 25 30 35 0 10 20 30 40 70 Chapter 8.0.Matplotlib.

3. Plotting numpy arrays as images 71 . Release 1.Matplotlib.1 0 5 10 15 20 25 30 35 0 10 20 30 40 8.0.

Image tutorial .Matplotlib. Release 1.0.1 72 Chapter 8.

artist.backend_bases. 0.CHAPTER NINE ARTIST TUTORIAL There are three layers to the matplotlib API. and lines. text.. width. imshow()) to create the most common graphics primitives (Line2D. respectively).7.pyplot. The primitives represent the standard graphical objects we want to paint onto our canvas: Line2D. Line2D). etc. hist(). Text. height] values in 0-1 relative ﬁgure coordinates: fig2 = plt. use the Figure to create one or more Axes or Subplot instances. As we will discuss below.Artist is the object that knows how to use a renderer to paint onto the canvas. and draw them when requested.1.figure() ax2 = fig2. There are two types of Artists: primitives and containers. which is just a special case of an Axes that lives on a regular rows by columns grid of Subplot instances. first plot The Axes is probably the most important class in the matplotlib API.15. and the Artist handles all the high level constructs like representing and laying out the ﬁgure. and the Axes has many special helper methods (plot(). The matplotlib. and the matplotlib. 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. we create a Figure instance using matplotlib.backend_bases. one column. If you want to create an Axes at an arbitrary location. bottom. and the one you will be working with most of the time. numpy arrays and strings) and create primitive Artist instances as needed (eg. the matplotlib. PDF Gtk+. Text. In the example below.figure().3]) Continuing with our example: 73 .1. The standard use is to create a Figure instance. Axes and Figure). Image. This is because the Axes is the plotting area into which most of the objects go.1) # two rows. and use the Axes instance helper methods to create the primitives. Most of you are probably familiar with the Subplot. simply use the add_axes() method which takes a list of [left. Rectangle. 0. and the containers are places to put them (Axis. this is not necessary – you can work directly with PostScript. The typical user will spend 95% of his time working with the Artists.add_subplot(2. 0. which is a convenience method for instantiating Figure instances and connecting them with your user interface or drawing toolkit FigureCanvas. Rectangle.Renderer is the object which knows how to draw on the FigureCanvas. text(). These helper methods will take your data (eg.FigureCanvas is the area onto which the ﬁgure is drawn. AxesImage.pyplot as plt fig = plt. add them to the relevant containers.figure() ax = fig. or wxPython FigureCanvas instances.add_axes([0. The FigureCanvas and Renderer handle all the details of talking to user interface toolkits like wxPython or drawing languages like PostScript®.

rectangles.lines. either of these will work: del ax. not both! The Axes also has helper methods to conﬁgure and decorate the x-axis and y-axis tick. lw=2) In this example.. You can remove lines later simply by calling the list methods. 0. circles and polygons).lines[0] ax. ax is the Axes instance created by the fig. has a Rectangle instance that determines the color. Release 1. it creates a Line2D instance and adds it to the Axes.Line2D instance at 0x19a95710> In [102]: line Out[102]: <matplotlib.lines list.0. Artist tutorial .plot. which you can use to set the background color and transparency of the ﬁgures.remove(line) # one or the other. The ﬁgure itself contains a Rectangle exactly the size of the ﬁgure.lines.1 import numpy as np t = np. and other properties of the Axes. Try creating the ﬁgure below. s. In the interactive ipython session below.01) s = np. call: In [101]: ax.Line2D instance at 0x19a95710> If you make subsequent calls to ax. 9. and each has an extensive list of properties to conﬁgure its appearance.set_xlabel.add_subplot call above (remember Subplot is just a subclass of Axes) and when you call ax. These instances are stored as member variables Figure. eg.Matplotlib. and is a 2D “patch” of color on the ﬁgure.1 Customizing your objects Every element in the ﬁgure is represented by a matplotlib Artist.lines list is length one and contains the same line that was returned by the line.arange(0. which handle the layout and drawing of the ticks. tick labels and axis labels. = ax. it passes the information on the Text instance of the XAxis.set_xlabel(’my xdata’) # returns a Text instance ytext = ax.patch and Axes.pi*t) line. you can see that the Axes.. Every matplotlib Artist has the following properties 74 Chapter 9. color=’blue’.lines[0] Out[101]: <matplotlib.plot. Likewise.set_ylabel(’my xdata’) When you call ax.lines. each Axes bounding box (the standard white box with black edges in the typical matplotlib plot.sin(2*np.0. = ax. tick labels and axis labels: xtext = ax.patch (“Patch” is a name inherited from MATLAB. 1.plot (and the hold state is “on” which is the default) then additional lines will be added to the list. Each Axes instance contains an XAxis and a YAxis instance.0. transparency.plot(t.

For example.4 0.0.5 0.0 0. Release 1. Customizing your objects 75 . you can also use the set method with keyword arguments.0 3 2 1 0 1 time (s) 2 3 4 Property alpha animated axes clip_box clip_on clip_path contains ﬁgure label picker transform visible zorder Description The transparency .0 70 60 50 40 30 20 10 04 a sine wave volts 0.0 0.get_alpha() o.8 1.2 0.5 1. possibly None A text label (eg.1.5*a) If you want to set a number of properties at once. For example: 9.set_alpha(0. to multiply the current alpha by a half: a = o.Matplotlib.a scalar from 0-1 A boolean that is used to facilitate animated drawing The axes that the Artist lives in. 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). 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 ﬁgure instance the artist lives in.1 1.6 0.0 0.

Release 1.artist.75 figure = Figure(8. Artist tutorial . 76 Chapter 9. This works for classes derived from Artist as well. (0.1 o.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. 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.5. there are two kinds of objects: primitives and containers.125) fill = 1 hatch = None height = 1 label = linewidth or lw = 1. zorder=2) If you are working interactively at the python shell. (1. In this section we’ll review where the various container objects store the Artists that you want to get at.2 Object containers Now that we know how to inspect and set the properties of a given object we want to conﬁgure. Here are the Figure rectangle properties mentioned above: In [149]: matplotlib. 1).0 picker = None transform = <Affine object at 0x134cca84> verts = ((0.0. so you can consult the interactive “help” or the matplotlib artists for a listing of properties for a given object. 0).Matplotlib.getp() function (simply getp() in pylab). 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. Figure and Rectangle. eg. which lists the properties and their values. we need to now how to get at that object. a handy way to inspect the Artist properties is to use the matplotlib. The primitives are usually the things you want to conﬁgure (the font of a Text instance.set(alpha=0. 9. (1.getp(fig.artist. As mentioned in the introduction.125x6. 1).patch) alpha = 1. but it also has properties like the xscale to control whether the xaxis is ‘linear’ or ‘log’.

axes: ax.gca and Figure. 0. transform=fig.Line2D([0. Release 1.lines. More useful is “ﬁgure coordinates” where (0. you should not insert or remove axes directly from the axes list.axes. 1].patch.1. figure=fig) In [194]: fig.axes.canvas.3]) In [159]: ax1 Out[159]: <matplotlib.transFigure. 0.lines. figure=fig) In [193]: l2 = matplotlib. [0.draw() Here is a summary of the Artists the ﬁgure contains 9. 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 ﬁgure. and it contains everything in the ﬁgure. These are also returned by the methods that create them: In [156]: fig = plt. <matplotlib.axes. patches and images. transform=fig.transFigure: In [191]: fig = plt.Subplot instance at 0xd54b26c> In [160]: print fig.transFigure. 1]. 1) is the top-right of the ﬁgure which you can obtain by setting the Artist transform to fig.figure() In [192]: l1 = matplotlib.0.figure. Here is an example which turns all the axes grids on: for ax in fig. 0. 0].Axes instance at 0xd3f0b2c>] Because the ﬁgure maintains the concept of the “current axes” (see Figure. which you can use to add primitives directly.figure() In [157]: ax1 = fig.grid(True) The ﬁgure also has its own text. and the delaxes() method to delete. 0) is the bottom-left of the ﬁgure and (1. [1.1 9.7.add_axes([0.axes.Figure. You are free however.axes [<matplotlib.extend([l1.add_subplot(211) In [158]: ax2 = fig. The background of the ﬁgure is a Rectangle which is stored in Figure.Subplot instance at 0xd54b26c>.3 Figure container The top level container Artist is the matplotlib.Line2D([0. but rather use the add_subplot() and add_axes() methods to insert. 1].1.Matplotlib.lines. to iterate over the list of axes or index into it to get access to Axes instances you want to customize.sca) to support the pylab/pyplot state machine.3. lines. l2]) In [195]: fig. Figure container 77 . As you add subplots (add_subplot()) and axes (add_axes()) to the ﬁgure these will be appended to the Figure.

0. the canonical plot() and pass in arrays or lists of values.Matplotlib. eg.4 Axes container The matplotlib. Like the Figure.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 . the method 78 Chapter 9.axes.Axes is the center of the matplotlib universe – it contains the vast majority of all the Artists used in a ﬁgure with many helper methods to create and add these Artists to itself. see Axes.patch # a Rectangle instance rect. see Axes. as well as helper methods to access and customize the Artists it contains.legends) A list of Figure Line2D instances (rarely used. Release 1.useful for raw pixel display A list of Figure Legend instances (diﬀerent from Axes.add_subplot(111) rect = ax. it contains a Patch patch which is a Rectangle for Cartesian coordinates and a Circle for polar coordinates.lines) A list of Figure patches (rarely used.patches) A list Figure Text instances 9. Artist tutorial . this patch determines the shape. background and border of the plotting region: ax = fig.set_facecolor(’green’) When you call a plotting method.

Here is an annotated interactive session illustrating what is going on: In [261]: fig = plt.lines. methods that create patches.plot(x.hist(np.Line2D() instance. like bar() creates a list of rectangles. update the line with all the Line2D properties passed as keyword arguments. height=12) # by default the axes instance is None In [264]: print rect.1).1. because the Axes needs to do a few things when it creates and adds an object. It also inspects the data contained in the Artist to update the data structures controlling auto-scaling. so that the view limits can be adjusted to contain the plotted data. The line has been added to the Axes.patches list: In [233]: n.figure() In [262]: ax = fig. linewidth=2) plot returns a list of lines because you can pass in multiple x. y pairs to plot.patches lists unless you know exactly what you are doing. add the line to the Axes. It sets the ﬁgure and axes property of the Artist. y = np. rectangles = ax.randn(1000).rand(2.random. Axes container 79 . color=’blue’. nonetheless. Release 1. 50.Matplotlib.0. and we are unpacking the ﬁrst element of the length one list into the line variable. bins.lines.775x0.Line2D instance at 0xd378b0c>] Similarly.add_patch(rect) # and notice that the ax.patches. = ax.add_patch method has set the axes # instance In [267]: print rect.0. will add the patches to the Axes.random.get_axes() Axes(0.get_transform() <Affine object at 0x13695544> # now we add the Rectangle to the Axes In [266]: ax.lines [<matplotlib. as well as the default Axes transformation (unless a transformation is set).lines container.get_axes() None # and the transformation instance is set to the "identity transform" In [265]: print rect. y.125.8) 9.0.4. facecolor=’yellow’) In [234]: rectangles Out[234]: <a list of 50 Patch objects> In [235]: print len(ax.1 will create a matplotlib.add_subplot(111) # create a rectangle instance In [263]: rect = matplotlib.lines list: In [229]: print ax. You can. 100) In [214]: line.patches) You should not add objects directly to the Axes.Rectangle( (1. and returns it to you: In [213]: x. width=5. create objects yourself and add them directly to the Axes using helper methods like add_line() and add_patch(). ’-’.lines or Axes.

0.get_xticklabels(): label.hist .xy plots ax.legend .get_transform() <Affine object at 0x15009ca4> # the default axes transformation is ax. many Axes helper methods for creating primitive Artists and adding them to their respective containers.errorbar .ﬁll .get_xlim() (0.autoscale_view() # and now the xlim are updated to encompass the rectangle In [273]: print ax. These are stored as instance variables xaxis and yaxis.images ax.0) # we have to manually force a figure draw In [274]: ax.legends ax.dataLim. the Axes contains two important Artist containers: the XAxis and YAxis.bar charts ax.annotate . which handle the drawing of the ticks and labels. The table below summarizes a small sampling of them.0.patches ax.Matplotlib.0) # but the data limits have been updated to encompass the rectangle In [271]: print ax.axes legends ax.texts In addition to all of these Artists. you can set the font size of the XAxis ticklabels using the Axes helper method: for label in ax.0. 6.texts ax.bounds (1.patches ax. Release 1. For example. 1.shared area ax. 5.text Artist Annotate Rectangle Line2D and Rectangle Polygon Rectangle AxesImage Legend Line2D PolygonCollection Text Container ax.figure.error bar plots ax.lines ax.1 # and the transformation has been set too In [268]: print rect.lines and ax.patches ax. and where they store them Helper method ax. 12.canvas. the kinds of Artist they create.get_xlim() (1.0.text .plot .imshow .transData <Affine object at 0x15009ca4> # notice that the xlimits of the Axes have not been changed In [270]: print ax.0) # we can manually invoke the auto-scaling machinery In [272]: ax.0.0.image data ax.bar .collections ax.scatter .scatter charts ax.transData In [269]: print ax. The XAxis and YAxis containers will be detailed below.draw() There are many.histograms ax. Artist tutorial . 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.text annotations ax.set_color(’orange’) 80 Chapter 9. 1.patches ax.

5.0. Each Axis object contains a label attribute (this is what pylab modiﬁes in calls to xlabel() and ylabel()) as well as a list of major and minor ticks.get_ticklines() Out[291]: <a list of 20 Line2D ticklines objects> # but you can also ask for the minor ticks 9. tick labels. 5.: In [285]: axis = ax. The ticks are XTick and YTick instances. 9.axis. 8.. Although the ticks contain all the primitives and will be covered below.get_ticklines() Out[288]: <a list of 20 Line2D ticklines objects> # by default you get the major ticks back In [291]: axis. this can be customized In [288]: axis. 7. the tick labels and the axis label.]) In [287]: axis. 3.axis.xaxis In [286]: axis.5 Axis containers The matplotlib. Because the ticks are dynamically created as needed (eg..get_ticklocs() Out[286]: array([ 0. 4.. panning and zooming. You can conﬁgure the left and right ticks separately for the y-axis. The Axis also stores the data and view intervals used in auto-scaling.. 2. the grid lines.Matplotlib. 6. when panning and zooming). tick locations etc. and the upper and lower ticks separately for the x-axis. the Axis methods contain accessor methods to return the tick lines. as well as the Locator and Formatter instances which control where the ticks are placed and how they are represented as strings. which contain the actual line and text primitives that render the ticks and ticklabels. Release 1..Axis instances handle the drawing of the tick lines.. you should access the lists of major and minor ticks through their accessor methods get_major_ticks() and get_minor_ticks().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.YAxis instance 9...XAxis instance matplotlib. Axis containers 81 .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.axis.. 1.

figure.1 In [292]: axis.0.patch # a rectangle instance rect.3.set_facecolor(’lightslategray’) for label in ax1.keyword minor=True|False The matplotlib.keyword minor=True|False A list of Line2D instances .1.ticker.Matplotlib. 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.Locator instance for major ticks The matplotlib.set_markeredgewidth(3) 82 Chapter 9.Formatter instance for major ticks The matplotlib.patch rect.add_axes([0. 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 .set_rotation(45) label. which customizes the axes and tick properties import numpy as np import matplotlib.get_ticklines(): # line is a Line2D instance line. not recommended for its beauty. 0.set_markersize(25) line.pyplot as plt # plt.keyword minor=True|False A list of Tick locations .get_ticklabels(): # label is a Text instance label.Figure instance fig = plt.Locator instance for minor ticks The matplotlib.figure creates a matplotlib.ticker.ticker.ticker.set_fontsize(16) for line in ax1.yaxis.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 oﬀ for the major or minor ticks Here is an example.set_facecolor(’lightgoldenrodyellow’) ax1 = fig.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.4]) rect = ax1.set_color(’red’) label.xaxis. Artist tutorial . 0.figure() rect = fig. 0.set_color(’green’) line.a Text instance A list of Text instances . Release 1.4.

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. Release 1. as well as the label instances for the upper and lower ticks.2 0.6 0.0.0 0.Tick is the ﬁnal container object in our descent from the Figure to the Axes to the Axis to the Tick.0 83 .4 0.1 1. 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.8 1.2 0.Matplotlib.4 0.6 Tick containers The matplotlib. In addition. Each of these is accessible directly as an attribute of the Tick.0 0.6. The Tick contains the tick and grid line instances.0 9.6 0. Tick containers 0.axis.

Release 1.FormatStrFormatter(’$%1..set_major_formatter(formatter) for tick in ax.set_color(’green’) $100.ticker as ticker fig = plt.rand(20)) formatter = ticker.00 20 84 Chapter 9.pyplot as plt import matplotlib.label2. _gridspec-guide: 5 10 15 $0.label2On = True tick.00 $20.yaxis.0.Matplotlib.00 $40.yaxis.label1On = False tick.00 $80.add_subplot(111) ax.2f ’) ax.00 0 . Artist tutorial .random.1 import numpy as np import matplotlib.figure() ax = fig.plot(100*np.get_major_ticks(): tick.00 $60.

2). To create a subplot that spans multiple cells. (1.subplot2grid((3. colspan=3) (1. plt. 2).subplot2grid((3. (0.. 2). unlike matplotlib’s subplot. rowspan=2) For example.3). Basic Example of using subplot2grid To use subplot2grid.3). plt. rowspan=2) (2.subplot” but uses 0-based indexing and let subplot to occupy multiple cells.) can be tuned. The number of rows and number of columns of the grid need to be set. the index starts from 0 in gridspec. plt. 0)) (2.3). Optionally. the subplot layout parameters (e.subplot2grid((3.subplot(2.0).3).3).subplot2grid((3. 0).subplot2grid((3.3). the following commands ax1 ax2 ax3 ax4 ax5 = = = = = plt. right. 1)) creates 85 . etc. SubplotSpec speciﬁes the location of the subplot in the given GridSpec.(0. (1.0). you provide geometry of the grid and the location of the subplot in the grid.2. 0)) is identical to ax = plt.1) Note that.subplot2grid((2.CHAPTER TEN CUSTOMIZING LOCATION OF SUBPLOT USING GRIDSPEC GridSpec speciﬁes the geometry of the grid that a subplot will be placed. colspan=2) ax3 = plt. plt.g. colspan=2) (1. For a simple single-cell subplot: ax = plt. ax2 = plt. left.subplot2grid((3.3).subplot2grid((3. subplot2grid a helper function that is similar to “pyplot.

Customizing Location of Subplot Using GridSpec . For.1 subplot2grid ax1 ax2 ax3 ax4 ax5 10. 3) ax1 = plt.GridSpec(2. SubplotSpec that spans multiple cells.GridSpec(3.subplot(gs[0.subplot(gs[1. :]) ax2 = plt.0.subplot(gs[1:. 0]) A gridspec instance provides array-like (2d or 1d) indexing that returns the SubplotSpec instance. use slice. 2) ax = plt.2).gridspec as gridspec gs = gridspec. ax2 = plt. Release 1.subplot2grid((2.Matplotlib.:-1]) 86 Chapter 10. -1]) The above example becomes gs = gridspec. 0)) is equal to import matplotlib.1 GridSpec and SubplotSpec You can create GridSpec explicitly and use them to create a Subplot. ax = plt.subplot(gs[1.(0.subplot(gs[0. For example.:-1]) ax3 = plt.

05. Release 1. but it only aﬀects the subplots that are created from the given GridSpec. :-1]) ax3 = plt.subplot(gs[-1. -1]) ax4 = plt. wspace=0.subplot(gs1[:-1.48. :]) ax2 = plt. 3) gs1.05.05) ax1 = plt.Matplotlib. wspace=0. right=0. gs1 = gridspec.0.48.2 Adjust GridSpec layout When a GridSpec is explicitly used.subplot(gs1[-1.05) This is similar to subplots_adjust.-2]) GridSpec ax1 ax2 ax3 ax4 ax5 10.1 ax3 = plt.GridSpec(3. you can adjust the layout parameters of subplots that are created from the gridspec.GridSpec(3. right=0. -1]) gs2 = gridspec.update(left=0.subplot(gs[-1. Adjust GridSpec layout 87 . The code below gs1 = gridspec.subplot(gs[1:. 3) gs1.2. 3) 10.0]) ax5 = plt.subplot(gs1[-1.GridSpec(3.update(left=0.

2) gs00 = gridspec. -1]) creates GirdSpec w/ different subplotpars ax1 ax4 ax5 ax2 ax3 ax6 10.GridSpecFromSubplotSpec(3.subplot(gs2[:.0. hspace=0.Matplotlib. 3. right=0.GridSpec(1. subplot_spec=gs0[1]) 88 Chapter 10.05) ax4 = plt. :-1]) ax5 = plt.3 GridSpec using SubplotSpec You can create GridSpec from the SubplotSpec. Release 1.update(left=0.1 gs2.55. 3. -1]) ax6 = plt.98.subplot(gs2[:-1. gs0 = gridspec. in which case its layout parameters are set to that of the location of the given SubplotSpec.subplot(gs2[-1. Customizing Location of Subplot Using GridSpec .GridSpecFromSubplotSpec(3. subplot_spec=gs0[0]) gs01 = gridspec.

Matplotlib. width_ratios=[1.0. 2.4.4 GridSpec with Varying Cell Sizes By default.1 GirdSpec Inside GridSpec ax1 ax4 ax5 ax2 ax3 ax6 10.GridSpec(2.subplot(gs[1]) plt. You can adjust relative heights and widths of rows and columns. Release 1. GridSpec creates cells of equal sizes. height_ratios=[4. only their relative ratios matter. gs = gridspec. GridSpec with Varying Cell Sizes 89 .subplot(gs[0]) plt.2]. Note that absolute values are meaningless.1] ) ax1 ax2 ax3 ax4 = = = = plt.subplot(gs[3]) 10.subplot(gs[2]) plt.

Customizing Location of Subplot Using GridSpec . Release 1.0.Matplotlib.1 ax1 ax2 ax3 ax4 90 Chapter 10.

CHAPTER ELEVEN LEGEND GUIDE Do not proceed unless you already have read legend() and matplotlib. See below). it automatically generate the legend from label properties of the child artists by calling get_legend_handles_labels() method. If label attribute is empty string or starts with “_”. • Note that not all kind of artists are supported by the legend.legend() is equivalent to: handles. 91 .get_legend_handles_labels() ax..e. that artist will be ignored.legend. and the second argument should a list of string labels.patches and some artists in ax.lines and ax.legend(handles. ax. **kwargs) If len(args) is 2. – Line2D – Patch – LineCollection – RegularPolyCollection Unfortunately.1 What to be displayed The legend command has a following call signature: legend(*args. For example. labels) The get_legend_handles_labels() method returns a tuple of two lists. list of artists and list of labels (python string).legend.Legend! 11. the ﬁrst argument should be a list of artist to be labeled. i. The following is the list of artists that are currently supported. or customize it beyond what is supported by matplotlib. 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. However.collection which are instance of LineCollection or RegularPolyCollection. it does not return all of its child artists. It returns all artists in ax. If len(args) is 0. labels = ax. The label attributes (returned by get_label() method) of collected artists are used as text labels.Legend.

. 0). and explicitly use these for the ﬁrst two argument of the legend call. labels[::-1]) # or sort them by labels import operator hl = sorted(zip(handles.get_legend_handles_labels() # reverse the order ax. 1.1. = plot([2.g. There are a two options.1]. you may use another artist as a proxy. plot() returns list of Line2D instances.2.1) p1. Or some return multiple artists. For example. p1]. Legend guide .1 • Remember that some pyplot commands return artist not supported by legend. label="line 1") p2.2. labels). First.Matplotlib. label="line 2") p3.: ax = subplot(1.3.. "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.1. ["Red Rectangle"]) 92 Chapter 11.1. the artists may belong to other axes or even none. = ax.: p1.1]) legend([p2. = plot([3.: p = Rectangle((0. key=operator. • The legend does not care about the axes that given artists belongs. For example. fill_between() returns PolyCollection that is not supported. 11.2. = ax.0. labels2 = zip(*hl) ax.1 Adjusting the Order of Legend items When you want to customize the list of artists to be displayed in the legend.3]) p2. Release 1. ["line 2". = plot([1. 1. labels2) 11. or their order of appearance.legend(handles2. labels = ax.1].itemgetter(1)) handles2. and errorbar() returns a length 3 tuple of Line2D instances. e.plot([2.2.e. 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. fc="r") legend([p]. i.plot([1.3.3].legend(handles[::-1].plot([3.1]) p3. you can keep lists of artists and labels.2 Using Proxy Artist When you want to display legend for an artist not supported by matplotlib. label="line 3") handles.

the coordinates (even for the bbox instance) are considered as normalized axes coordinates. Release 1. loc=2. from matplotlib.2. 1). borderaxespad=0..transFigure) Also.102). 11.) show() 11.. For example. borderaxespad=0. 1). Multicolumn Legend 93 . mode=”expand” horizontally expand the legend to ﬁll the axes area. 1.2 Multicolumn Legend By specifying the keyword argument ncol. height of the bbox). ncol=2. a tuple of 4 ﬂoats (x.1 11. Also. you can place above or outer right-hand side of the axes. if you want your axes legend located at the ﬁgure corner (instead of the axes corner): l = legend(bbox_to_anchor=(0.pyplot import * subplot(211) plot([1. 0.2. 1.1].02.1]. . either by string or a integer number. width.3]. 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. y. You can specify your own bbox using bbox_to_anchor argument.py for example. transform=gcf().) subplot(223) plot([1. you can have a multi-column legend. y with width=height=0). loc=3. label="test1") plot([3.2.0. or a tuple of 2 ﬂoats (x. See legend_demo3. label="test2") legend(bbox_to_anchor=(0.2. the legend will anchor to the bbox of the axes (for legend) or the bbox of the ﬁgure (ﬁglegend). 1. label="test2") legend(bbox_to_anchor=(1.05.2. Unless bbox_transform argument is given.3 Legend location The location of the legend can be speciﬁed by the keyword argument loc. bbox_to_anchor can be an instance of BboxBase. label="test1") plot([3.Matplotlib.3]. mode="expand".

Thus.5 1.0 0.5 test1 test2 0.3]) p2.pyplot import * p1. loc=1) legend([p2].Matplotlib.1]) legend([p1]. ["Test1"].2.0 2.1 3.0. you want to split the legend into multiple ones.2.2. Legend guide . ["Label 1"]. loc=1) l2 = legend([p2].5 2. from matplotlib. = plot([3. ["Label 2"].3].0 test1 test2 1. gca().0 0. you need to manually add the removed legend.0 2.5 1.0 11.5 2. a new legend instance is created and old ones are removed from the axes.: p1.4 Multiple Legend Sometime. = plot([3.2. ["Test2"]. the above code only shows the second legend.0 1.5 2.5 2.0 1. When the legend command is called. = plot([1.0 1. loc=4) # this removes l1 from the axes.1].5 1.0 3.add_artist(l1) # add l1 as a separate artist to the axes show() 94 Chapter 11. = plot([1. Release 1. label="test1") p2. label="test2") l1 = legend([p1].0 1.0 0. loc=4) However.

0 1.0 1.4.5 2. Multiple Legend 95 .5 1.Matplotlib.0 2. Release 1.0 Label 1 Label 2 0.0 0.0.5 1.1 3.5 2.0 11.

Legend guide .1 96 Chapter 11.0.Matplotlib. Release 1.

Axes the event occurred in. y=%d. xdata=%f . event. and the event descriptions 97 .canvas. 12. tkinter. x=%d.plot(np. which was the ﬁrst user interface matplotlib supported.mpl_disconnect(cid) Note: The canvas retains only weak references to the callbacks. Otherwise the instance will be garbagecollected and the callback will vanish.xdata. and report event locations in both pixel and data coordinates. the class instances that are sent back to you when the event occurs. you need to retain a reference to that instance.y.button. which is part of the FigureCanvasBase. onclick) The FigureCanvas method mpl_connect() returns a connection id which is simply an integer. it is helpful to the developers to have an API for interacting with the ﬁgure via key presses and mouse movements that is “GUI neutral” so we don’t have to repeat a lot of code across the diﬀerent user interfaces. ﬂtk and macosx) and in order to support features like interactive panning and zooming of ﬁgures. qt.1 Event connections To receive events. including information like which matplotlib. When you want to disconnect the callback. The events also understand the matplotlib coordinate system.CHAPTER TWELVE EVENT HANDLING AND PICKING matplotlib works with 6 user interface toolkits (wxpython.add_subplot(111) ax. event.canvas.rand(10)) def onclick(event): print ’button=%d. Although the event handling API is GUI neutral.axes. event. ydata=%f ’%( event.x. it is based on the GTK model. 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. Here is a simple example that prints the location of the mouse click and which button was pressed: fig = plt. just call: fig.random. Here are the events that you can connect to. gtk.mpl_connect(’button_press_event’. The events that are triggered are also a bit richer vis-a-vis matplotlib than standard GUI events.figure() ax = fig. event.

line = line self.mouse button is released DrawEvent .canvas draw KeyEvent .get_ydata()) self.mouse scroll wheel is rolled LocationEvent . The KeyEvent and MouseEvent classes that handle these events are both derived from the LocationEvent. self) def __call__(self.Matplotlib.Event.key is pressed KeyEvent . Release 1.cid = line.ys = list(line. Event handling and picking .mouse enters a new ﬁgure LocationEvent .canvas.key is released MouseEvent .mouse motion PickEvent .an object in the canvas is selected ResizeEvent .backend_bases.pixels from left of canvas y y position . line): 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.mouse leaves an axes 12.mouse enters a new axes LocationEvent . event): 98 Chapter 12.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’ ‘ﬁgure_enter_event’ ‘ﬁgure_leave_event’ ‘axes_enter_event’ ‘axes_leave_event’ Class and description MouseEvent .get_xdata()) self.ﬁgure canvas is resized MouseEvent . which has the following attributes x x position . where a simple line segment is created every time a mouse is pressed: from matplotlib import pyplot as plt class LineBuilder: def __init__(self.figure.0.xs = list(line.mouse button is pressed MouseEvent .mpl_connect(’button_press_event’.2 Event attributes All matplotlib events inherit from the base class matplotlib. 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.mouse leaves a ﬁgure LocationEvent .

ys.axes: return self.mpl_connect( ’motion_notify_event’.line.canvas.on_motion) 12. so we have access to the data and pixel coordinates in event.mpl_connect( ’button_press_event’.pyplot as plt class DraggableRectangle: def __init__(self.line.figure. ‘win’. any character.on_press) self.figure. ‘up’. self.1 Draggable rectangle exercise Write draggable rectangle class that is initialized with a Rectangle instance but will move its x.y location when dragged. When the mouse is pressed.rect.2. In the motion event callback.xdata.figure() ax = fig.figure.rect = rect self.xs.rect.mpl_connect( ’button_release_event’. self. In addition to the LocationEvent attributes. self.figure.line. and add those deltas to the origin of the rectangle you stored.x and event. or ‘control’ 12. event if event. 1. self. On the button release event. ‘down’ (up and down are used for scroll events) key the key pressed: None.xy and connect to the press.append(event.cidrelease = self.inaxes!=self. it has button button pressed None. Release 1. = ax.patches.rect.set_title(’click to build line segments’) line. ‘shift’.ydata) self.add_subplot(111) ax. motion and release mouse events.cidmotion = self.append(event.xs. Event attributes 99 . 3. Here is the solution: import numpy as np import matplotlib. 2. rect): self.xdata) self.show() The MouseEvent that we just used is a LocationEvent.plot([0].ys) self.2.canvas.canvas. check to see if the click occurs over your rectangle (see matplotlib. compute the deltax and deltay of the mouse movement. The redraw the ﬁgure.Matplotlib.cidpress = self.set_data(self. [0]) # empty line linebuilder = LineBuilder(line) plt. store the rectangle xy and the location of the mouse click in data coords.canvas.Rectangle.press = None def connect(self): ’connect to all the events we need’ self.1 print ’click’.on_release) self. Hint: you will need to store the original xy location of the rectangle which is stored as rect.0.draw() fig = plt. just reset all the button press data you stored as None.contains()) and if it does.

rect. x0+dx=%f’%(x0.rect. event): ’on release we reset the press data’ self.add_subplot(111) rects = ax.mpl_disconnect(self. event.rect. self.figure() ax = fig.xdata. y0 = self. Release 1.canvas.rand(10)) drs = [] for rect in rects: dr = DraggableRectangle(rect) dr. y0. 20*np. event): ’on button press we will see if the mouse is over us and store some data’ if event.axes: return x0. dx. event.ypress #print ’x0=%f. attrd = self.inaxes != self.figure.xdata=%f.rect.rect.1 def on_press(self.canvas.draw() def disconnect(self): ’disconnect all the stored connection ids’ self.figure.rect.rect.rect. x0+dx) self.scipy.set_x(x0+dx) self.press dx = event.xdata .xy x0. xpress=%f.draw() def on_release(self.mpl_disconnect(self.ydata . event): ’on motion we will move the rect if the mouse is over us’ if self.inaxes != self. xpress.xpress dy = event.cidpress) self.Matplotlib.xdata.rect. ypress = self.contains(event) if not contains: return print ’event contains’. y0.rect.random.figure. see # http://www.show() Extra credit: use the animation blit techniques discussed in the animations recipe to make the animated drawing faster and smoother.append(dr) plt.axes: return contains.connect() drs.press = None self.cidmotion) fig = plt.cidrelease) self.rect.canvas.rect.0.press = x0.canvas.mpl_disconnect(self. Extra credit solution: # draggable rectangle with the animation blit techniques.ydata def on_motion(self.press is None: return if event.canvas.figure.set_y(y0+dy) self. xpress.figure. Event handling and picking .xy self.bar(range(10). dx=%f.org/Cookbook/Matplotlib/Animations import numpy as np 100 Chapter 12. event. event.

xpress dy = event.on_motion) def on_press(self.mpl_connect( ’button_release_event’.lock = self # draw everything but the selected rectangle and store the pixel buffer canvas = self.rect.rect.figure. y0.2. y0 = self.rect) # and blit just the redrawn area canvas.rect.draw_artist(self.lock is not self: return if event. self.blit(axes.1 import matplotlib.draw() self. Release 1.xy self. y0.axes.contains(event) if not contains: return print ’event contains’.cidpress = self. event): ’on motion we will move the rect if the mouse is over us’ if DraggableRectangle.cidrelease = self. event): ’on button press we will see if the mouse is over us and store some data’ if event.background = canvas.set_y(y0+dy) 12. self.press = x0. Event attributes 101 .mpl_connect( ’motion_notify_event’.rect. event.figure.mpl_connect( ’button_press_event’. event.background = None def connect(self): ’connect to all the events we need’ self.axes: return if DraggableRectangle.press = None self.xdata.bbox) def on_motion(self.figure.lock is not None: return contains.canvas axes = self.canvas.axes: return x0. self.rect.rect. xpress.cidmotion = self.canvas.xdata . self.rect.ydata DraggableRectangle.press dx = event. rect): self.rect.inaxes != self.rect.figure.rect.rect.set_animated(True) canvas.0.copy_from_bbox(self.rect. ypress = self.canvas.bbox) # now redraw just the rectangle axes.xy x0.rect = rect self.set_x(x0+dx) self.rect.ydata .axes self. attrd = self.Matplotlib.pyplot as plt class DraggableRectangle: lock = None # only one can be animated at a time def __init__(self.ypress self.on_release) self.rect.on_press) self.inaxes != self.

blit(axes.bar(range(10). Release 1.0.Matplotlib.connect() drs.bbox) def on_release(self.rect. 20*np.axes # restore the background region canvas.show() 12.figure.canvas.background) # redraw just the current rectangle axes.3 Mouse enter and leave If you want to be notiﬁed when the mouse enters or leaves a ﬁgure or axes.canvas.figure.mpl_disconnect(self.lock is not self: return self.canvas.figure.draw() def disconnect(self): ’disconnect all the stored connection ids’ self. event): ’on release we reset the press data’ if DraggableRectangle.mpl_disconnect(self.cidmotion) fig = plt.lock = None # turn off the rect animation property and reset the background self.append(dr) plt.rect.restore_region(self.rect.rand(10)) drs = [] for rect in rects: dr = DraggableRectangle(rect) dr.canvas.canvas axes = self.1 canvas = self.background = None # redraw the full figure self.rect. you can connect to the ﬁgure/axes enter/leave events.rect.cidrelease) self.rect. Here is a simple example that changes the colors of the axes and ﬁgure background that the mouse is over: """ Illustrate the figure and axes enter and leave events by changing the 102 Chapter 12.rect) # blit just the redrawn area canvas.add_subplot(111) rects = ax.rect.figure.mpl_disconnect(self. Event handling and picking .figure.press = None DraggableRectangle.random.figure() ax = fig.draw_artist(self.cidpress) self.set_animated(False) self.

add_subplot(212) fig2.set_facecolor(’grey’) event.inaxes event.canvas.canvas.figure.4 Object picking You can enable picking by setting the picker property of an Artist (eg a matplotlib Line2D.draw() def enter_figure(event): print ’enter_figure’.canvas.figure() fig1.inaxes.canvas.figure() fig2.pyplot as plt def enter_axes(event): print ’enter_axes’. event..canvas.add_subplot(211) ax2 = fig1.draw() fig1 = plt.set_facecolor(’yellow’) event.inaxes.canvas.mpl_connect(’figure_leave_event’.draw() def leave_axes(event): print ’leave_axes’.patch. Text. leave_axes) plt.figure event.Matplotlib.canvas. enter_figure) fig1.mpl_connect(’axes_leave_event’.patch. event.add_subplot(212) fig1. AxesImage.mpl_connect(’figure_enter_event’.1 frame colors on enter and leave """ import matplotlib.mpl_connect(’figure_leave_event’. enter_axes) fig2.set_facecolor(’white’) event.canvas.patch. leave_figure) fig1. enter_figure) fig2. Object picking 103 .canvas. leave_figure) fig2.canvas.canvas.show() 12.suptitle(’mouse hover over figure or axes to trigger events’) ax1 = fig1.canvas.canvas. event.mpl_connect(’axes_enter_event’.add_subplot(211) ax2 = fig2.inaxes event.figure event.draw() def leave_figure(event): print ’leave_figure’.0..mpl_connect(’axes_enter_event’.set_facecolor(’red’) event.4.canvas.mpl_connect(’axes_leave_event’. leave_axes) fig2 = plt. Release 1. enter_axes) fig1.canvas.suptitle(’mouse hover over figure or axes to trigger events’) ax1 = fig2.) 12. etc. Polygon.canvas.mpl_connect(’figure_enter_event’.figure.patch. Patch. event.

props = picker(artist.0. function if picker is callable. Release 1.Matplotlib.artist # now do something with this.1 Simple picking example In the example below. etc. mouseevent) to determine the hit test. The mouse event in turn has attributes like x and y (the coords in display space. which Axes the mouse is over. If the mouse event is over the artist. Our onpick callback function simply prints the data that are under the pick location.pyplot as plt 104 Chapter 12. which keys were pressed. ydata (the coords in data space). it is a user supplied function which determines whether the artist is hit by the mouse event. the artist may provide additional data to the pick event that is generated. eg pixels from left. See matplotlib. 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 speciﬁed epsilon tolerance) 12.. The PickEvent which is passed to your callback is always ﬁred with two attributes: mouseevent the mouse event that generate the pick event. we set the line picker property to a scalar.backend_bases. Line2D attaches the ind property. eg the indices of the data within epsilon of the pick event. so it represents a tolerance in points (72 points per inch). 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.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 ﬁre 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 ﬁre oﬀ an event if its data is within epsilon of the mouse event. you need to connect to the ﬁgure canvas pick_event to get pick callbacks on mouse press events. See pick() for details on the PickEvent properties of the line. Additionally. For some artists like lines and patch collections. you can get information about which buttons were pressed. Diﬀerent matplotlib Artists can attach diﬀerent data to the PickEvent. Eg: def pick_handler(event): mouseevent = event.MouseEvent for details. Event handling and picking . The onpick callback function will be called when the pick event it within the tolerance distance from the line. artist the Artist that generated the pick event. For example. which are the indices into the line data under the pick point. Additionally. and has the indices of the data vertices that are within the pick distance tolerance.4.mouseevent artist = event. The signature is hit.. Here is the code: import numpy as np import matplotlib. bottom) and xdata.

4. When you click on one of the mu. Object picking 105 . Exercise solution: """ compute the mean and stddev of 100 data sets and plot mean vs stddev. Release 1. picker=5) # 5 points tolerance def onpick(event): thisline = event. you can use multiple subplots to plot the multiple time series.rand(100. axis=1) fig = plt. ’o’. onpick) plt.plot(np. plot the raw data from the dataset that generated the mean and stddev """ import numpy as np import matplotlib.show() 12. zip(xdata[ind]. sigma points. = ax. If more than one point is within the tolerance of the clicked on point.set_title(’click on points’) line.std(X.0. ys.ind print ’onpick points:’.plot(xs.figure() ax = fig.mpl_connect(’pick_event’.add_subplot(111) ax. ’o’.random.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.Matplotlib. and plot the original time series of the data that generated the clicked on points.artist!=line: return True N = len(event.4.figure() ax = fig. axis=1) ys = np.artist xdata = thisline. Connect the line created by the plot command to the pick event.pyplot as plt X = np.get_ydata() ind = event.ind) 12.1 fig = plt.random. 1000) xs = np.rand(100).get_xdata() ydata = thisline.set_title(’click on point to plot time series’) line.add_subplot(111) ax.mean(X. = ax. ydata[ind]) fig. picker=5) # 5 points tolerance def onpick(event): if event.canvas.

ind): ax = figi. onpick) plt.0.transAxes. 1. Event handling and picking . dataind in enumerate(event.Matplotlib.plot(X[dataind]) ax. transform=ax.set_ylim(-0.show() 106 Chapter 12. ys[dataind]). 0.mpl_connect(’pick_event’.1 if not N: return True figi = plt.canvas.subplotnum+1) ax.1.figure() for subplotnum.9.5) figi.05. ’mu=%1. va=’top’) ax. Release 1.3f ’%(xs[dataind].add_subplot(N.3f \nsigma=%1.show() return True fig.text(0.5.

the userland data coordinate system.transFigure coordinate system of the Figure. 13. to go from display back to the native coordinate system. which typically occur in display space. and The (1. or create your own (see matplotlib. as it happens under the hood. matplotlib updates the datalimits. and fig is a Figure instance. Coordinate data axes ﬁgure display TransforDescription mation Object ax. and the description of that system.transforms).0) is the bottom left of the display.transData The userland data coordinate system. 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. (0.transAxes The coordinate system of the Axes. matplotlib is built on top of a transformation framework to easily move between coordinate systems. This is particularly useful when processing events from the user interface. Whenever you add data to the axes.CHAPTER THIRTEEN TRANSFORMATIONS TUTORIAL Like any graphics packages. In the Transformation Object column. In 95% of your plotting. and (width.1) is top right of the axes fig. ax is a Axes instance. The table below summarizes the existing coordinate systems. For example. and transform the input to the display coordinate system. the data limits stretch from 0 to 10 on the x-axis.0) is bottom left of the axes. That is why the display coordinate system has None for the Transformation Object column – it already is in display coordinates. and -1 to 1 on the y-axis. and the display coordinate system. most commonly updated with the set_xlim() and set_ylim() methods. (0.1) is top right of the ﬁgure None This is the pixel coordinate system of the display. and (1. controlled by the xlim and ylim ax. in the ﬁgure below.0) is bottom left of the ﬁgure. (0. it helps to have an understanding of these objects so you can reuse the existing transformations matplotlib makes available to you. the data coordinate system. the ﬁgure coordinate system. 107 . The transformations also know how to invert themselves. the axes coordinate system. you won’t need to think about this. the transformation object you should use to work in that coordinate system. but as you push the limits of custom ﬁgure generation. and you want to know where the mouse click or key-press occurred in your data coordinate system.1 Data coordinates Let’s start with the most commonly used coordinate.

transData instance to transform from your data to your display coordinate system. (1.5 0.transform((5.175.0 0. Transformations Tutorial .transData. 1) plt.00 2 4 6 8 10 You can use the ax. ]) In [16]: ax.5 1.pi*x) fig = plt.show() 1.exp(-x/2.transData) Out[14]: <class ’ matplotlib. either a single point or a sequence of points as shown below: In [14]: type(ax. 0)) Out[15]: array([ 335.figure() ax = fig. 0).pyplot as plt x = np.plot(x.005) y = np.sin(2*np.transData.0 0.2)]) Out[16]: 108 Chapter 13.add_subplot(111) ax. 247.transforms.arange(0.set_ylim(-1. Release 1.1 import numpy as np import matplotlib. y) ax.Matplotlib.) * np.0.transform([(5. 0.CompositeGenericTransform’> In [15]: ax. 10) ax. 10.set_xlim(0.

642. [ 132. but you can connect to the ’on_draw’ Event to update ﬁgure coordinates on ﬁgure draws.435. 1.5 1.Matplotlib. you may also ﬁnd that the two arrows for the data and display annotations do not point to exactly the same point.0) 2 4 6 8 10 Note: If you run the source code in the example above in a GUI backend.175.2 ]. 247. and the GUI backend may slightly resize the ﬁgure when it is created.transData. 0.transform((335. Out[43]: array([ 5.00 display = (225.0. 13.CompositeGenericTransform’> In [43]: inv.0 0. Release 1.0.175.0 0.1. The eﬀect is more pronounced if you resize the ﬁgure yourself. the exact values of the display coordinates may diﬀer if you have a diﬀerent window size or dpi setting. 180.)) If your are typing along with this tutorial.1 array([[ 335. Likewise..5 0.0) data = (5. Data coordinates 109 . This is because the display point was computed before the ﬁgure was displayed.5. ]]) You can use the inverted() method to create a transform which will take you from display to data coordinates: In [41]: inv = ax. 0. This is one good reason why you rarely want to work in display space.inverted() In [42]: type(inv) Out[42]: <class ’ matplotlib. see Event handling and picking. the display labeled points are probably not the same as in the ipython session because the documentation ﬁgure size defaults are diﬀerent.transforms.]) 247. in the ﬁgure below.

this will look like an ellipse.5) is the center.transAxes for placing text. 0)) Out[56]: array([ 335. because you often want a text bubble in a ﬁxed.0) is the bottom left of your axes or subplot.0. Note that when we just change the ylim.2.95.0. but this is less useful in my experience than using ax. location. 0. Use the pan/zoom tool to move around. fontsize=16. 2) In [56]: ax. 247. 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()). import numpy as np import matplotlib.0) is the top right. the upper left of the axes pane.20) Out[57]: (10. 181.1.1) is to the left and above your axes.13333333]) 13. both are altered.add_subplot(2. 0)) Out[54]: array([ 335. but the circle will remain ﬁxed because it is not in data coordinates and will always remain at the center of the axes.175 . eg. and when we change the xlim too. and you will see the data move.pyplot as plt fig = plt.transData.5.675 .2 Axes coordinates After the data coordinate system.transData. 0. the data limits are updated so the transformation yields a new display point.transform((5.Matplotlib. axes is probably the second most useful coordinate system. This coordinate system is extremely useful when placing text in your axes. only the y-display coordinate is altered. ‘D’ as you often see in journals. ‘C’. ’C’. fontweight=’bold’. or manually change the data xlim and ylim. (0. and (1.show() You can also make lines or patches in the axes coordinate system. Here is a simple example that creates four panels and labels them ‘A’.patches as patches 110 Chapter 13.05. Release 1. 0)) Out[58]: array([-171.transData. Transformations Tutorial . label.175.transform((5. transform=ax.text(0.set_ylim(-1. ‘B’. 1.2) Out[55]: (-1. ’D’)): ax = fig. 1.13333333]) In [57]: ax.set_xlim(10. ’B’.transform((5.transAxes. 20) In [58]: ax.i+1) ax. You can also refer to points outside the range. import numpy as np import matplotlib. and have that location remain ﬁxed when you pan or zoom. va=’top’) plt.figure() for i. so (-0. ]) In [55]: ax. 181.1 When you change the x or y limits of your axes.pyplot as plt import matplotlib. here is a silly example which plots some random dots in data space. label in enumerate((’A’. More on this later when we talk about the Bbox. Nonetheless. In [54]: ax. Here the point (0.

This trick only works for separable transformations.6 0. etc.4 0.2 0.transAxes.Matplotlib. axvspan()) but for didactic purposes we will implement the horizontal span here using a blended transformation.8 0.4 0.show() 13. like you see in normal Cartesian coordinate systems.5) ax.0 0.2 0.0 A B 0.8 1.4 0.6 0.0 0.0 0.0 D C 0.2 0.25.0 0. Release 1. alpha=0. y = 10*np. y.4 0.2 0.8 1. but not on inseparable transformations like the PolarTransform.2 0.figure() ax = fig.add_patch(circ) plt.2 0.8 0.0 1. 13.2 0.0 0. we have built in functions to make them easy to plot (see axhline().0 0.6 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.random.0 0. In fact these blended lines and spans are so useful.0 1.8 1.add_subplot(111) x. axhspan().8 0. 1000) ax.4 0. Blended transformations 111 .4 0.8 1. 0.0 fig = plt.2 0. facecolor=’yellow’.1 1.8 0.4 0.0.4 0.6 0.0 1.0 0. 0.5.Circle((0.6 0.3.plot(x.3 Blended transformations Drawing in blended coordinate spaces which mix axes with data coordinates is extremely useful. pan or zoom level.rand(2. ’go’) # plot some data in data coordinates circ = patches. transform=ax.0 0.6 0.5). axvline().0 0.6 0.6 0.

add_subplot(111) x = np.transData.5) 112 Chapter 13.set_title(r’$\sigma=1 \/ \dots \/ \sigma=2$’.1 in axes coords rect = patches.2 stddev region with a span.transforms as transforms fig = plt.0).1 10 8 6 4 2 00 import import import import 2 4 6 8 10 numpy as np matplotlib.transAxes) # highlight the 1.Rectangle((1.blended_transform_factory( ax. color=’yellow’. Release 1.random. fontsize=16) # the x coords of this transformation are data.Matplotlib. alpha=0.patches as patches matplotlib. # We want x to be in data coordinates and y to # span from 0. transform=trans. and the # y coord are axes trans = transforms.figure() ax = fig..randn(1000) ax.. width=1.pyplot as plt matplotlib. Transformations Tutorial . height=1. ax. 30) ax.hist(x.0.

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.axes. Using offset transforms to create a shadow effect 113 .1 ax.0. adjusting the zorder to make sure the shadow is drawn ﬁrst and then the object 13. etc.Axes. like points or inches rather than in data coordinates. One use for an oﬀset is to create a shadow eﬀect. where you draw one object identical to the ﬁrst just to the right of it.Axes.get_xaxis_transform() 13.get_xaxis_transform() and matplotlib. The methods are matplotlib.add_patch(rect) plt. So in the example above.get_yaxis_transform(). Release 1.4 Using offset transforms to create a shadow effect One use of transformations is to create a new transformation that is oﬀset from another transformation.axes. ticklabels. Typically you want the shift to be in some physical dimension. and just below it. eg to place one object shifted a bit relative to another object. the call to blended_transform_factory() can be replaced by get_xaxis_transform: trans = ax.4.Matplotlib. so that the shift eﬀect is constant at diﬀerent zoom levels and dpi settings.

.plot(x. yt. -2/72.set_title(’creating a shadow effect with an offset transform’) plt.ScaledTranslation(dx. import import import import numpy as np matplotlib.1 it is shadowing above it. Release 1. This code says: ﬁrst apply the data transformation ax. we’ll create the oﬀset transform ourselves. 2.transforms..dpi_scale_trans transformation for the scale_trans argument.add_subplot(111) # make a simple sine wave x = np.wikipedia.5*line. = ax. and scale_trans is a transformation which scales xt and yt at transformation time before applying the oﬀsets. scale_trans) where xt and yt are the translation oﬀsets.pi*x) line.01) y = np. fig.patches as patches matplotlib. # use the zorder to make sure we are below the line ax. transform=shadow_transform. y. Transformations Tutorial . a‘point <http://en.0. to ﬁrst scale xt and yt speciﬁed in points to display space before doing the ﬁnal oﬀset. In typography. 0. lw=3.sin(2*np. and by specifying your oﬀsets in points. It is instantiated with: trans = ScaledTranslation(xt. dy = 2/72. But in the example below. and down 2 points dx. Note the use of the plus operator in: offset = transforms. color=’blue’) # shift the object over 2 points. y.transData and then translate the data by dx and dy points. fig.transData + offset # now plot the same data with our offset transform.plot(x.offset_copy(). your ﬁgure will look the same regardless of the dpi resolution it is saved in.pyplot as plt matplotlib.transforms as transforms fig = plt.transData + offset showing that can chain transformations using the addition operator. lw=3.arange(0. dy.Matplotlib. zorder=0.. color=’gray’. which returns a new transform with an added oﬀset. dy.dpi_scale_trans) shadow_transform = ax. offset = transforms.org/wiki/Point_%28typography%29>‘_ is 1/72 inches.figure() ax = fig.show() 114 Chapter 13. The dpi and inches oﬀset is a common-enough use case that we have a special helper function to create it in matplotlib. A typical use case is to use the ﬁgure fig.dpi_scale_trans) shadow_transform = ax.get_zorder()) ax. The transforms module has a helper transformation ScaledTranslation.ScaledTranslation(dx.

transData = self.transData instance is deﬁned in the basic separable axis Axes class: self.0 0.0 1. There is an eﬃciency here.0 13. (1.5 2. Here is how the ax. i. Michael Droettboom implemented the transformations framework.transData transform we have been working with in this tutorial is a composite of three diﬀerent transformations that comprise the transformation pipeline from data -> display coordinates.0 0. so let’s look at these other two pieces.5 0. taking care to provide a clean API that segregated the nonlinear projections and scales that happen in polar and logarithmic plots. It is also possible to multiply aﬃne transformation matrices together. and then apply them to coordinates in one step.. because you can pan and zoom in your axes which aﬀects the aﬃne transformation. The transformation pipeline 115 . This is not true of all possible transformations. but you may not need to compute the potentially expensive nonlinear scales or projections on simple navigation events. self.5.Matplotlib.e.5 The transformation pipeline The ax. it maps your view xlim and ylim to the unit space of the axes (and transAxes then takes that unit space to display space).transLimits + self.0).5 1. which maps the (0.transLimits is the transformation that takes you from data to axes coordinates.1) corners of the axes or subplot bounding box to display space.0 0. We can see this in action here 13. Release 1.transAxes) We’ve been introduced to the transAxes instance above in Axes coordinates.transScale + (self.0.5 1.1 creating a shadow effect with an offset transform 1.0 0. from the linear aﬃne transformations that happen when you pan and zoom.

or radius and theta for polar data.scale. Michael Droettboom has provided a nice tutorial example of creating a hammer projection axes. 10) Out[81]: (0. the projection transformation. The scales transforms are properties of the respective xaxis and yaxis Axis instances..25.transform((10. For non-separable axes the PolarAxes.transform((0.projections. the xaxis updates its scale to a matplotlib.transform((5.25)) Out[90]: array([ 2. there is one more piece to consider.5.Matplotlib. then the ax.set_xlim(0.. 0. eg. which is responsible for the optional non-linear scaling of the data.set_ylim(-1.0. 0. 0. 116 Chapter 13.0)) Out[87]: array([ 0.]) In [87]: ax. for logarithmic axes.-1)) Out[84]: array([ 0.1)) Out[86]: array([ 1. -0.5.]) In [86]: ax.transLimits.transData = self. but when you call a logarithmic scaling function like semilogx() or explicitly set the scale to logarithmic with set_xscale().transProjectionAffine + self.transScale + self. latitude and longitude for map data. eg. see apicustom_projection_example.transScale attribute.LogScale instance.transProjection + \ (self. For example. and the best way to learn more is to open the source for those packages and see how to make your own. 10) In [82]: ax.transAxes) transProjection handles the projection from the space.5]) and we can use this same inverted transformation to go from the unit axes coordinates back to data coordinates. There are several projection examples in the matplotlib. Release 1. since matplotlib supports extensible axes and projections. The transData matplotlib. this is just set to the identity transform. In [90]: inv. 1.PolarAxes is similar to that for the typical separable matplotlib Axes.transLimits.projections package.-1)) Out[85]: array([ 1. 1) In [84]: ax.set_xscale(’log’).transScale attribute is set to handle the nonlinear projection. Transformations Tutorial .]) In [85]: ax. since the basic matplotlib axes has linear scale. to a separable Cartesian coordinate system.5]) The ﬁnal piece is the self. 0. When an Axes is initially setup.transform((0. when you call ax.polar.transLimits.transLimits. with one additional piece transProjection: self.transform((10.1 In [80]: ax = subplot(111) In [81]: ax.1) Out[82]: (-1..

LINETO.LINETO.1).).). For example to draw the unit rectangle from (0.)..add_patch(patch) ax. which supports the standard set of moveto. we could use this code import matplotlib.LINETO. Path.figure() ax = fig. 0. (0..CLOSEPOLY. bottom ignored codes = [Path. 1. ] # # # # # left.CHAPTER FOURTEEN PATH TUTORIAL The object underlying all of the matplotlib. Path. top right..2) array of (x. and a N-length array of path codes. (1.). ] path = Path(verts.PathPatch(path. bottom left.0) to (1.). The Path is instantiated with a (N. top right.show() The following path codes are recognized 117 ..patch objects is the Path. 1. 0. curveto commands to draw simple and compound outlines consisting of line segments and splines. Path..add_subplot(111) patch = patches. Path. lineto.MOVETO. codes) fig = plt.pyplot as plt from matplotlib.y) vertices.patches as patches verts = [ (0. facecolor=’orange’.path import Path import matplotlib. 0. (1.2) plt.2) ax.set_ylim(-2. (0. lw=2) ax.set_xlim(-2.

pyplot as plt from matplotlib. to the given end point.0 1. and CURVE4 has three vertices for the two control points and the end point.5 0. with the given control points.Matplotlib.5 2.0 0. Draw a line from the current position to the given vertex.0 0.5 0.0 0.5 1.5 2.5 1.1 2. to the given end point. Draw a quadratic Bézier curve from the current position.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.5 1. Draw a line segment to the start point of the current polyline.0 1. Release 1.02. 1 endpoint) CURVE4 3 (2 control points. the two control points. 1 endpoint) CLOSEPOLY (point itself is 1 ignored) 14. 1 1 2 (1 control point. Draw a cubic Bézier curve from the current position.0 0.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.0.0 1.5 1. 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 point.path import Path 118 Chapter 14. and the end point import matplotlib. Path Tutorial .0 1.

0.05. 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..MOVETO.Matplotlib. Path. lw=2) ax. While we could change it now. the length of bins is 1 greater than the length of n in the example below: 14.. 0.text(0.05. ys = zip(*verts) ax. -0. ’P1’) ax. eg a bunch of Rectangles. etc.plot(xs. 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. ms=10) ax.).add_patch(patch) xs. ’x--’.8.1. Compound paths 119 . ’P0’) ax. which create a number of primitives. Path.text(1. -0.set_xlim(-0. 1.text(-0. ’P2’) ax.05. 0. replacing the functionality in bar. 0.8).PathPatch(path.05. ys.).85.15. First we’ll create some random normally distributed data and compute the histogram.CURVE4.).1) ax.2.set_ylim(-0. (0. in case you need to do so in your own code for eﬃciency reasons.show() 14.figure() ax = fig. can usually be implemented more eﬃciently using a compound path. Plotting functions like hist() and bar(). facecolor=’none’.1) plt. ] path = Path(verts. ] # # # # P0 P1 P2 P3 codes = [Path. Path.patches as patches verts = [ (0. it would break old code. 1. codes) fig = plt. Polygon.2 Compound paths All of the simple patch primitives in matplotlib. Release 1. 1.1 import matplotlib.CURVE4.05. (1.2. 0. 1.1. are implemented with simple path. color=’black’. so here we will cover how to create compound paths. Circle.CURVE4.85. ’P3’) ax.add_subplot(111) patch = patches. Because numpy returns the bin edges and not centers. Rectangle. (0.text(0. lw=2. eg you are creating an animated bar plot.

0 P0 0.0] = left 120 Chapter 14. 2)) codes = np.6 0.0 # histogram our data with numpy data = np. where n is the array of counts for each histogram bar: # get the corners of the rectangles for the histogram left = np.zeros(len(left)) top = bottom + n Now we have to construct our compound path.Path. For each rectangle.array(bins[1:]) bottom = np. Path Tutorial .4 0.zeros((nverts. Each of the left. 3 for the LINETO.Path. LINETO and CLOSEPOLY for each rectangle.8 1. which will consist of a series of MOVETO.4 0.2 0.0 0.0 P1 P2 P3 0.MOVETO codes[4::5] = path.ones(nverts. Release 1. we need 5 vertices: 1 for the MOVETO.Path.8 0. As indicated in the table above. etc. 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. bottom. int) * path.randn(1000) n. 100) We’ll now extract the corners of the rectangles.array(bins[:-1]) right = np.Matplotlib. and 1 for the CLOSEPOLY.random.CLOSEPOLY verts[0::5. arrays below is len(n).2 0.1 1.histogram(data.0.6 0.LINETO codes[0::5] = path. bins = np.

0] verts[1::5.2. attach it to a PathPatch.Matplotlib.add_patch(patch) Here is the result 30 25 20 15 10 5 03 2 1 0 1 2 14. facecolor=’green’.PathPatch(barpath.1] verts[2::5.0. codes) patch = patches. edgecolor=’yellow’. alpha=0.0] verts[3::5. Compound paths 121 .5) ax. and add it to our axes: barpath = path.1 verts[0::5.0] verts[2::5.Path(verts.1] verts[3::5. Release 1.1] = = = = = = = bottom left top right top right bottom All that remains is to create the path.1] verts[1::5.

Release 1.Matplotlib.1 122 Chapter 14. Path Tutorial .0.

CHAPTER FIFTEEN ANNOTATING AXES Do not proceed unless you already have read Annotating text. text() and annotate()! 15.1 Annotating with Text with Box Let’s start with a simple example. 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 .

set_boxstyle("rarrow". can be accessed and modiﬁed as usual. use empty string as the ﬁrst argument. 124 Chapter 15. ax. edgewidth. following box styles are implemented. a box around the text is drawn. ) This annotates a point at xy in the given coordinate (xycoords) with the text at xytext given in textcoords.3.3 Note that the attributes arguments can be speciﬁed within the style name with separating comma (this form can be used as “boxstyle” value of bbox argument when initializing the text instance) bb.annotate("Annotation". ec="b". etc.get_bbox_patch() The return value is an instance of FancyBboxPatch and the patch properties like facecolor. xytext=(x2. Annotating Axes . y2).3.3".tooth_size=None pad=0. bb. xycoords=’data’.tooth_size=None pad=0. va="center". y1). To draw only an arrow.3.text(0. the annotated point is speciﬁed in the data coordinate and the annotating text in oﬀset points. and when given.6) The arguments are the name of the box style with its attributes as keyword arguments. "Direction". To change the shape of the box.rounding_size=None pad=0. An arrow connecting two point (xy & xytext) can be optionally drawn by specifying the arrowprops argument. pad=0.6") 15.1 The text() function in the pyplot module (or text method of the Axes class) takes bbox keyword argument. rotation=45.3 pad=0. lw=2) t = ax.rounding_size=None pad=0. size=15. bbox_props = dict(boxstyle="rarrow. textcoords=’offset points’. Currently.set_boxstyle("rarrow. bbox=bbox_props) The patch object associated with the text can be accessed by: bb = t.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. Often.0.Matplotlib. ha="center". use set_boxstyle method.pad=0.3 pad=0. xy=(x1.pad=0. Release 1.3. 0. fc="cyan". See annotate() for available coordinate systems. Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0.

Annotating with Arrow 125 .1 square sawtooth roundtooth rarrow larrow round4 round 15.0. Release 1.Matplotlib.2.

2. connectionstyle="arc3").annotate("".2).8). The path is transmuted to arrow patch.Matplotlib.2 0.8 0. which is controlled by the arrowstyle key value.8.1 ax. connect clip shrink mutate The creation of the connecting path between two points is controlled by connectionstyle key and following styles are available.0 The arrow drawing takes a few steps. xytext=(0. xycoords=’data’. a connecting path between two points are created. The path is further shrunk by given amount of pixels (shirnkA & shrinkB) 4. If patch object is given (patchA & patchB). 126 Chapter 15.6 0. This is controlled by connectionstyle key value.4 0.2 0. Release 1.6 0. the path is clipped to avoid the patch. 0.8 1. 1. xy=(0.0 0.0 0. Annotating Axes .0. 3.2. textcoords=’data’.0 0. ) 1.4 0. arrowprops=dict(arrowstyle="->". 0.

The behavior of each connection style is (limitedly) demonstrated in the example below.0 angleA=90. Release 1. it may be changed in the future). 15. angleA=90.fraction=0. rad=0 arc.angleB=0. some arrow style option only can be used when the connecting path is a quadratic spline. Annotating with Arrow 127 .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).3 angle.rad=-0. armA=30. armA=0. angleB=0 arc3.armA=None.angleB=0 angleA=0. angleB=180. rad=5 arc. angleB=0. fraction=-0. fraction=0. (Warning : The behavior of the bar style is currently not well deﬁned.1 Name angle angle3 arc arc3 bar Attrs angleA=90.3 angle.armB=None.3 angle3. rad=5 bar. angleB=0.2. angle=180.0. angleA=-90. angleB=90 arc3. rad=0 bar. angle3.armB=0. angleB=0. angleA=-90. angleA=-90.0. angle. angleB=10.rad=0. As will be discussed below. according to the given arrowstyle.rad=0.3. rad=0 bar.angleB=0. armB=30.0 rad=0. angleA=-90. rad=0 arc. armB=40. armB=30. angleA=-90.2 The connecting path (after clipping and shrinking) is then mutated to an arrow patch.0. fraction=-0.3 arc3. armA=30.0 armA=0. angleB=180.rad=0.Matplotlib. angleA=0. angleA=-90.rad=0.

Annotating Axes .head_width=0.head_width=0.4. the starting point is set to the center of the text extent.4. By default.3.2.0.angleB=None head_length=0.2 tail_width=0.head_width=0.shrink_factor=0.4 head_length=0.5.head_width=0.4. For these arrow styles. If the annotation string is given.2 head_length=0. They are fancy.head_width=0.tail_width=0.2 head_length=0.head_width=0.0.head_width=0.2 head_length=0.head_width=0. the patchA is set to the bbox patch of the text by default.4. For example.4.> <|- <|-| > ]]-[ fancy simple wedge |-| Some arrowstyles only work with connection style that generates a quadratic-spline segment. (0. a box around the text can be drawn using the bbox argument.1 Name -> -[ -|> <<-> <|<|-|> fancy simple wedge Attrs None head_length=0.4.2 head_length=0.4.5 -> -[ -| > <<.5.2 head_length=0. you must use “angle3” or “arc3” connection style.0) means lower-left corner and 128 Chapter 15.4. This can be adjusted with relpos key value. and wedge.lengthB=0. As in the text command.Matplotlib.tail_width=0. simple. Release 1.2 widthB=1. The values are normalized to the extent of the text.

2 0.0 Test 15.2.6 0.8 0.4 0.0 0.Matplotlib.4 0.0 0.2 0. Annotating with Arrow 129 .0 Test 1.0 0.4 0.8 0.6 0.8 1.6 0.4 0.8 1.0 0.2 0.0. Release 1.0 0.1 1.6 0.2 0.0 0.

pad=0.0 15.anchored_artists import AnchoredDrawingArea ada = AnchoredDrawingArea(20. 10) ada.0 0. 0.2") ax.add_artist(at) Test The loc keyword has same meaning as in the legend command.set_boxstyle("round.6 0. The initial size only matters.1 (1.axes_grid.anchored_artists import AnchoredText at = AnchoredText("Figure 1a". And user can add arbitrary artist to the drawing area. 1.axes_grid. Release 1. you can utilize AnchoredDrawingArea.2 0. ) at.patch.4 0. loc=1.0.0 0.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.4 0.1) means top-right.. 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. For example. A common example is the legend.8 0.8 1.Matplotlib. pad=0.drawing_area. Annotating Axes . 0.0 0. from mpl_toolkits.2 0. 20.axes_grid. 10).rounding_size=0. prop=dict(size=8). The instance is created with a size of the drawing area (in pixel).6 0. A simple application is when the size of the artist (or collection of artists) is known in pixel size during the time of creation.anchored_artists. If you want to draw a circle with ﬁxed size of 20 pixel x 20 pixel (radius = 10 pixel). loc=2. This type of artists can be created by using the OﬀsetBox class. from mpl_toolkits. frameon=True.add_artist(p1) 130 Chapter 15.. A few predeﬁned classes are available in mpl_toolkits. frameon=False) p1 = Circle((10.

2 Figure 1a 0.0.0 0.0 0.0 Sometimes.6 0.transData.8 1.0 p2 = Circle((30.0 0.4 0. the radius of the circles in above example are 10 pixel and 5 pixel.4 0. i.0 0.. respectively.4 0. from mpl_toolkits.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. This is similar to AnchoredDrawingArea except that the extent of the artist is determined during the drawing time respecting the speciﬁed transform. loc=2) 15. Placing Artist at the anchored location of the Axes 131 .8 0.e.8 1. you want to your artists scale with data coordinate (or other coordinate than canvas pixel).2 0. 1.2 0. 5.drawing_area.2 0.4 0. 10).1 1. fc="r") ada.3.Matplotlib.6 0.0 0.anchored_artists import AnchoredAuxTransformBox box = AnchoredAuxTransformBox(ax. Release 1.8 0.axes_grid.6 0. You can use AnchoredAuxTransformBox class.6 0.0 0.

2 0.0 As in the legend. Using the HPacker and VPacker.0 0. 132 Chapter 15.0 0. the bbox_transform is set to IdentityTransform by default.0 0.4 0.0 0. 1. height=0.add_artist(el) The ellipse in the above example will have width and height corresponds to 0. 1.4 0. Annotating Axes .0 0.0 0.4 0.0 Note that unlike the legend.2 0.2 Test : 0.6 0. Release 1.4 in data coordinate and will be automatically scaled when the view limits of the axes change.6 0.Matplotlib.6 0. width=0.0.1 and 0. angle=30) # in data coordinates! box. the bbox_to_anchor argument can be set.6 0.8 1.0). this is how the legend is created).8 0.8 1.1.4.1 el = Ellipse((0. you can have an arrangement(?) of artist as in the legend (as a matter of fact.2 0.drawing_area.4 0.8 0.

0. If a transform is returned. xycoords=an1. va="center". va="center". bbox=dict(boxstyle="round". For an advanced user who wants more control. you can annotate a point in other axes. arrowprops=dict(arrowstyle="->")) 2.5) of the an1’s bbox xytext=(30. 0. it supports a few other options. ax1. ax2 = subplot(121).0 0. Artist instance. bbox=dict(boxstyle="round". # (1. arrowprops=dict(arrowstyle="->")) 1. fc="w")) an2 = ax. xy=(0.4 Using Complex Coordinate with Annotation The Annotation in matplotlib support several types of coordinate as described in Annotating text. textcoords=ax2.annotate("Test 2".6 Test 1 Test 2 0. xycoords=ax1.annotate("Test". For example. For example. 3.0 0. Transform instance.Matplotlib. 0.5. xycoords="data". xy=(0. it is same as 1 and if bbox is returned. it is same as 2. 1.5. Using Complex Coordinate with Annotation 133 .4 0. ax. 0. The callable object should take a single argument of renderer instance. an1 = ax.4 0. 0.5).0 Note that it is your responsibility that the extent of the coordinate artist (an1 in above example) is determined before an2 gets drawn. xy=(1. The xy value (or xytext) is interpreted as a fractional coordinate of the bbox (return value of get_window_extent) of the artist. it means that an2 needs to be drawn later than an1. ha="center". fc="w"). xy=(0.annotate("Test".5.0 0. A callable object that returns an instance of either BboxBase or Transform.5.8 1.4.2 0.8 0.0. 0.5).1 15. xycoords=ax.0. xycoords="axes fraction") With this.annotate("Test 1".5). subplot(122) ax2.transData.5).annotate("Test".2 0. textcoords="offset points".5). In most cases.transAxes) is identical to ax. Release 1. ha="left".transData. xytext=(0.0). following two commands give identical results 15. xy=(0.5.6 0.5).

5.0 5.axes([0.5). 0. fc="w")) an2 = ax. 0.figure(figsize=(3. ha="center". xy=(1. OffsetFrom is a helper class for such case. xy=(0. 0. va="bottom".7]) an1 = ax.2)) ax=plt.5). textcoords=(an1. xycoords=an1. textcoords="offset points") 4. 0. 0. you want your annotation with some “oﬀset points”. ha="center".5. 0. but not from the annotated point but from other point. bbox=dict(boxstyle="round".annotate("Test 2". 0.5. annotate("Test". and 1 is in normalized axes coordinate.0 0.8 0.0 0. 0.pyplot as plt plt.axes([0.1.4 0.annotate("Test 1". xycoords=("data". import matplotlib.0. xy=(0.1 an2 = ax. xy=(0. A tuple of two coordinate speciﬁcation.4 0. 0. Sometimes.5 is in data coordinate. xycoords="data". bbox=dict(boxstyle="round". va="center".figure(figsize=(3.2)) ax=plt.5). xy=(1.0 0. xytext=(30.1. xycoords=an1.1.5. 1.6 Test 1 0.text import OffsetFrom Test 2 134 Chapter 15. You may use an atist or transform as with a tuple. fc="w"). 1).pyplot as plt plt. Annotating Axes . xycoords="data".1.1). arrowprops=dict(arrowstyle="->")) plt. ha="center".6 0.0). xycoords=an1. For example. textcoords="offset points") an2 = ax.5.). xytext=(30. bbox=dict(boxstyle="round". 0.5).1.7]) an1 = ax.annotate("Test 1".2 0.annotate("Test 2".8 1. va="center".8. xy=(0. For example. Release 1.2 0.get_window_extent.show() 1.Matplotlib. import matplotlib.annotate("Test 2". "axes fraction"). The ﬁrst item is for x-coordinate and the second is for ycoordinate.0). xytext=(0. "axes fraction")) 0. fc="w")) from matplotlib.8.

5.2 0.show() 1.5. xycoords="data". bbox=dict(boxstyle="round". # xytext is offset points from "xy=(0.0 0.annotate("Test 2".Matplotlib. xyB=xy.patches import ConnectionPatch xy = (0.add_artist(con) The above code connects point xy in data coordinate of ax1 to point xy int data coordinate of ax2. But. 0)) an2 = ax. 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.5 Using ConnectorPatch The ConnectorPatch is like an annotation without a text.6 0. Using ConnectorPatch 135 .0 0.1). arrowprops=dict(arrowstyle="->")) plt.5. xy=(0.6 Test 1 0. xytext=(0.1 Advanced Topics 15. fc="w").1 offset_from = OffsetFrom(an1.8 1.2. 0.axes_grid.2 0. coordsA="data". 15.5.4 Test 2 0.0. axesA=ax1. 15. xycoords=an1" va="top". from matplotlib. Release 1. utilizing it will be straight forward. the ConnectorPatch is useful when you want to connect points in diﬀerent axes. coordsB="data".1.inset_locator deﬁnes some patch classes useful for interconnect two axes. axesB=ax2) ax2.0 You may take a look at this example pylab_examples-annotation_demo3. Here is a simple example. While the annotate function is recommended in most of situation.4 0.2) con = ConnectionPatch(xyA=xy. 15. textcoords=offset_from.6 Zoom effect between Axes mpl_toolkits. 0). (0. While the ConnectorPatch instance can be added to any axes. -10).8 0. Understanding the code requires some knowledge of how mpl’s transform works. ha="center".0 0. 0.

return the path of the box around it. The value for the boxstyle can be a callable object in following forms. return path Here is a complete example.*x0*.5 0.6 0.0 0. class MyStyle(BoxStyle. *y0*. height..4 0.1 1.Matplotlib.): """ Given the location and size of the box.0 0.3 0.00. *width*.6 0.0. aspect_ratio=1. Annotating Axes . Release 1. mutation_size.0 Exception occurred rendering plot.5 0.8 1.BoxStyle.7 Deﬁne Custom BoxStyle You can use a custom box style._Base class. y0.patches. . from matplotlib.*aspect_ratio* : aspect-ration for the mutation. width.0 0.4 0. .2 0. However.BoxStyle._Base as demonstrated below. """ path = .pyplot as plt # we may derive from matplotlib. *height* : location and size of the box .2 0.2 0.path import Path from matplotlib. # You need to overide transmute method in this case.4 0.3 0.patches import BoxStyle import matplotlib.1 0._Base): 136 Chapter 15.4 0.0 0. 15.patches.: def __call__(self.2 0.*mutation_size* : a reference scale for the mutation.. x0. it is recommended that you derive from the matplotlib.8 0.1 0.

8 1. Deﬁne Custom BoxStyle 137 . You don’t need to worry about the rotation as it is automatically taken care of. """ def __init__(self.1 1. pad=0.2 0.3): """ The arguments need to be floating numbers and need to have default values.0 """ A simple box.0 0. mutation_size): """ Given the location and size of the box. Release 1.4 0.Matplotlib.pad = pad super(MyStyle. height.0 0.7.8 0.6 0. *width*. x0.*x0*. self). width. """ # padding pad = mutation_size * self. y0. the *mutation_size* is the font size of the text. return the path of the box around it.6 0.0 0.2 0. *height* : location and size of the box . .*mutation_size* : a reference scale for the mutation.pad # width and height with padding added.4 0. *pad* amount of padding """ self.__init__() def transmute(self. *y0*. Test 15.0. Often.

y0 = x0-pad. (x0.LINETO.0 138 Chapter 15.5". 0.LINETO.LINETO. y0)] com = [Path. Path.1 width.0. y1). alpha=0.CLOSEPOLY] path = Path(cp.4 0. y0 + height cp = [(x0. com) return path # register the custom style BoxStyle.subplot(111) ax. Annotating Axes st Te . Path. Path.8 0.2 0.pad=0. Path. bbox=dict(boxstyle="angled. rotation=30. va="center".0 0.5.6 0. y0). ha="center". Path.2 0. y0-pad.2)) del BoxStyle. Release 1._style_list["angled"] plt.LINETO.Matplotlib.figure(1.6 0._style_list["angled"] = MyStyle plt. figsize=(3.LINETO.MOVETO. y1 = x0+width.show() 1. # boundary of the padded box x0.5. Path.). (x0.0 0. "Test". (x1. (x1. (x0-pad.0 0. y0).text(0. height = width + 2. x1. size=30.*pad. y0). \ height + 2. y1).8 1. (x0.3)) ax = plt. (y0+y1)/2.*pad.4 0.

See the source code of 15.1 Similarly. lib/matplotlib/patches.7. Deﬁne Custom BoxStyle 139 .0.py and check how each style class is deﬁned.Matplotlib. Release 1. you can deﬁne custom ConnectionStyle and custom ArrowStyle.

0.1 140 Chapter 15.Matplotlib. Annotating Axes . Release 1.

sharey=ax1) 141 .lines. it involved a fair amount of boilerplate code. sharey=ax1) fig.figure() fig.sin(4*np. sharex=ax1. np.plot(t.Line2D object at 0x98719ec>] In [99]: ax2 = plt. matplotlib Axes support a sharex and sharey attribute.subplot(212.arange(0. possibly with shared axes.add_subplot(223. if you wanted to use the pythonic API and create a ﬁgure instance and from that create a grid of subplots.add_subplot(222. eg two subplots with time as a common axis.2 Easily creating subplots In early versions of matplotlib.Line2D object at 0xb7d8fec>] 16.add_subplot(221) fig.01) In [97]: ax1 = plt.CHAPTER SIXTEEN OUR FAVORITE RECIPES Here is a collection of short tutorials. Eg # old fig = ax1 = ax2 = ax3 = ax3 = style plt.sin(2*np.subplot(211) In [98]: ax1. you can pass in a keyword indicating what axes you want to share with In [96]: t = np. sharey=ax1) fig. When you create a subplot() or axes() instance.add_subplot(224. examples and code snippets that illustrate some of the useful idioms and tricks to make snazzier ﬁgures and overcome some matplotlib warts. To facilitate this. 0. When you pan and zoom around on one.pi*t)) Out[100]: [<matplotlib. np. 10.lines. 16.plot(t.1 Sharing axis limits and views It’s common to make two or more plots which share an axis. sharex=ax1. you want the other to move around with you. sharex=ax1) In [100]: ax2. sharex=ax1.pi*t)) Out[98]: [<matplotlib.

ax2). (’close’. In [67]: plot(r. ’<f8’). Our Favorite Recipes . (’volume’.0]. ’|V4’).subplots(2. 2. You can either unpack the axes individually: # new style method 1.autofmt_xdate and to ﬁx the second problem we can 142 Chapter 16. ’<f8’). dtype=object) The dtype of the numpy record array for the ﬁeld ‘date’ is ‘|O4’ which means it is a 4-byte python object pointer.. you see that the x locations are formatted the same way the tick labels are.3 Fixing common date annoyances matplotlib allows you to natively plots python datetime instances. 2008-10-13. and here are some tricks to help you work around them. (’low’. 2004-08-23.load(datafile). and turn oﬀ x and y sharing for the whole bunch.. What we’d like is for the location in the toolbar to have a higher degree of precision. 2008-10-10.Line2D object at 0x92a6b6c>] you will see that the x tick labels are all squashed together. ’<f8’). eg giving us the exact date out mouse is hovering over. .1 Fernando Perez has provided a nice top level method to create in subplots() (note the “s” at the end) everything at once..ﬁgure. We’ll load up some sample date data which contains datetime. sharey=True) ax1. ’<f8’)]) In [66]: r. unpack the axes fig. (’adj_close’.date. ’<i8’). Release 1. sharex=True.recarray) In [65]: r. There are a couple of things it does not handle so gracefully. ((ax1. we can use method:matplotlib. 2. To ﬁx the ﬁrst problem.0. use an axes array fig.plot(x) or get them back as a numrows x numcolumns object array which supports numpy indexing: # new style method 2.get_sample_data(’goog.date instances. eg “Dec 2004”.npy’) In [64]: r = np. in this case the objects are datetime. 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. axs = plt. (’high’. which we can see when we print some samples in the ipython terminal window.close) Out[67]: [<matplotlib. (’open’. (ax3. sharex=True.lines. ax4)) = plt.subplots(2.view(np. ’|O4’). sharey=True) axs[0.date Out[66]: array([2004-08-19.plot(x) 16.Figure. 2004-08-20. ’<f8’). 2008-10-14].Matplotlib.dtype Out[65]: dtype([(’date’. If you plot the data. (’’.date objects in a numpy record array: In [63]: datafile = cbook. and for the most part does a good job picking tick locations and string formats. r.

DateFormatter(’%Y-%m-%d’) plt. you’ll see date format strings like 2004-12-01 in the toolbar.4.close) # rotate and align the tick labels so they look better fig.0.plot(r.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. Release 1.fmt_xdata = mdates.close(’all’) fig. eg to just 16.date. matplotlib has a number of date formatters built in.autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar import matplotlib. r. plt. Fill Between and Alpha 143 . It has a very handy where argument to combine ﬁlling with logical ranges.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.fmt_xdata attribute which can be set to any function that takes a scalar and returns a string.autofmt_xdate fixes the labels’) Now when you hover your mouse over the plotted data. so we’ll use one of those.title(’fig.dates as mdates ax. 16.subplots(1) ax. ax = plt.Matplotlib.

facecolor=’blue’. ax2: ax.close. At its most basic level.0.date. Release 1.npy’) r = np.view(np.min() ax1.plot(r.fill_between(r.Matplotlib. pricemin. Let’s compare two graphs of a ﬁnancial times with a simple line plot on the left and a ﬁlled line on the right.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 ﬁll in a curve over some threshold value. ax2) = plt. sharex=True. r.subplots(1. fill_between can be use to enhance a graphs visual appearance.5) for ax in ax1.pyplot as plt import numpy as np import matplotlib.close.load(datafile). lw=2) ax2. Our Favorite Recipes .close. import matplotlib.recarray) # create two subplots with the shared x and y axes fig.cbook as cbook # load up some sample financial data datafile = cbook.grid(True) 144 Chapter 16. r.1 800 700 600 500 400 300 200 fig.2. sharey=True) pricemin = r. alpha=0. (ax1.date.get_sample_data(’goog.

Nwalkers) 16.one standard deviation of the mean position of the population.002 + 0.01*np. PDF or SVG.pyplot as plt import numpy as np Nsteps.random. In other examples. Release 1.Matplotlib.arange(Nsteps) # an (Nsteps x Nwalkers) array of random walk steps S1 = 0.suptitle(’Google (GOOG) daily closing price’) fig.randn(Nsteps. Note that the postscript format does not support alpha (this is a postscript limitation.get_yticklabels(): label. Nwalkers = 100. Our next example computes two populations of random walkers with a diﬀerent mean and standard deviation of the normal distributions from which the steps are drawn.4. 250 t = np.0. but it can be used to soften colors for more visually appealing plots. We use shared regions to plot +/. not just aesthetic. import matplotlib. Fill Between and Alpha 145 .set_visible(False) fig. the alpha channel is functionally useful as the shaded regions can overlap and alpha allows you to see both. Here the alpha channel is useful.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. as we’ll see below.1 ax1. so when using alpha save your ﬁgures in PNG.set_ylabel(’price’) for label in ax2. not a matplotlib limitation).

legend(loc=’upper left’) ax. facecolor=’yellow’.fill_between(t. color=’yellow’) ax.4 position 0. mu1.Matplotlib. mu2-sigma2. alpha=0.plot(t. Release 1.std(axis=1) mu2 = X2.randn(Nsteps.004 + 0.0.std(axis=1) # plot it! fig. label=’mean population 2’.mean(axis=1) sigma1 = X1.5) ax.5) ax. mu1. facecolor=’blue’.1 0.set_xlabel(’num steps’) ax.grid() 0.1 S2 = 0. mu1+sigma1. mu1-sigma1. lw=2.2 0. color=’blue’) ax.subplots(1) ax.5 0. Nwalkers) # an (Nsteps x Nwalkers) array of random walker positions X1 = S1. label=’mean population 1’. mu2+sigma2.3 0.cumsum(axis=0) X2 = S2.fill_between(t.random.cumsum(axis=0) # Nsteps length arrays empirical means and standard deviations of both # populations over time mu1 = X1. lw=2.set_ylabel(’position’) ax.plot(t.mean(axis=1) sigma2 = X2. Our Favorite Recipes .0 0. alpha=0.6random walkers empirical µ and ± σ interval 0.set_title(’random walkers empirical $\mu$ and $\pm \sigma$ interval’) ax.10 146 mean population 1 mean population 2 20 40 60 num steps 80 100 Chapter 16.02*np. ax = plt.

upper_bound. fancy legends 147 . Transparent.sigma*np. lw=2. alpha=0. color=’blue’) ax.randn(Nsteps) X = S. lower_bound. color=’black’.plot(t. Release 1. fancy legends Sometimes you know what your data looks like before you plot it.fill_between(t.0. label=’walker position’.fill_between(t.002 sigma = 0. we simulate a single random walker and compute the analytic mean and standard deviation of the population positions.arange(Nsteps) mu = 0. where takes a boolean mask the same length as the x. X.1 The where keyword argument is very handy for highlighting certain regions of the graph.legend(loc=’upper right’) Other times you don’t know where your data is.01 # the steps and position S = mu + sigma*np.set_ylabel(’position’) ax. and loc=’best’ will try and place the legend: 16. label=’1 sigma range’) ax. np. facecolor=’blue’. In the example below.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. and mak know for instance that there won’t be much data in the upper right hand corner.plot(t. label=’population mean’.sqrt(t) upper_bound = mu*t + sigma*np.5) ax.5 Transparent. ax = plt.5. mu*t. 16. The population mean is shown as the black dashed line.Matplotlib. ymin and ymax arguments.sqrt(t) fig. X. and the plus/minus one sigma deviation from the mean is showsn as the yellow ﬁlled region. where=X>upper_bound.set_xlabel(’num steps’) ax.random.random. and only ﬁlls in the region where the boolean mask is True.subplots(1) ax.seed(1234) Nsteps = 500 t = np.5. Then you can safely create a legend that doesn’t overlay your data: ax. lw=1. ls=’--’) ax.grid() Another handy use of ﬁlled 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. We use the where mask X>upper_bound to ﬁnd the region where the walker is above the one sigma boundary. facecolor=’yellow’. alpha=0. and shade that region blue.cumsum() # the 1 sigma upper and lower analytic population bounds lower_bound = mu*t . upper_bound.

0.plot(np.legend(loc=’upper right’) but still. so the text doesn’t move around with changes in x or y limits.20 walker position population mean 100 200 300 num steps 400 500 ax. your legend may overlap your data.5) ax.legend(loc=’best’. label=’uniform distribution’) ax. np. 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.6 0.0 0.Matplotlib. Our Favorite Recipes . and in these cases it’s nice to make the legend frame transparent. fancybox=True) leg.8 0. 148 Chapter 16. Release 1.0 position 0.1 1.set_title(’fancy.random.random.plot(np. 3) leg = ax.randn(300). label=’normal distribution’) ax.4 0.random.rand(300).seed(1234) fig. ’s-’. two useful tricks are to place the text in axes coordinates (see Transformations Tutorial).get_frame().set_alpha(0.6 Placing text boxes When decorating axes with text boxes. transparent legends’) 16.4 1. ’o-’.set_ylim(-3.2 0.subplots(1) ax.2 1.

2f $’%(mu.randn(10000) mu = x.5) # place a text box in upper left in axes coords ax.std() textstr = ’$\mu=%.mean() median = np.05. Placing text boxes 149 .text(0. transparent legends normal distribution uniform distribution 50 100 150 200 250 300 np. fontsize=14.median(x) sigma = x. median.seed(1234) fig.0. verticalalignment=’top’. facecolor=’wheat’.6. transform=ax. bbox=props) 16. Release 1.2f $\n$\mathrm{median}=%. alpha=0. textstr.random.2f $\n$\sigma=%.1 3 2 1 0 1 2 30 fancy. ax = plt.random. 0. 50) # these are matplotlib.Matplotlib.Patch properies props = dict(boxstyle=’round’.subplots(1) x = 30*np.95. sigma) ax.patch.hist(x.transAxes.

1 600 500 median =0. Our Favorite Recipes .Matplotlib.54 σ =29.0.86 400 300 200 100 0150 100 50 0 50 100 µ =0. Release 1.48 150 Chapter 16.

exceltools provides some utilities for working with Excel.natgrid is an interface to natgrid C library for gridding irregularly spaced data. 17. line. with continental and political boundaries. but requires pygtk. This toolkit ships with matplotlib. See toolkit_mplot3d-index for more documentation and examples. 17.CHAPTER SEVENTEEN TOOLKITS Toolkits are collections of application-speciﬁc functions that extend matplotlib. 17. surf.3 Excel Tools mpl_toolkits. This requires a separate installation of the natgrid toolkit from the sourceforge download page. but ships with matplotlib and thus may be a lighter weight solution for some use cases. 17.5 mplot3d mpl_toolkits.mplot3d provides some basic 3D plotting (scatter. 151 .2 GTK Tools mpl_toolkits. mesh) tools.4 Natgrid mpl_toolkits.gtktools provides some utilities for working with GTK. but requires xlwt 17. This toolkit ships with matplotlib. see basemap docs.1 Basemap Plots data on map projections. Not the fastest or feature complete 3D library out there.

Matplotlib. 152 Chapter 17. The AxesGrid toolkit is distributed with matplotlib source. Release 1.1 17. Toolkits .6 AxesGrid The matplotlib AxesGrid toolkit is a collection of helper classes to ease displaying multiple images in matplotlib.0. See toolkit_axesgrid-index for documentations.

0 time (s) 1.5 2.0 0.1 Simple Plot The most basic plot().0 About as simple as it gets.5 1. folks 0.0 153 .5 voltage (mV) 0.5 1.0 0.0 0. with text labels 1.CHAPTER EIGHTEEN SCREENSHOTS Here you will ﬁnd a host of example ﬁgures with the code that generated them 18.

0 time (s) 1. Release 1.8 0.2 0.0.99).5 1. Jonathon Taylor and Reinier Heeres for the mplot3d toolkit.0 A tale of 2 subplots Damped oscillation 1 2 3 4 5 Undamped 0. Screenshots . wireframe.80 1. scatter. See the matplotlib.0 0.0 0. and bar charts (added in matlpotlib-0.6 0.2 Subplot demo Multiple regular axes (numrows by numcolumns) are created with the subplot() command.5 0.5 1.4 Path demo You can add aribitrary paths in matplotlib as of release 0.0 0.0 0.0 18.Matplotlib.0 0.path. 18. Thanks to John Porter. 1.4 0. The toolkit is included with all standard matplotlib installs.5 mplot3d The mplot3d toolkit (see toolkit_mplot3d-tutorial and mplot3d-examples-index) has support for simple 3d graphs including surface. 154 Chapter 18.1 18.4 0.6 0.3 Histograms The hist() command automatically generates histograms and will return the bin counts or probabilities 18.98.5 2.2 0.

which used matplotlib in ground tracking of the spacecraft.025 0. See bar_stacked.py for another example.6 Ellipses Histogram of IQ : µ =100. 18. This provides a scale free..005 0. candlestick bars.0.015 0. nine lines of code. accurate graph of the arc regardless of zoom level 18. exploding one or more wedges out from the center of the pie.030 0. Michael Droettboom built on work by Charlie Moad to provide an extremely accurate 8-spline approximation to elliptical arcs (see Arc) in the viewport. You can also use up and down bars.Matplotlib. Optional features include auto-labeling the percentage of area.6.020 Probability 0.1 0. etc. You can make horizontal bar charts with the barh() command.000 40 18. . Release 1.. and a shadow eﬀect. Take a close look at the attached code that produced this ﬁgure. Ellipses 155 . σ =15 60 80 100 120 Smarts 140 160 In support of the Phoenix mission to Mars. 18. stacked bars.8 Pie charts The pie() command uses a MATLAB compatible syntax to produce pie charts.7 Bar charts The bar() command takes error bars as an optional argument.010 0.

Matplotlib. See matplotlib. allowing you to write cross GUI ﬁgures and widgets. Release 1. Screenshots .widgets and the widget examples <examples/widgets> 156 Chapter 18.0. 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.9 Table demo spline paths 2 1 0 1 2 3 4 The table() command will place a text table on the axes 18.10 Scatter demo The scatter() command makes a scatter plot with (optional) size and color arguments.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. Here the alpha attribute is used to make semitransparent circle markers with the Agg backend (see What is a backend?) 18.

see matplotlib. some are random traces that I used since the goal was to illustrate plotting techniques. 18.561 0.337 -0.8 0.6 0. Some of the data in the plot.112 -0.010 0.337 0.6 0.0 0. This example emulates one of the ChartDirector ﬁnancial plots.4 0.010 4 2 0.dates for details and usage.2 0.8 18. Release 1.4 0.12 Fill demo The fill() command lets you plot ﬁlled polygons. not market analysis! 18. Fill demo 157 .14 Financial charts You can make much more sophisticated ﬁnancial plots.2 0. are real ﬁnancial data.786 0. Thanks to Andrew Straw for providing this function 18.561 -0.ticker and matplotlib.13 Date demo You can plot date data with major and minor ticks and custom tick formatters for both the major and minor ticks.0.12.112 -0.1 4 2 0 2 4 4 0 2 1.Matplotlib.786 -1.

mercator.15 Basemap demo Jeﬀ Whitaker provided this example showing how to eﬃciently plot a collection of lines over a colormap image using the Basemap . Darren Dale and Gregory Lielens for contributions to the log scaling infrastructure. 2 4 6 8 10 18. Many map projections are handled via the proj4 library: cylindrical equidistant. Thanks to Andrew Straw. The lower subplot uses a base10 log on the xaxis and a base 4 log on the yaxis. albers equal area conic and stereographic. 158 Chapter 18.17 Polar plots The polar() command generates polar plots. 18. Release 1. lambert azimuthal equal area.1 10 8 6 4 2 00 18.0.Matplotlib. semilogy() and loglog() functions generate log scaling on the respective axes. See the tutorial entry on the wiki.16 Log plots The semilogx(). Exception occurred rendering plot. Screenshots . lambert conformal conic.

matplotlib mathtext is an independent implementation.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 ﬁgure legends. Legends 159 . and matplotlib supports external TeX rendering of strings with the usetex option. sometimes you need TeX. 18. with MATLAB compatible legend placement commands. See the tutorial at Writing mathematical expressions.20 Native TeX rendering Although matplotlib’s internal math rendering engine is quite powerful.19 Mathtext_examples A sampling of the many TeX expressions now supported by matplotlib’s internal mathtext engine.Matplotlib. and does not required TeX or any external packages installed on your computer. The mathtext module provides TeX style mathematical expressions using freetype2 and the BaKoMa computer modern or STIX fonts. 18. See the matplotlib.0. Release 1. Thanks to Charles Twardy for input on the legend command 18.1 40 35 30 25 Scores 20 15 10 5 0 G1 18.18.mathtext module for additional.

0% 15. Screenshots .0.0% Dogs Frogs Logs 160 Chapter 18.0% 10. Release 1.Matplotlib.1 Raining Hogs and Dogs Hogs 30.0% 45.

see user_interfaces-mpl_with_glade.21 EEG demo You can embed matplotlib into pygtk. Pbrain is written in pygtk using matplotlib.6 50 year 292. The lower axes uses specgram() to plot the spectrogram of one of the EEG channels.4 153.9 Hail 917. see user_interfaces-embedding_in_gtk2. EEG demo 161 . FLTK or Qt applications. For an example of how to use the navigation toolbar in your applications.1 18.2 717.8 456.4 174.5 1049.3 75.2 5 year 66.Matplotlib.0 305.6 555. Here is a screenshot of an eeg viewer called pbrain which is part of the NeuroImaging in Python suite NIPY. If you want to work with glade.8 636.4 20 year 213. see user_interfaces-embedding_in_wx2. If you want to use matplotlib in a wx application.0 18.0 192.1 Loss by Disaster 2000 Loss $1000's 1500 1000 500 0 Freeze Wind Flood 100 year 431.4 799.9 865. Tk.0.5 32.7 10 year 124.21.2 677.5 1175.2 577. wxpython. Release 1.6 796.8 1368. Quake 2149.

05 0.25 ∆i 162 Chapter 18.15 0.15 0.05 0.10 0.10 0. Release 1.05 0.10 Volume and percent change ∆i +1 0.00 0.20 0.00 0.10 0.15 0.15 0.1 0. Screenshots .25 0.0.Matplotlib.20 0.05 0.

21.6 0.0 Amp Freq 0.4 0.00 3.00 Reset 18.Matplotlib.2 0.0 5.1 10 5 red blue green 0 5 10 0. Release 1.8 1.0. EEG demo 163 .

1 0.8 1.1 0.2 0. Screenshots .0 0.1 0.4 0. Release 1.2 0.Matplotlib.2 0.3 0.0.5 0.6 0.0 164 Chapter 18.6 0.0 0.4 0.

Matplotlib. EEG demo 165 .0.1 800 700 600 500 400 300 200 100 4 200 200 5 6 200 7 200 200 8 200 9 18. Release 1.21.

0. Release 1. Screenshots .72 L:126.Matplotlib.58 H:127.06 MA (20) MA (200) MACD (12. V:133.1 70 30 140 120 100 80 5 0 5 10 RSI (14) SPY daily >70 = overbought <30 = oversold 06-Jan-2011 O:126.46 C:127. 26. 9) 200 7 8 200 9 200 201 0 201 1 166 Chapter 18.64.9M Chg:+1.

21.Matplotlib. Release 1.0 0. EEG demo 167 .0 -2 10-1 100 101 102 10 18.0 0.5 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 loglog base 4 on x 105Errorbars go negative 5 10 semilogx 1.5 15 201.0.

0 45° 1.5 1.5 2. Screenshots . Release 1.0 0° 180° 225° 270° 315° 168 Chapter 18.1 And there was90° rejoicing! much 135° 0.0.Matplotlib.

0.21. EEG demo 169 .Matplotlib. Release 1.1 Minimum Message Length Model length Data length Total message length Message length ---> Model complexity ---> 18.

00 y xy x + y x = y x <y x .Matplotlib.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.1 0 1 2 3 4 5 6 7 8 170 ˙ a +b + +s + x y $100.y x.00 α_ $100. Screenshots 9 . Release 1.0.

Release 1.6 0.2 0.0 0. EEG demo 171 .0 18.5 2.0 1.1 TEX is Number 3.21.0 0.0 ∞ n=1 −eiπ ! 2n voltage (mV) 2.5 1.Matplotlib.0.4 time (s) 0.8 1.

0. Release 1. Screenshots .1 172 Chapter 18.Matplotlib.

173 .0]. and they have done a lot of work comparing their html5 rendered images with our core renderer Agg.1.4 Contour ﬁxes and and triplot Ian Thomas has ﬁxed a long-standing bug that has vexed our most talented developers for years. contourf() now handles interior masked regions. axarr = plt. see the CHANGELOG 19.CHAPTER NINETEEN WHAT’S NEW IN MATPLOTLIB This page just covers the highlights – for the full story.1. Eg: fig.1. Basic usage allows you to create the ﬁgure and an array of subplots with numpy indexing (starts with 0).plot([1. The backend is almost feature complete.1 new in matplotlib-1. 2) axarr[0.1 HTML5/Canvas backend Simon Ratcliﬀe and Ludwig Schwardt have released an HTML5/Canvas backend for matplotlib. and the boundaries of line and ﬁlled contours coincide. a new module for doing complex subplot layouts. 19.3 Easy pythonic subplots Fernando Perez got tired of all the boilerplate code needed to create a ﬁgure and multiple subplots when using the matplotlib API. The backend features client/server interactive navigation of matplotlib ﬁgures in an html5 compliant browser. featuring row and column spans and more.2 Sophisticated subplot grid layout Jae-Joon Lee has written gridspec. left See pylab_examples-subplots_demo for several code examples.0 19.3]) # upper. 19.subplots(2. See gridspec-guide for a tutorial overview.1. 19. and wrote a subplots() helper function.2.

Eric Firing has done a lot of work on rationalizing show across backends.1. 19.1. 174 Chapter 19. Release 1. with the desired behavior to make show raise all newly created ﬁgures and block execution until they are closed.0.1 subplot2grid ax1 ax2 ax3 ax4 ax5 Additionally. user interface toolkits and versions. he has contributed a new module matplotlib. supporting mixing of 2D and 3D graphs in the same ﬁgure.Matplotlib. Thanks Ben Root. Repeated calls to show should raise newly created ﬁgures since the last call. and/or multiple 3D graphs in a single ﬁgure. but it is not possible to test them all.5 multiple calls to show supported A long standing request is to support multiple calls to show().tri and helper function triplot() for creating and plotting unstructured triangular grids. 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.6 mplot3d graphs can be embedded in arbitrary axes You can now place an mplot3d graph into an arbitrary axes location. What’s new in matplotlib . This has been diﬃcult because it is hard to get consistent behavior across operating systems. using the “projection” keyword argument to add_axes or add_subplot. 19.

8 Lots of performance and feature enhancements • Faster magniﬁcation of large images.0 19.0 0. particularly the alpha channel.1.01. throughout the API 19. auto-generating a set of images and comparing them against a set of known-goods.7 tick_params 0.0.1 1.9 Much improved software carpentry The matplotlib trunk is probably in as good a shape as it has ever been. See pyplot function tick_params() and associated Axes method tick_params().0 175 .1.1. thanks to improved software carpentry. a convenience method for changing the appearance of ticks and tick labels.0 Eric Firing wrote tick_params.5 triplot of Delaunay triangulation 1.5 0. new in matplotlib-1.0 0.0 0.5 0.Matplotlib. Release 1.5 1. 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. We now have a buildbot which runs a suite of nose regression tests on every svn commit. sending emails to developers on failures 19.1. 19.

John Hunter has written two new tutorials on working with paths and transformations: Path Tutorial and Transformations Tutorial. Michael Droettboom.99 19.2. Thanks to Andrew Straw.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. allowing active new feature development to happen in the trunk while keeping the release branches stable. 19. Chapter 19. 19. Release 1. closing over 100 bugs on the bug tracker with help from Jae-Joon Lee. What’s new in matplotlib .Matplotlib. Releases and release bugﬁxes happen in branches. Michael Droettboom and other matplotlib developers for the heavy lifting. Michael Sarahan has written Image tutorial.2 new in matplotlib-0.0.1 New documentation Jae-Joon Lee has written two new guides Legend guide and Annotating Axes.1.10 Bugﬁx marathon Eric Firing went on a bug ﬁxing and closing marathon. Christoph Gohlke and Michiel de Hoon.

0 0.5 1. 19.0.5 0. The toolkit is included standard with all new mpl installs. See pylab_examples-spine_placement_demo and matplotlib.2.Spine.4 0.2 mplot3d Reinier Heeres has ported John Porter’s mplot3d over to the new matplotlib transformations framework.2.2.Matplotlib.2 0.6 0.99 177 .2 0. as well as “detach” the spine to oﬀset it away from the data.0 0.3 axes grid toolkit Jae-Joon Lee has added a new toolkit to ease displaying multiple images in matplotlib. and it is now available as a toolkit mpl_toolkits.6 0.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. as well as some support for curvilinear grids to support the world coordinate system.mplot3d (which now comes standard with all mpl installs).4 0.1 1.0 4 2 0 42 2 02 4 4 0. 19.0 0. Release 1.8 80 60 40 20 0 20 40 60 20 10 30 0 20 10 10 010 20 20 30 19. See mplot3d-examples-index and toolkit_mplot3d-tutorial 19. No longer are your axis lines constrained to be a simple rectangle around the ﬁgure – you can turn on or oﬀ left. new in matplotlib-0. right and top. See axes_grid-examples-index and axes_grid_users-guide-index. bottom.spines.8 0.2.

Jeﬀ Whitaker.legend.Legend. What’s new in matplotlib . 178 Chapter 19. as well as fancy box drawing. See legend() and matplotlib.6 and 3. Jouni K. Manuel Metz. Thanks to Charlie Moad for testing and preparing the source release.5 (2.1 Legend enhancements Jae-Joon has rewritten the legend class.0. and there are a lot of new features and bug-ﬁxes.4 It’s been four months since the last matplotlib release. Michiel de Hoon and many others who submitted patches 19.3.5 4 4 2 0 2 4 4 2 0 2 19. and ConnectionStyle. David Kaplan.5 0. Release 1. Michael Droettboom.1 0. with contributions from Jae-Joon Lee.0 will not be available until numpy is available on those releases).2 Fancy annotations and arrows Jae-Joon has added lot’s of support to annotations for drawing fancy boxes and connectors in annotations. and added support for multiple columns and rows.4 and 2. including binaries for OS X and Windows for python 2.98.3.0 0. Thanks to the many developers who contributed to this release. Darren Dale. See annotate() and BoxStyle. 19. Seppänen.3 new in 0. Eric Firing. ArrowStyle.Matplotlib. Ryan May.

19. no third-party libraries are needed other than Python and NumPy. depending on the application. Set ‘backend : macosx’ in your matplotlibrc ﬁle.5 Fill between Added a fill_between() function to make it easier to do shaded region plots in the presence of masked data. The backend can therefore use Quartz directly and.98.0. The backend is interactive from the usual terminal application on Mac using regular Python.1 10 8 6 4 2 0 2 4 6 8 19. Release 1. You can pass an x array and a ylower and yupper array to ﬁll betweem. See pylab_examplespsd_demo2. new in 0. but in principle it should to work there as well.3. In addition.3.3.Matplotlib. and an optional where argument 19. and pylab_examples-psd_demo3. can be orders of magnitude faster than the existing backends. It hasn’t been tested with ipython yet.py -dmacosx 19.3 Native OS X backend Michiel de Hoon has provided a native Mac OSX backend that is almost completely implemented in C.3. The changes should increase MATLAB compatabililty and increase scaling options.4 psd amplitude scaling Ryan May did a lot of work to rationalize the amplitude scaling of psd() and friends.4 179 . or run your script with: > python myfile.

0 1.4 notes from the CHANGELOG: Added mdehoon’s native macosx backend from sf patch 2179017 . csd.0 1. 19.5 2.5 1.5 2. Ther ArtistInspector could use a little refactoring now since there is duplication of effort between the rest out put and the non-rest output . pprinted strings instead .6 Lots more Here are the 0.0 1.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.0 1.Matplotlib.5 0.harcopy. to format the docstrings differently for hardcopy and other use.1 2.5 1.0 2.5 0. Having all the rest markup in the ipython shell also confused the docstrings. What’s new in matplotlib . -RM 180 Chapter 19.JDH Removed the prints in the set_*style commands. Release 1.0 0.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 ﬁlling. optionally.3.5 1.0 0.0 0.5 1. scale all densities by the sampling frequency.0.0 0.JDH Updated spectral methods (psd. etc. This gives better MATLAB compatibility.98.) to scale one-sided densities by a factor of 2 and. eg setp and getp. I added a new rc param docstring.

py are reorganized as subclasses of the Style classes. dates) to Axes. -MGD drop the deprecated "new" keyword of np.8 1.4 181 . -JJL The transmuter classes in the patches.0 n=1 n=2 n=3 n=4 0. including baseline adjustment of the multiline texts so that it is center aligned.2 or later. -JJL 19. new in 0.g.2 0.0 0.8 0. -JJL Fixed a bug in the new legend class that didn’t allowed a tuple of coordinate vlaues as loc.Matplotlib.0 0. Release 1.4 0. -JJL Fixed a bug in svg backend that new_figure_manager() ignores keywords arguments such as figsize. A few more box and arrow styles are added.histogram() for numpy 1.1 1.4 0.fill_between.6 0.0 Fixed alignment of ticks in colorbars. etc.98. Also applied some changes for better look.3.0.2 0. -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. -RM Added fancybox keyword to legend.6 0.

1 square sawtooth roundtooth rarrow larrow round4 round <|<|-|> ]]-[ fancy simple wedge |-| 182 Chapter 19. What’s new in matplotlib .0.Matplotlib. Release 1.

5 1.1 1.MGD Added static helper method BrokenHBarCollection.MM Added rcParam axes. . See examples/pylab/fill_between.0 1.py .98.JJL Fixed histogram autoscaling bug when bins or range are given explicitly (fixes Debian bug 503148) .unicode_minus which allows plain hypen for minus when False .5 fill between where 1.5 2.DSD Reimplementaion of the legend which supports baseline alignement. patch by Erik Tollerud JJL Fix crash in log ticking.0. new in 0.0 0. .5 0.JDH Add x_isdata and y_isdata attributes to Artist instances. Release 1.0 0.3.0 1.4 183 .span_where and Axes/pyplot method fill_between.0 Improve checks for external dependencies.0 0. and expand mode. using subprocess (instead of deprecated popen*) and distutils (for version checking) . multi-column.5 1.JDH Added scatterpoints support in Legend.Matplotlib.5 0. and use them to determine whether either or both coordinates are used when 19.

EF Update the psd().JKS Add path simplification support to paths with gaps.Matplotlib. under the hood. csd().1 updating dataLim.RM Fix handling of c kwarg by scatter.JKS set_xlim.image. and specgram() methods of Axes and the csd() cohere(). axvline. This is used to fix autoscaling problems that had been triggered by axhline. and specgram() functions in mlab to be in sync with the changes to psd().RM and EF Fix a possible EINTR problem in dviread. axvspan. .EF 184 Chapter 19.JKS Added ’scilimits’ kwarg to Axes.EF Fix problem with AFM files that don’t specify the font’s full name or family name.MM Fixed bug in pdf backend: if you pass a file object for output instead of a filename. in a wep app.ma string array scalars. . respecitively. See examples/misc/image_thumbnail. we now flush the object at the end. ylim now return a copy of the viewlim array to avoid modify inplace surprises Added image thumbnail generating function matplotlib. These are added in a way that does not change the API. . these all call the same core to do computations. What’s new in matplotlib . e. generalize is_string_like to accept numpy and numpy.MGD Added Jae Joon’s fancy arrow. . which might help when saving pdf files from the qt backend. In fact. based on suggestion by Jae-Joon Lee.py Autoscaling is now supported with shared axes . cohere().psd() to allow controlling of zero padding and returning of negative frequency components.EF Experimental new kwarg borderpad to replace pad in legend. box and annotation enhancements -see examples/pylab_examples/annotation_demo2.JKS Fix bug with zoom to rectangle and twin axes . . for easy access to the set_powerlimits method of the major ScalarFormatter.ticklabel_format() method. .g. Release 1. .0.JDH Applied scatleg patch based on ideas and work by Erik Tollerud and Jae-Joon Lee. . .thumbnail. . . axhspan.RM Add ’pad_to’ and ’sides’ parameters to mlab.py .EF Fixed exception in dviread that happened with Minion .

MM Fix step plots with log scale .DMK Fix backtick in Postscript output. Patch by Jae-Joon Lee. .MGD Fix masked arrays with markers in non-Agg backends .98.EF Introduce drawstyles for lines.MGD 19. .3.MGD Fix log with base 2 .4 185 .EF Added support for multiple histograms with data of different length .MGD Added support for bilinear interpolation in NonUniformImage. Also fixed plot to handle empty data arrays. "path.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. . added ability to select points and stop point selection with keyboard in ginput and manual contour labeling code.0. PS and SVG). new in 0.EF Fix hatching in PS backend . Legends always use drawstyle ’default’. Finally. patch by Gregory Lielens. . fixed contour labeling bug.Matplotlib.MGD Add "filled" kwarg to Path. and fixed handling of markers in figlegend.simplify" must be set to True in matplotlibrc for this to work. .py Also. .JKS Fix conversion of quadratic to cubic Bezier curves in PDF and PS backends.EF Fix polar interpolation to handle negative values of theta .intersects_bbox. .intersects_path and Path. .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.JKS Added 5-point star marker to plot command q. . based on patch by Tony Yu.MM Fixed quiver and quiverkey bugs (failure to scale properly when resizing) and added additional methods for determining the arrow angles . Release 1.1 Allow spy to ignore zero values in sparse arrays.MGD Changed full arrows slightly to avoid an xpdf rendering problem reported by Friedrich Hagedorn. Transparently split linestyles like ’steps--’ into drawstyle ’steps’ and linestyle ’--’.

MGD Fix locale problems in SVG backend .JSW improve interactive pan/zoom in qt4 backend on windows . What’s new in matplotlib .MGD fix quiver so masked values are not plotted .1 Fix clip_on kwarg so it actually works correctly . path simplification (which does not handle NaNs or infs) will be turned off automatically when infs or NaNs are present.MGD and EF 186 Chapter 19. In particular.Matplotlib.0.DSD Fix more bugs in NaN/inf handling. Release 1. Also masked arrays are now converted to arrays with NaNs for consistent handling of masks and NaNs .

1 alone or in any derivative version. BY WAY OF EXAMPLE. OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING. analyze. that JDH’s License Agreement and JDH’s notice of copyright. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 1. and otherwise use matplotlib 1.0. Non-BSD compatible licenses (eg LGPL) are acceptable in matplotlib Toolkits.1 License agreement for matplotlib 1. distribute.0. then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 1. royalty-free. BUT NOT LIMITATION. and the Individual or Organization (“Licensee”) accessing and otherwise using matplotlib software in source or binary form and its associated documentation. See the Open Source Initiative licenses page for details on individual licenses. see Testing.1. test..0. “Copyright (c) 2002-2009 John D.1 1.0. prepare derivative works.1 FOR ANY INCIDENTAL.1 alone or in any derivative version prepared by Licensee. 2. This License Agreement will automatically terminate upon a material breach of its terms and conditions. EXPRESS OR IMPLIED. Hunter (“JDH”). and wants to make the derivative work available to others as provided herein.e. and its license is based on the PSF license. JDH hereby grants Licensee a nonexclusive.0.0. 4. OR ANY DERIVATIVE THEREOF. 187 . however.1 available to Licensee on an “AS IS” basis. SPECIAL. DISTRIBUTING. For a discussion of the motivations behind the licencing choice.1 or any part thereof. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 1. JDH MAKES NO REPRESENTATIONS OR WARRANTIES.0. JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 1. perform and/or display publicly.0. This LICENSE AGREEMENT is between John D. 3. i. Hunter.0. JDH is making matplotlib 1.1. All Rights Reserved” are retained in matplotlib 1.CHAPTER TWENTY LICENSE Matplotlib only uses BSD compatible code. world-wide license to reproduce. OR OTHERWISE USING MATPLOTLIB 1. 20. EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. Subject to the terms and conditions of this License Agreement. provided. 6.

installing or otherwise using matplotlib 1. Nothing in this License Agreement shall be deemed to create any relationship of agency.0.0. or any third party. Licensee agrees to be bound by the terms and conditions of this License Agreement.1.1 7. or joint venture between JDH and Licensee. partnership. 8. Release 1.Matplotlib. 188 Chapter 20. 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 . By copying.

Jim Benson provided the patch to handle vertical mathttext. Charles Twardy provided the impetus code for the legend class and has made countless bug reports and suggestions for improvement. and added a number of new marker types to plot.CHAPTER TWENTYONE CREDITS matplotlib was written by John Hunter and is now developed and maintained by a number of active developers. He also wrote the support for dropped axis spines and the buildbot unit testing infrastructure which triggers the JPL/James Evans platform speciﬁc builds and regression test image comparisons from svn matplotlib across platforms on svn commits. and has provided many suggestions and a lot of insight to the overall design and organization of matplotlib. Jared Wahlstrand wrote the initial SVG backend. Special thanks to those who have made valuable contributions (roughly in order of ﬁrst contribution by date) Jeremy O’Donoghue wrote the wx backend Andrew Straw provided much of the log scaling architecture. and provided many examples. Steve Chaplin served as the GTK maintainer and wrote the Cairo and GTKCairo backends. David Moore wrote the paint backend (no longer used) Todd Miller supported by STSCI contributed the TkAgg backend and the numerix module. which allows matplotlib to work with either numeric or numarray. and added support for legending scatter plots. John Gill wrote the table class and examples. free-standing. with much pain and suﬀering. 189 . the ﬁll command. Perry Greenﬁeld supported by STSCI overhauled and modernized the goals and priorities page. platform independent font manager with a WC3 compliant font ﬁnder and cache mechanism and ported truetype and mathtext to PS. He also ported image support to the postscript backend. PIL support for imshow. Paul Barrett supported by STSCI overhauled font management to provide an improved. implemented an improved colormap framework. helped with support for auto-legend placement. Gary Ruben made many enhancements to errorbar to support x and y errorbar plots.

and did the lions share of the psfrag LaTeX support for postscript. which is the basis for the experimental traited mpl conﬁguration. datetime support. and wrote the site. in addition to ongoing support and enhancements in performance.conf build and runtime conﬁguration support.py and TextWithDash. masked array. He has made substantial contributions to extending and maintaining the PS and Qt backends. and wrote TConﬁg. James Evans and colleagues at the JPL collaborated on the QtAgg backend and sponsored development of a number of features including custom unit types. Jeﬀrey Whitaker at NOAA wrote the Basemap tookit Sigve Tjoraand. scale free ellipses.Matplotlib.1 Gregory Lielens provided the FltkAgg backend and several patches for the frontend. broken bar plots and more. He also provided the matshow() command. Fernando Perez has provided numerous bug reports and patches for cleaning up backend imports and expanding pylab functionality. The brainvisa Orsay team and Fernando Perez added Qt support to ipython in pylab mode. Credits . to tex support and to the get_sample_data handler 190 Chapter 21. and added support for irregularly sampled images. and provided matplotlib support in the pylab mode for ipython.cfg and matplotlib. Ted Drain. Darren Dale did the work to do mathtext exponential labeling for log plots. added improved support for scalar formatting. Daishi Harada added support for “Dashed Text”. and support for log ticking with alternate bases and major and minor log ticking. Nicolas Young added support for byte images to imshow. See dashpointlabel. pcolor. Charlie Moad contributed work to matplotlib’s Cocoa support and has done a lot of work on the OSX and win32 binary releases. Jouni K. including contributions to toolbar2. which are more eﬃcient in CPU and memory.0. James Amundson did the initial work porting the qt backend to qt4 Eric Firing has contributed signiﬁcantly to contouring. Baptiste Carvello provided the key ideas in a patch for proper shared axes support that underlies ganged plots and multiscale plots. The JPL team wrote the unit testing image comparison infrastructure for regression test image comparisons. Nadia Dencheva supported by STSCI provided the contouring and contour labeling code. Andrew Dalke of Dalke Scientiﬁc Software contributed the strftime formatting code to handle years earlier than 1900. Paul Mcguire provided the pyparsing module on which mathtext relies. image and quiver support. and made a number of optimizations to the matplotlib mathtext grammar. Release 1. Jochen Voss served as PS backend maintainer and has contributed several bugﬁxes. He setup the infrastructure for the sphinx documentation that powers the mpl docs. Seppänen wrote the PDF backend and contributed numerous ﬁxes to the code. design and code quality in most aspects of matplotlib.

wrote the axes grid toolkit. John Porter. Jonathon Taylor and Reinier Heeres John Porter wrote the mplot3d module for basic 3D plotting in matplotlib. Release 1. Jae-Joon Lee implemented fancy arrows and boxes. and with Alex Mont contributed fast rendering code for quadrilateral meshes. much better font and unicode support.0. and feature and performance enhancements across the matplotlib code base. implementing Knuth’s box layout algorithms. and has made numerous contributions to the code and documentation 191 . and is responsible for numerous bug-ﬁxes.1 Paul Kienzle improved the picking infrastruture for interactive plots. and Jonathon Taylor and Reinier Heeres ported it to the refactored transform trunk.Matplotlib. He also rewrote the transformation infrastructure to support custom projections and scales. saving to ﬁle-like objects across backends. rewrote the legend support to handle multiple columns and fancy text boxes. Michael Droettboom supported by STSCI wrote the enhanced mathtext support.

Credits .Matplotlib. Release 1.0.1 192 Chapter 21.

Part II The Matplotlib FAQ 193 .

.

the best way to test your install is by running a script.1 Report a compilation problem See Report a problem. 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. If not. 22.2 matplotlib compiled ﬁne. but nothing shows up with plot The ﬁrst thing to try is a clean install and see if that helps. Open up a UNIX shell or a DOS command 195 .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. rather than working interactively from a python shell or an integrated development environment such as IDLE which add additional complexities.CHAPTER TWENTYTWO INSTALLATION FAQ Contents • Installation FAQ – Report a compilation problem – matplotlib compiled ﬁne.

3. 22.matplotlib conﬁguration directory. 22. 22. At this point you might want to make sure you understand matplotlib’s conﬁguration process. Release 1. Something like simple_plot. see Report a problem.matplotlib conﬁguration directory.1 prompt and cd into a directory containing a minimal example in a ﬁle.3. 2. Use Start → Control Panel to start the Add and Remove Software utility.2.3. 22.py --verbose-helpful This will give you additional information about which backends matplotlib is loading.py. To cleanly rebuild: 1. Run: easy_install -m PackageName 3. 2. Delete the caches from your .3]) show() and run it with: python simple_plot.matplotlib conﬁguration directory. or for example: from pylab import * plot([1.2 Windows installer 1. version information.py clean does not properly clean the build directory.0. Delete the caches from your . governed by the matplotlibrc conﬁguration ﬁle which contains instructions within and the concept of the matplotlib backend.3 Cleanly rebuild and reinstall everything The steps depend on your platform and installation method. 2. Installation FAQ . Delete any . and more.1 Easy Install 1.egg ﬁles or directories from your installation directory.Matplotlib.3 Source install Unfortunately: python setup. and does nothing to the install directory. Delete the build directory in the source tree 196 Chapter 22. Delete the caches from your . If you are still having trouble.

There is more information on using Subversion in the developer docs. just do: > svn update When you run svn update. There are two types of backends: user interface 22. Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. ie the plotting code. the “frontend” is the user facing code.0.1 3. you need to run the python setupegg develop command again to compile them. and each of these capabililities is called a backend. you are all set. Delete any matplotlib directories or eggs from your installation directory <locating-matplotlibinstall> 22.py develop This creates links in the right places and installs the command line script to the appropriate places. Some people embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications.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. 22. Install from svn 197 .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. matplotlib can target diﬀerent outputs.6 Backends 22.net/svnroot/matplotlib/trunk/matplotlib matplotlib and build and install as usual with: > cd matplotlib > python setup. matplotlib targets many diﬀerent use cases and output formats. If C ﬁles have changed.5 Install from git See Using git.svn. if you want to update your matplotlib at any time.4. Others use matplotlib in batch scripts to generate postscript images from some numerical simulations.4 Install from svn Checking out the main source: svn co https://matplotlib.sourceforge. Release 1. Then. whereas the “backend” does all the dirty work behind the scenes to make the ﬁgure. if the output shows that only Python ﬁles have been updated.Matplotlib. 22.6. To support all of these use cases. and still others in web application servers to dynamically serve up graphs.

There are a two primary ways to conﬁgure your backend. The canonical renderer for user interfaces is Agg which uses the antigrain C++ library to make a raster (pixel) image of the ﬁgure. with GTK.pyplot or matplotlib. eg WXAgg.use(’PS’) # generate postscript output by default If you use the use directive. It gives you the option of running your scripts in batch or working interactively from the python shell. just set your backend to TkAgg. PDF. some of the user interfaces support other rendering engines. If however. To make things a little more customizable for graphical user interfaces. GTKAgg. read on.pylab. TkAgg.. This will do the right thing for 95% of the users. with the least amount of hassles. or other image formats.0. or need a better understanding of what is going on.. PS). 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. One is to set the backend parameter in you matplotlibrc ﬁle (see Customizing matplotlib): backend : WXAgg # use wxpython with antigrain (agg) rendering The other is to use the matplotlib use() directive: import matplotlib matplotlib. or a web application server (Matplotlib in a web application server). png jpg tiﬀ . and just want to get cranking. macosx.. Release 1. All of the user interfaces can be used with agg rendering. tkinter.. CocoaAgg. you can also select GDK rendering (backend GTK) or Cairo rendering (backend GTKCairo). Vector graphics languages issue drawing commands like “draw a line from this point to this point” and hence are scale free. qt. you want to write graphical user interfaces. and raster backends generate a pixel represenation of the line whose accuracy depends on a DPI setting. matplotlib separates the concept of the renderer (the thing that actually does the drawing) from the canvas (the place where the drawing goes).Matplotlib. For the rendering engines. If you are unsure what to do. QTAgg. Installation FAQ . wxpython. one can also distinguish between vector or raster renderers. this must be done before importing matplotlib. and is smart enough to do the right thing when you ask for postscript. SVG. or ﬂtk) and hardcopy backends to make image ﬁles (PNG. or pdf. For example.1 backends (for use in pygtk. In addition. 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 .

4 There is a bug in PyGTK-2. you have two choices: a mpkg installer. print matplotlib.4.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.rc1py2. we recommend the enthought python distribution EPD for OS X (which comes with matplotlib and much more) or the MacPython or the oﬃcial OS X version from python.7. matplotlib.org. The mkpg installer will have a “zip” extension. again depedending on your python version.__version__. OS-X questions 199 . You need to unzip this ﬁle using either the “unzip” command on OSX. When you double click on the resultant mpkd directory.5macosx10. many users have had trouble with it so there are alternatives. which will have a name like ﬁle:matplotlib-0. matplotlib.app.0. This directory may not be in your python path. and OSX versions. it will run the Installer.mpkg.0. which you can install via setuptools easy_install.2 Compile matplotlib with PyGTK-2.99.5_mpkg. and will have a name like ﬁle:matplotlib-0.2 Installing OSX binaries If you want to install matplotlib from one of the binary installers we build.rc1-py2.__file__’ If you get an error like: 22. If it is feasible for you.1 Which python for OS X? Apple ships with its own python.Matplotlib.h to add the G_BEGIN_DECLS and G_END_DECLS macros.app. You need to edit pygobject.5. or simply double clicking on it to run StuﬀIt Expander.7. which is a typical Installer.5-macosx10.0. 22.7 OS-X questions 22.zip depending on the python. prompt you for a password if you need system wide installation privileges.6. so you can test your installation with: > python -c ’import matplotlib. and install to a directory like ﬁle:/Library/Python/2. const char *typename_. Release 1. and rename typename parameter to typename_: + const char *typename.99. 22.7. or an binary OSX egg.5/site-packages/.

98 from the matplotlib download site.egg Processing matplotlib-0. it’s annoying.99. easy_install will install it from the disk.3-fat.5-macosx-10.5-i386.5/site-packages/ matplotlib-0. Reading http://matplotlib.7.0’) If you rename matplotlib-0.matplotlib”).egg Some users have reported problems with the egg for 0.98. 200 Chapter 22.98.egg. in <module> ImportError: No module named matplotlib then you will need to set your PYTHONPATH.5/site-packages:$PYTHONPATH See also ref:environment-variables.0 error: Could not find suitable distribution for Requirement.0-py2.egg to matplotlib-0.parse(’matplotlib==0.rc1-py2. Remove the ~/.98.egg removing ’/Library/Python/2.98.4 Building and installing from source on OSX with EPD If you have the EPD installed (Which python for OS X?). 22.0-py2.net Reading http://cheeseshop..0-py2. line 1.5.98. it might turn out to be rather tricky to install a new version of matplotlib from source on the Mac OS 10.python.3 No local packages or download links found for matplotlib==0.3-fat. still. getting an error: > easy_install .sourceforge.0-py2.5-macosx-10.org/pypi/matplotlib/0..5macosx-10.5 . Installation FAQ .0-py2.Matplotlib. with easy_install. eg: export PYTHONPATH=/Library/Python/2.1 Traceback (most recent call last): File "<string>".7.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). and manually install it with > easy_install –install-dir=~/dev/lib/python2. at least sometimes: 0.98.98. Renaming is all it takes to install them.0.snip. Here’s a procedure that seems to work.0./matplotlib-0.5.3-fat. We recommend you download the latest egg from our download site directly to your harddrive. but the naming conventions for OSX eggs appear to be broken (see below) so there is no guarantee the right egg will be found. Release 1.91. which prevents their installation through easy_install..matplotlib folder (“rm -rf ~/.5-macosx-10.5/site-packages/matplotlib-0. You can try: > easy_install matplotlib which should grab the latest egg from the sourceforge site.. Many Mac OS X eggs with cruft at the end of the ﬁlename. 22.

98. removing all occurrences of the string -arch ppc. Save the following as a shell script .5.py build python setup.sourceforge.Matplotlib.svn.1 Binary installers for windows If you have already installed python.0.8.sdk into MacOSX10. In /Library/Frameworks/Python.3 to MACOSX_DEPLOYMENT_TARGET=10. LDFLAGS. just in case): /Library/Frameworks/Python.5) which have the exe extension.5/config/Makefile. for example . 22./install-matplotlib-epd-osx.5.8 Windows questions 22.4u.5-macosx-10. Run this script (for example sh . PKG_CONFIG_PATH. you can use one of the matplotlib binary installers for windows – you can get these from the sourceforge download site.sdk 2..3-fat. ARCHFLAGS). or simply type the commands in the terminal command line.sf.Y/site-packages/easy-inst (where X. 3. builds and installs it.framework/Versions/Current/lib/python2. Windows questions 201 . checks out the source from svn.1 1.sh NAME=matplotlib VERSION=0_99 PREFIX=$HOME #branch="release" branch="trunk" if [ $branch = "trunk" ] then echo getting the trunk svn co https://matplotlib.5 if you installed Python 2. This script sets some local variable (CFLAGS.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.svn.sh) in the directory in which you want the source code to be placed. changing the line MACOSX_DEPLOYMENT_TARGET=10.egg).8.py install #--prefix=$PREFIX #Use this if you don’t want it installed into your de cd .5 and changing the occurrences of MacOSX10. Choose the ﬁles that match your version of python (eg py2./install-matplotlib-epd-osx.2n2-py2.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 ./matplotlib-0. removes previous installations.framework/Versions/Current/lib/pythonX. 22. Edit the ﬁle (make a backup before you start. If you haven’t already installed python. The backend seems to be set to MacOSX.net/svnroot/$NAME/trunk/$NAME $NAME cd $NAME fi if [ $branch = "release" ] then echo getting the maintenance branch svn co https://matplotlib. Release 1.

There are also two packaged distributions of python that come preloaded with matplotlib and many other tools like ipython. scipy.1 you can get the oﬃcial version from the python web site. numpy. but you get everything with a single click installer. vtk and user interface toolkits. Installation FAQ . y) 202 Chapter 22. • the enthought python distribution EPD • python (x. Release 1.Matplotlib. These packages are quite large because they come with so much.0.

1 Matplotlib.2) y = sin(x) 203 . plt. We have been gradually converting the matplotlib examples from pure MATLAB-style. which imports everything from pylab and makes plotting fully interactive. to a preferred style in which pyplot is used for some convenience functions.CHAPTER TWENTYTHREE USAGE Contents • Usage – Matplotlib. Example.show. plt.pyplot as plt import numpy as np Then one calls. and pyplot: how are they related? Matplotlib is the whole package. and matplotlib. either pyplot or the object-oriented style is used for the remainder of the plotting code. This is what you get if you use the ipython shell with the -pylab option.pyplot is a module in matplotlib.arange. np. pylab is a module in matplotlib that gets installed alongside matplotlib. plt.ﬁgure. making that namespace (or environment) even more MATLABlike. Pyplot provides a MATLAB-style state-machine interface to the underlying object-oriented plotting library in matplotlib. np. pure MATLAB-style: from pylab import * x = arange(0. the imports at the top are: import matplotlib.zeros.pi. Pylab combines the pyplot functionality (for plotting) with the numpy functionality (for mathematics and for working with arrays) in a single namespace. pylab. using “from pylab import *”. and numpy is used explicitly for numeric array operations.plot. In this preferred style. np. and pyplot: how are they related? 23. pylab. etc. for example. 0. 10.

For more complicated applications. 10.2) y = np. y) show() Now in preferred style.arange(0.plot(x. 0.2) y = np. 204 Chapter 23. Usage . but still using pyplot interface: import matplotlib.arange(0.1 plot(x. the explicitness and clarity become increasingly valuable.sin(x) fig = plt. why do all the extra typing required as one moves away from the pure MATLAB-style? For very simple things like this example. y) plt.pyplot as plt import numpy as np x = np. the only advantage is educational: the wordier styles are more explicit. 0. 10.add_subplot(111) ax. y) plt. but object-orientation for the rest: import matplotlib. more clear as to where things come from and what is going on.plot(x.figure() ax = fig. Release 1.show() And using pyplot convenience functions. and the richer and more complete object-oriented interface will likely make the program easier to write and maintain.sin(x) plt.pyplot as plt import numpy as np x = np.0.Matplotlib.show() So.

CHAPTER TWENTYFOUR HOWTO Contents • Howto – Plotting: howto * Find all objects in ﬁgure of a certain type * Save transparent ﬁgures * Save multiple plots in one pdf ﬁle * Move the edge of an axes to make room for tick labels * Automatically make room for tick labels * Conﬁgure 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 .

findobj(text.set_alpha(0.1 Find all objects in ﬁgure 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 ﬁlter function).Rectangle instance called patch and the axes has a Rectangle instance called patch.pdf’) 206 Chapter 24.figure() fig.3 Save multiple plots in one pdf ﬁle Many image ﬁle formats can only have one image per ﬁle.5) If you need all the ﬁgure elements to be transparent.1 24. linewidth.5) ax = fig.Matplotlib. For example.backend_pdf import PdfPages pp = PdfPages(’multipage.1. edgecolor. there is currently no global alpha setting. y. The ﬁgure has a matplotlib. but you can set the alpha channel on individual elements. If you need ﬁner grained control. eg you do not want full transparency or you to aﬀect the screen displayed version as well. the following snippet ﬁnds every object in the ﬁgure which has a set_color property and makes the object blue: def myfunc(x): return hasattr(x. eg: ax.plot(x. but will not aﬀect the displayed image on the screen. Release 1. alpha=0. Currently only the pdf backend has support for this.set_color(’blue’) You can also ﬁlter on class instances: import matplotlib.set_alpha(0.1.2 Save transparent ﬁgures The savefig() command has a keyword argument transparent which.Text): o.backends.set_fontstyle(’italic’) 24. Howto .add_subplot(111) ax. ’set_color’) for o in fig.patch. if True. linestyle. you can set the alpha properties directly. but some formats support multi-page ﬁles. alpha).findobj(myfunc): o.1 Plotting: howto 24.5) 24.0.1. You can set any property on them directly (facecolor. ﬁrst initialize the ﬁle: from matplotlib.patches.text as text for o in fig.set_xlabel(’volts’. To make a multi-page pdf ﬁle. will make the ﬁgure and axes backgrounds transparent when saving. Eg: fig = plt.5) ax. alpha=0.patch.

1 You can give the PdfPages object to savefig(). 24.savefig() Finally.add_subplot(111) You can control the defaults for these parameters in your matplotlibrc ﬁle. you don’t know ahead of time what your 24. which allows you to specify the location explicitly: ax = fig. 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.4 Move the edge of an axes to make room for tick labels For subplots.Figure. and top as well as the horizontal and vertical spacing between multiple rows and columns using the matplotlib.figure. height]) where all values are in fractional (0 to 1) coordinates. with their defaults left = 0. you can control the default spacing on the left.figure() fig.subplots_adjust() method (in pyplot it is subplots_adjust()).2) ax = fig.1.125 the left side of the subplots of the ﬁgure right = 0. to move the bottom of the subplots up to make room for some rotated x tick labels: fig = plt. But in some cases.2 # the bottom of the subplots of the figure The other parameters you can conﬁgure are.5 Automatically make room for tick labels In most use cases. format=’pdf’) A simpler way is to call PdfPages. Release 1.1.0. See axes_demo.1 the bottom of the subplots of the ﬁgure top = 0. right.py for an example of placing axes manually.add_axes([left.subplots_adjust(bottom=0. bottom.9 the top of the subplots of the ﬁgure wspace = 0.Figure. but you have to specify the format: savefig(pp.Matplotlib.2 the amount of height reserved for white space between subplots If you want additional control. bottom.9 the right side of the subplots of the ﬁgure bottom = 0.subplot.bottom : 0. For example.2 the amount of width reserved for blank space between subplots hspace = 0.add_axes() method). you would set: figure.figure.1. width. see Customizing matplotlib. For example.close() 24.savefig: pp. the multipage pdf object has to be closed: pp. you can create an Axes using the axes() command (or equivalently the ﬁgure matplotlib. Plotting: howto 207 . to make the above setting permanent.

backend_bases. really. All Line2D objects support a line (solid. The tick linewidth is controlled by the “markeredgewidth” property: 208 Chapter 24. tick). etc) and a marker (circle.Figure.draw() return False fig.transFigure) bboxes.RendererBase instance. Howto .text.width: # we need to move it over fig.transforms as mtransforms fig = plt. One way to solve this chicken and egg problem is to wait until the ﬁgure is draw by connecting (matplotlib.draw()).figure.union(bboxes) if fig.0.1 tick labels will be.inverse_transformed(fig. and then do something with it.mpl_connect()) to the “on_draw” signal (DrawEvent) and get the window extent there.append(bboxi) # this is the bbox that bounds all the bboxes. again in relative # figure coords bbox = mtransforms.Text.pyplot as plt import matplotlib.FigureCanvasBase.width) # pad a little fig. ’labels’)) def on_draw(event): bboxes = [] for label in labels: bbox = label.1) of each of the labels and uses it to move the left of the subplots over so that the tick labels ﬁt in the ﬁgure import matplotlib.6 Conﬁgure the tick linewidths In matplotlib.set_yticks((2.Matplotlib.set_yticklabels((’really.plot(range(10)) ax.subplots_adjust(left=1.subplotpars. eg move the left of the canvas over.5. The matplotlib. or how large they will be (data and labels outside your control may be being fed into your graphing application). is not known until the ﬁgure is drawn (matplotlib.. but there is a rub. which is used to calculate the text size. and you may need to automatically adjust your subplot parameters based on the size of the tick labels.get_window_extent() # the figure transform goes from relative coords->pixels and we # want the inverse of that bboxi = bbox.figure() ax = fig.text. Here is that gets a bounding box in relative ﬁgure coordinates (0. dashed. see Event handling and picking. really’.show() 24.Bbox.mpl_connect(’draw_event’.Text instance can report its extent in window coordinates (a negative x coordinate is outside the window).1*bbox. Release 1.1.add_subplot(111) ax.canvas. After the window is drawn and the text instance knows its renderer. you can call matplotlib. the ticks are markers.backend_bases. Any matplotlib.7)) labels = ax. square.get_window_extent().canvas. on_draw) plt. ’long’.left < bbox.

Matplotlib.1. are markerfacecolor. By default.7 Align my ylabels across multiple subplots If you have multiple subplots over one another.get_yticklines(): line.1 labels long really.plot(range(10)) for line in ax. markersize. 24.1. and the y data have diﬀerent scales.add_subplot(111) ax. Release 1. Plotting: howto 209 . and the manual setting in the right subplots.figure() ax = fig. see Axis containers and Tick containers.get_xticklines() + ax. matplotlib positions the x location of the ylabel so that it does not overlap any of the y ticks. 24. and all markers.0. you can often get ylabels that do not align vertically across the multiple subplots.pyplot as plt fig = plt. which can be unattractive. The example below shows the default behavior in the left subplots.show() The other properties that control the tick marker.set_markersize(10) plt. markeredgecolor. really. markeredgewidth. For more information on conﬁguring ticks. You can override this default behavior by specifying the coordinates of the label. really 0 1 2 3 4 5 6 7 8 9 import matplotlib.

/data/aapl.add_subplot(222) ax2.rand(10)) ax4. bbox=box) ax4. eg ﬁnancial time series.set_ylim(0. The solution is to pass in some proxy x-data.5) plt. Release 1. you get large horizontal gaps on periods when there is not data.ticker as ticker r = mlab.set_ylabel(’misaligned 1’.0.plot(np.figure() fig.5) ax2.set_ylabel(’misaligned 2’.set_label_coords(labelx. 2000) ax4 = fig. Howto . bbox=box) ax2. and then use a custom formatter to format these as dates.set_label_coords(labelx.set_title(’ylabels not aligned’) ax1.rand(10)) ax1.1. eg weekends. 2000) ax3 = fig.yaxis.rand(10)) labelx = -0.add_subplot(223) ax3.sort() r = r[-30:] # get the last 30 days 210 Chapter 24. eg evenly sampled indicies. wspace=0.subplots_adjust(left=0.1 import numpy as np import matplotlib.csv2rec(’.random. bbox=box) ax1.random.2.Matplotlib. alpha=0.add_subplot(224) ax4.random.pyplot as plt box = dict(facecolor=’yellow’.pyplot as plt matplotlib.6) ax1 = fig.bbox=box) ax3.plot(2000*np.plot(2000*np.8 Skip dates where there is no data When plotting time series. one often wants to leave out days on which there is no data.set_ylabel(’aligned 1’.mlab as mlab matplotlib.rand(10)) ax2. pad=5.2) fig = plt.csv’) r.show() 24. 0.random.set_ylabel(’aligned 2’.plot(np.yaxis. By passing in dates on the x-xaxis.set_title(’ylabels aligned’) ax2.add_subplot(221) ax1. 0.3 # axes coords ax2 = fig.. The example below shows how to use an ‘index formatter’ to achieve the desired plot: import import import import numpy as np matplotlib.set_ylim(0.

FuncFormatter(format_date)) fig.add_subplot(111) ax.6 0.00 1 2 3 4 5 6 7 8 9 N = len(r) ind = np.8 0. For a discussion of the implementation see pnpoly.show() # the evenly spaced plot indices def format_date(x.arange(N) misaligned 2 plt.1 ylabels not aligned 2000 ylabels aligned 2000 misaligned 1 1000 500 00 1 2 3 4 5 6 7 8 9 1. 0.autofmt_xdate() 24.set_major_formatter(ticker.figure() ax = fig.4 0.6 0. Plotting: howto 211 .0 0. ’o-’) ax.0.adj_close.1.5).5 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].clip(int(x+0.4 0. pos=None): thisind = np. In [25]: import numpy as np 24. N-1) return r.strftime(’%Y-%m-%d’) fig = plt. r. Release 1.nxutils provides two high performance methods: for a single point use pnpoly() and for an array of points use points_inside_poly().xaxis.3 0.8 0.7 0.1 0.plot(ind.9 Test whether a point is inside a polygon The matplotlib.Matplotlib.1.2 0.2 0.9 0.

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 ﬁles (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 diﬀerent axes, turning the axes rectangular frame oﬀ on the 2nd axes to keep it from obscuring the ﬁrst, 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 ﬁgure 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 ﬁgure 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 ﬁgure 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 ﬁgures 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 ﬁgure 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 ﬁgure 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 ﬁgure, pauses the script until the ﬁgure is closed, and then allows the script to continue running until the next ﬁgure 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 diﬀ. If it is feasible, do your diﬀ 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 diﬀ against the entire tree, but rather against a single directory or ﬁle, that is ﬁne, but we do prefer svn diﬀs 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 ﬁx a code bug, please explain your patch in words – what was broken before and how you ﬁxed it. Also, even if your patch is particularly simple, just a few lines or a single function replacement, we encourage people to submit svn diﬀs 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 unmodiﬁed 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 oﬀer. 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 oﬃcial 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 stuﬀ 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 ﬁnd 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 conﬁgured 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 conﬁgure matplotlib for use in these environments. Most importantly, you need to decide what kinds of images you want to generate (PNG, PDF, SVG) and conﬁgure 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 conﬁgured to recognize requests to generate other output formats (PDF, PS, EPS, SVG). The easiest way to conﬁgure 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 conﬁguring 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 ﬁlesystem by calling saveﬁg:

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 ﬁle handle:
**

import sys fig.savefig(sys.stdout)

Here is an example using the Python Imaging Library PIL. First the ﬁgure 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 Scientiﬁc 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 eﬀorts 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 ﬁnd 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 ﬁnd 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 ﬁnd 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 ﬁle 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 diﬀerent conﬁguration 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 ﬁrst: 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 ﬁle (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 signiﬁcantly diminished. Very often, the mere act of trying to minimize your code to the smallest bit that produces the error will help you ﬁnd 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 ﬂags 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 ﬁrst 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 ﬁling 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 ﬁle 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 ﬁles or directories, or reorganized existing ones, are the new ﬁles included in the match patterns in MANIFEST.in. This ﬁle 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 ﬁxing, use svnmerge.py to keep them in sync. See Using svnmerge below.

**26.1.3 Using svnmerge
**

svnmerge is useful for making bugﬁxes 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 bugﬁxes to and the trunk (see above) • Create and commit the bugﬁx on the branch. • Then make sure you svn upped on the trunk and have no local modiﬁcations, 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 speciﬁc 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 conﬂicts (code that must be manually resolved). Correct those conﬂicts, build matplotlib and test your choices. If you have resolved any conﬂicts, you can let svn clean up the conﬂict ﬁles for you:

> svn -R resolved .

svnmerge.py automatically creates a ﬁle 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 git@github.com: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 diﬀerent representations of source code repositories in svnmerge and git.

26.1. Version control

227

Matplotlib, Release 1.0.1

An example git workﬂow

The following is a suggested workﬂow 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 git@github.com: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

transforms as mtrans # OK # OK. if you want to abbreviate 26.2. if there is a ﬁle with tabs or a diﬀerent number of spaces it is a bug – please ﬁx it. • 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. Tell your editor to strip whitespace from line ends when saving a ﬁle. use reindent. though we do not do this throughout. 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. with nothing to the left of the triple quotes. and formatting conventions In general.thing as mthing syntax. To detect and ﬁx these and other whitespace errors (see below).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. the following in your . Please do not commit lines with trailing white space.lines as mlines matplotlib. If a logical line needs to be longer.cbook. please use reindent. There are some modules with names that match commonly used local variable names. Release 1.transforms as mtransforms matplotlib. not hard tabs. as it causes noise in svn diﬀs.py before checking changes into svn.1 import matplotlib. Unless you are sure your editor always does the right thing. The matplotlib. eg matplotlib. do not use an escaped newline. we want to hew as closely as possible to the standard coding guidelines for python written by Guido in PEP 0008. C and C++: .lines or matplotlib.0. Limit line length to 80 characters. if you want to disambiguate # OK.cbook as cbook if cbook. spacing.transforms as transforms matplotlib. It may be preferable to use a temporary variable to replace a single long line with two shorter and more readable lines. The standard indentation unit is always four spaces.colors. Conﬁgure your editor to use spaces. To avoid the clash.py as a command-line script. The former makes it explicit that you are importing a module or package. use parentheses to break it. Keep docstrings uniformly indented as in the example below.emacs will cause emacs to strip trailing white space upon saving for python. If you are an emacs user. Coding guide . again as in the example below.2 Naming. use the preﬁx ‘m’ with the import some.dedent() function is needed to remove excess indentation only if something will be interpolated into the docstring.Matplotlib. eg: import import import import matplotlib.

You can pop the ones to be used locally and pass on the rest.py def text(*args. text=’’.py def __init__(self. they just get passed through the API to the artist constructor which looks for suitably named methods and calls them with the value. **kwargs) draw_if_interactive() return ret text() in simpliﬁed form looks like this. For example. In some cases.Artist. True) if not self.artist. True) scaley = kwargs. Release 1. x.2. If all the keyword args are to be used in the function.e.3 Keyword argument processing Matplotlib makes extensive use of **kwargs for pass-through customizations from one function to another.e. x=0. Style guide 231 . as in the example above.Axes.text. in plot().axes.. **kwargs): t = Text(x=x. **kwargs): scalex = kwargs.text(). I. **kwargs): Artist.add_line(line) lines._get_lines(*args. you may want to consume some keys in the local function.pop(’scalex’. use the key/value keyword args in the function deﬁnition rather than the **kwargs idiom.pylab.1 (add-hook ’python-mode-hook (lambda () (add-hook ’local-write-file-hooks ’delete-trailing-whitespace))) 26. i.2. y=0. fontdict=None. y=y. The deﬁnition of the pylab text function is a simple pass-through to matplotlib.py def text(self. it just passes all args and kwargs on to matplotlib.py def plot(self. no one looks at the keywords.0. s. and not passed on. the use of **kwargs should be reserved for pass-through keyword arguments.__init__(): # in axes.cla() lines = [] for line in self._hold: self. **kwargs): self.Matplotlib. *args.pop(’scaley’. **kwargs): ret = gca().text(*args.update(kwargs) update does the work looking for methods named like set_property if property is a keyword argument.append(line) 26.text(): # in pylab.Text.update() method: illustration) just passes them on to the # in text. **kwargs) and __init__() (again with liberties for matplotlib. y. A typical example is in matplotlib.. withdash=False.__init__(self) self. scalex and scaley are local arguments and the rest are passed on as Line2D() keyword arguments: # in axes. text=s. and let others pass through. As a general rule.

eg.get(’fontsize’. An example is matplotlib.levels)) elif len(args) == 1: .. The requirements are: 1.fmt = kwargs.Line2D: # in lines. eg.Axes.3f ’) colors = kwargs. **kwargs): fontsize = kwargs. In this case. matplotlib. but you still need the **kwargs idiom. 2. *args. Coding guide .ContourLabeler.0.levels indices = range(len(self.artist.lines. it can be diﬃcult for the new user to know which kwargs are supported. single point of conﬁguration so changes to the properties don’t require multiple docstring edits. so you will be forced to use **kwargs. as automated as possible so that as properties change.). python will not allow you to use named keyword args after the *args usage.axes.etc.. Here is an example from matplotlib. 1) self..kwdocd and matplotlib. The functions matplotlib.contour.’ | ’:’ | ’steps’ | ’None’ | ’ ’ | ’’ ] """ Since matplotlib uses a lot of pass-through kwargs. in matplotlib. They combine python string interpolation in the docstring with the matplotlib artist introspection facility that underlies setp and getp.py def clabel(self. Release 1..Matplotlib.kwdoc(Line2D) Then in any function accepting Line2D pass-through kwargs.py def set_linestyle(self. ’%1.artist.3 Documentation and docstrings Matplotlib uses artist introspection of docstrings to support properties. linestyle): """ Set the linestyle of the line ACCEPTS: [ ’-’ | ’--’ | ’-. The kwdocd is a single dictionary that maps class name to a docstring of kwargs. Yes. this is not ideal given python properties or enthought traits. The setter methods use the docstring with the ACCEPTS token to indicate the type of argument the method accepts. 26.clabel(): # in contour..py artist. semilogy().kwdoc() to facilitate this.get(’fmt’. in every function that creates a line (plot(). Matplotlib uses a docstring interpolation scheme to support documentation of every function that takes a **kwargs.lines: # in lines. etc. All properties that you want to support through setp and getp should have a set_property and get_property method in the Artist class.plot(): 232 Chapter 26.kwdocd[’Line2D’] = artist.get(’colors’. That is when you want to use *args to allow variable numbers of nonkeyword args. semilogx(). but it is a historical legacy for now. None) inline = kwargs. None) if len(args) == 0: levels = self. the docs are updated automagically. Eg..1 Note: there is a use case when kwargs are meant to be used locally in the function (not passed on).get(’inline’.

default True.get_sample_data().kwdocd[’Patch’] setting in matplotlib.4.Patch.0. and do not have ready access to the ﬁle:examples directory in which they reside.4 Developing a new backend If you are working on a custom backend. Developing a new backend 233 . if defined.py def plot(self. *args.autoscale_view for more information """ pass plot. which supports Patch kwargs. and these are automatically generated when the website it built to show up both in the examples and gallery sections of the website.cbook.__init__.Matplotlib.5 Writing examples We have hundreds of examples in subdirectories of ﬁle:matplotlib/examples in the trunk.__doc__ docstring outside the class deﬁnition.__doc__) % artist. which can then be accessed using matplotlib. since the artist inspector cannot work until the class is fully deﬁned and we can’t modify the Patch.py is a matplotlib backend in your PYTHONPATH. 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. See Axes. There are some some manual hacks in this case.patches. Thus any example data that is required for the example should be provided through the sample_data svn directory.1 # in axes. eg. if my_backend.dedent(plot. the backend setting in matplotlibrc (Customizing matplotlib) supports an external backend via the module directive.__doc__ = cbook. First get a copy of the repository and svn add your data: 26. matplotlib. are passed on to autoscale_view to determine whether the x and y axes are autoscaled.patches.__init__().py -d module://my_backend 26.kwdocd Note there is a problem for Artist __init__ methods. **kwargs): """ Some stuff omitted The kwargs are Line2D properties: %(Line2D)s kwargs scalex and scaley. violating the “single entry point” requirement above – see the artist.use(’module://my_backend’) • from the command shell with the -d ﬂag: > python simple_plot. 26. Release 1. Many people ﬁnd these examples from the website.

test() To run a single test from the command line. eg.1 svn co https://matplotlib. you can provide a dot-separated path to the module and function.tests. and customizations to the nose testing infrastructure are in matplotlib.dat’) The ﬁle will be fetched from the svn repo using urllib and updated when the revision number changes.svn. (There is other old testing cruft around.Matplotlib. datafile 26. (this is assuming the test is installed): nosetests matplotlib.dat svn commit -m ’added my data’ and then in your example code you can load it into a ﬁle handle with: import matplotlib. Coding guide .6.2) For example.get_sample_data(’mydata. making it easy to write new tests.tests.cbook as cbook fh = cbook.cbook as cbook datafile = cbook. matplotlib. If you prefer just to get the full path to the ﬁle instead of an ﬁle object: import matplotlib.dat’. 234 Chapter 26.test_simplification:test_clipping 26. The tests are in matplotlib.testing. Make sure you have nose installed and type from within Python: import matplotlib matplotlib.) 26. please ignore it while we consolidate our testing to these locations.0.get_sample_data(’mydata.2 Writing a simple test Many elements of Matplotlib can be tested using standard tests.6.tests.test_basic: from nose.tools import assert_equal def test_simple(): ’’’very simple example test’’’ assert_equal(1+1.net/svnroot/matplotlib/trunk/sample_data cp ~/path/to/mydata. asfileobj=False) print ’datafile’.dat sample_data/ cd sample_data svn add mydata.sourceforge. Release 1.1 Running the tests Running the tests is simple.6 Testing Matplotlib has a testing infrastructure based on nose. here is a test from Nose determines which functions are tests by searching for functions beginning with “test” in their name.

testing.spines[’left’]. this test generates a single image and automatically tests it: import numpy as np import matplotlib from matplotlib. it is an expected failure: from nose. Release 1.decorators import knownfailureif @knownfailureif(True) def test_simple_fail(): ’’’very simple example test that should fail’’’ assert_equal(1+1.25)) ax.testing.decorators import image_comparison import matplotlib. Testing 235 .figure() x = np.1)) ax.yaxis. although the following test will fail.pi.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. For example. The correspondence is done by matching ﬁlenames.pyplot as plt @image_comparison(baseline_images=[’spines_axes_positions.2*np.savefig(’spines_axes_positions. The main consideration is that you must specify the “baseline”.spines[’bottom’].tools import assert_equal from matplotlib.Matplotlib.0.set_color(’none’) ax.png’]) def test_spines_axes_positions(): # SF bug 2852168 fig = plt.spines[’top’].6. This allows the test to be added to the test suite and run on the buildbots without causing undue alarm.0.100) y = 2*np.spines[’right’]. For example.6.y) ax. • The correct image gets added to the sample_data respository with the name test_baseline_<IMAGE_FILENAME. images in the image_comparison() decorator. so ensure that: • The ﬁlename given to savefig() is exactly the same as the ﬁlename given to image_comparison() in the baseline_images argument.1) ax.3) 26.set_position((’axes’. you may mark it as a known failing test with the knownfailureif() decorator.set_position((’axes’.1. (See Writing examples above for a description of how to add ﬁles to the sample_data repository.linspace(0.png>.set_color(’none’) fig.add_subplot(1.3 Writing an image comparison test Writing an image based test is only slightly more diﬃcult than a simple test.) 26. or expected.1 26.sin(x) ax = fig.0.6.4 Known failing tests If you’re writing a test.set_ticks_position(’right’) ax.plot(x.set_ticks_position(’top’) ax.xaxis.set_title(’centered spines’) ax.

you are required to give the source code to other people and give them the right to redistribute it as well. is allowed. 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. python and TeX.e. which in addition to granting you full rights to the source code including redistribution. gcc. You can also write extension modules for Python and provide them only in binary form.0.tests. If you include code.tests Let’s say you’ve added a new module named matplotlib.7 Licenses Matplotlib only uses BSD compatible code. and we choose a license that was based on the python license (BSD compatible). The best known and perhaps most widely used license is the GPL. If it doesn’t. but there is an important diﬀerence to be considered in the GPL and BSD variants. There are countless other licenses that place speciﬁc restrictions on code reuse. modified or not. include it in your own open source project.Matplotlib. 26. The second major class are the BSD-style licenses (which includes MIT and the python PSF license). append its name to default_test_modules in lib/matplotlib/__init__. you may consider contacting the author and asking them to relicense it. Many of the most famous and widely used open source projects are released under the GPL. I. BSD. There are several reasons why early matplotlib developers selected a BSD compatible license. possibly a toolkit. To add this module to the list of default tests. MIT or compatible license (see the Open Source Initiative licenses page for details on individual licenses).7.6. emacs and sage.1 Note that the ﬁrst argument to the knownfailureif() decorator is a fail condition. carries with it an extra obligation. matplotlib is a python extension. or ‘indeterminate’. sell it. These basically allow you to do whatever you want with the code: ignore it. Distributing binary-only versions of Python. whatever. python itself is released under a BSD compatible license. or link with it. If you bring in code from another project make sure it has a PSF. in the sense that. GPL and LGPL code are not acceptable in the main code base. but make sure you clearly state the licenses you are using. include it in your proprietary product.5 Creating a new module in matplotlib. though we are considering an alternative way of distributing L/GPL code through an separate channel. Coding guide . quoting from the PSF license page: There is no GPL-like "copyleft" restriction.py. which can be a value such as True. If you use GPL code in your own code.test_whizbang_features. Non-BSD compatible licenses are acceptable in matplotlib toolkits (eg basemap). or may be a dynamically evaluated expression. including linux. There is no requirement to release any of your source code. 26. 236 Chapter 26. 26. Famous projects released under a BSD-style license in the permissive sense of the last paragraph are the BSD operating system.. False. Release 1. your product must be released under a GPL compatible license.1 Why BSD compatible? The two dominant license variants in the wild are GPL-style and BSD-style.

The ﬁnal reason behind the licensing choice is compatibility with the other python extensions for scientiﬁc computing: ipython. the enthought tool suite and python itself are all distributed under BSD compatible licenses. they want to retain the right to release some proprietary code.0. Two of the matplotlib backends (FLTK and WX) were contributed by private companies. and many software companies will not use GPL code in software they plan to distribute. numpy. numpy.1 Also. out of legitimate concern that use of the GPL will “infect” their code base by its viral nature. In eﬀect.Matplotlib. such as enthought.7. Licenses 237 . even a boring one. scipy. scipy. we wanted to attract as many users and developers as possible. the enthought tool suite and python itself are all distributed under BSD compatible licenses. Release 1. Companies and institutions who use matplotlib often make signiﬁcant contributions. The other reason is licensing compatibility with the other python extensions for scientiﬁc computing: ipython. 26. because they have the resources to get a job done. even those that are highly committed to open source development.

Release 1.1 238 Chapter 26.Matplotlib. Coding guide .0.

rst extension is not necessary) in the table of contents.rst. Sphinx-0.5 or later is required.1 Getting started The documentation for matplotlib is generated from ReStructured Text using the Sphinx documentation generation tool.org/birkenfeld/sphinx/ cd sphinx python setup. doc/api and doc/faq. Additional ﬁles can be added to the various guides by including their base ﬁle name (the .py html or: . developers guide. To build the users guide in html format.rst ﬁle for the users guide. The output produced by Sphinx can be conﬁgured by editing the conf. such as: 239 . we want to make navigating the Matplotlib documentation as easy as possible. and faqs.2 Organization of matplotlib’s documentation The actual ReStructured Text ﬁles are kept in doc/users.py to build a pdf. The main entry point is doc/index./make. or pass no arguments to build everything. which pulls in the index. cd into doc/ and do: python make. so most developers work from the sphinx source repository (Mercurial based) because it is a rapidly evolving project: hg clone http://bitbucket.py ﬁle located in the doc/.CHAPTER TWENTYSEVEN DOCUMENTING MATPLOTLIB 27.py install The documentation sources are found in the doc/ directory in the trunk.py html you can also pass a latex ﬂag to make. You might still run into problems. doc/devel. The documentation suite is built as a single document in order to make the most eﬀective use of cross referencing. api reference. 27. It is also possible to include other documents through the use of an include statement.

Here are a few additional things to keep in mind: • Please familiarize yourself with the Sphinx directives for inline markup./. 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.or row-spanning cells for latex output. • Mathematical expressions can be rendered as png images in html. • Function arguments and keywords should be referred to using the emphasis role.0.Matplotlib. Such tables can not be used when documenting matplotlib. Documenting matplotlib .. For example: 2 :math:‘\sin(x_n^2)‘ yields: sin(xn ).3]) 240 Chapter 27./TODO 27. use the :file: directive. Matplotlib’s documentation makes heavy use of cross-referencing and other semantic markup.. and: . include:: .3 Formatting The Sphinx website contains plenty of documentation concerning ReST markup and working with Sphinx in general.1 .2...2. and in the usual way by latex.. nor the literal role: Please do not describe ‘‘argument‘‘ like this. • Sphinx does not support tables with column. Release 1.1) • Interactive IPython sessions can be illustrated in the documentation using the following directive: . 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. For example. sourcecode:: ipython In [69]: lines = plot([1. when referring to external ﬁles.3]) which would yield: In [69]: lines = plot([1.

. note:: Here is a note yields: Note: here is a note also: Warning: here is a warning • Use the deprecated directive when appropriate: . 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. use something else. followed later by: . which have similar syntax to the deprecated role: .0. for example: .. [#] • Use the note and warning directives. 27.1 • Footnotes 1 can be added using [#]_.98: The transforms have been completely revamped. You can create a references to a term in the glossary with the :term: role. versionadded:: 0.. Formatting 241 . deprecated:: 0. 1 For example..98: This feature is obsolete. yields: Deprecated since version 0..98 This feature is obsolete.. • Use the seealso directive. use something else. sparingly. • Use the versionadded and versionchanged directives.3. Release 1. New in version 0.Matplotlib.98 The transforms have been completely revamped. to draw attention to important comments: . rubric:: Footnotes .

3.2 Static ﬁgures Any ﬁgures that rely on optional system conﬁgurations need to be handled a little diﬀerently. this will be done automatically at build time to ensure that the code that is included runs and produces the advertised ﬁgure. Plots from the examples directory may be referenced through the symlink mpl_examples in the doc directory.py The :scale: directive rescales the image to some percentage of the original size.0.1 Docstrings In addition to the aforementioned formatting suggestions: • Please limit the text width of docstrings to 70 characters. in order to keep the prerequisites to the documentation eﬀort as low as possible. Documenting matplotlib . each will be given a numbered ﬁle name and included.figure()). eg. there are a many cases where a table is used in place of a deﬁnition list for autogenerated sections of docstrings.: . 27. 27. plot:: pyplots/pyplot_simple. Please run the doc/pyplots/make.. :include-source: will present the contents of the ﬁle.1 Dynamically generated ﬁgures Figures can be automatically generated from scripts and included in the docs. The path should be relative to the doc directory. but additional entries in the index need to be explicitly added. Matplotlib includes a Sphinx extension (sphinxext/plot_directive. though we don’t recommend using this in most cases since it is probably better to choose the correct ﬁgure size and dpi in mpl and let it handle the scaling.Matplotlib. a PDF). Several ﬁgures will be saved with the same basename as the ﬁlename when the documentation is generated (low and high res PNGs.1 • The autodoc extension will handle index entries for the API. 27. These ﬁgures are not to be generated during the documentation build. Any plots speciﬁc to the documentation should be added to the doc/pyplots directory and committed to SVN. plot:: mpl_examples/pylab_examples/simple_plot. and commit the script and the images to svn.py script when adding such ﬁgures. Please also add a line to the README in doc/pyplots for any 242 Chapter 27. Note: matplotlib makes extensive use of keyword arguments as pass-through arguments. marked up as source code.4.py) for generating the images from the python script and including either a png copy for html or a pdf for latex: . Release 1.4 Figures 27.. It is not necessary to explicitly save the ﬁgure in the script.4. • Keyword arguments should be described using a deﬁnition list.py :include-source: If the script produces multiple ﬁgures (through multiple calls to pyplot.

eg: 27.6 Internal section references To maximize internal consistency in section labeling and references.. insert the following special comment anywhere in the script: # -*./lib/matplotlib/mpl-data/matplotlibrc One exception to this is when referring to the examples dir. use hypen separated.. Release 1.5.Matplotlib.. To exclude the example from having an image rendered. An image is generated and included for all examples in the api and pylab_examples directories.. plot:: pyplots/tex_unicode_demo.rst: .noplot -*- 27. image:: . Relative paths are extremely confusing in the sphinx plot extensions.4. I use the symlink directory./examples So we can include plots from the examples dir using the symlink: . if I want to refer to a ﬁle in the mpl-data directory. API documents like matplotlib.3 Examples The source of the ﬁles in the examples directory are automatically included in the HTML docs./. Once these steps have been taken. literalinclude:: .py :include-source: 27. Referring to mpl documents 243 . For example. these ﬁgures can be included in the usual way: .g./lib/matplotlib/mpl-data/images/subplots. e.pyplot. This way..plot() can refer to the examples in a known location. In the top level doc directory we have symlinks pointing to the mpl examples: home:~/mpl/doc> ls -l mpl_* mpl_examples -> . from customizing. eg.0. a license ﬁle or an image ﬁle from mpl-data. you may want to include to a document in the matplotlib src./. in users/navigation_toolbar.5 Referring to mpl documents In the documentation.rst..py We used to use a symlink for mpl-data too..png In the users subdirectory. we refer to the image icons with: . so without getting into the dirty details. descriptive labels for section references.. but the distro becomes very large on platforms that do not support links (eg the font ﬁles are duplicated and large) 27. plot:: mpl_examples/pylab_examples/simple_plot. refer to it via a relative path from the document where the rst ﬁle resides. it is easier to simply include a symlink to the ﬁles at the top doc level directory..1 additional requirements necessary to generate a new ﬁgure.

the class matplotlib. If parts == 2. if parts == 1. A single option is available: parts controls how many of parts in the path to the class are shown.. let’s prefer hyphens to separate words. If parts == 0.0.7 Section names.8 Inheritance diagrams Class inheritance diagrams can be generated with the inheritance-diagram directive. If a module name is provided.. Example: .Patch is shown as Patch.patches matplotlib. you provide the directive with a number of class or module names (separated by whitespace). since underscores are widely used by Sphinx itself. so the label: .lines matplotlib. For example. all classes in that module will be used. Release 1. 27.. so let’s avoid top level names in references like user or devel or faq unless necesssary. inheritance-diagram:: matplotlib. Documenting matplotlib . To use it. _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. eg Possible hangups rather than Possible Hangups 27.Matplotlib. All of the ancestors of these classes will be included in the inheritance diagram..Patch.text :parts: 2 244 Chapter 27. because for example the FAQ “what is a backend?” could later become part of the users guide. _faq-backend In addition.patches. _what-is-a-backend is better than: . the full path is shown. please use Upper lower for section titles.1 . it is shown as patches. etc For everything but top level chapters.

W edge patches.rst$" .ArrowStyle patches. and promoting or demoting section headings.Annotation 27.T extWithDash text.Polygon patches.VertexSelector patches.OﬀsetFrom patches. rst-mode) ("\\.rest$" .1 patches.Rectangle patches.PathPatch patches. Emacs helpers 245 .Patch patches.Shadow patches._Style patches.ConnectionStyle patches.FancyArrow patches. rst-mode)) auto-mode-alist)) Some helpful functions: C-c TAB .FancyBboxPatch patches.FancyArrowPatch patches.Line2D patches.Ellipse text.rst-toc-update Update the table of contents at point 27.BoxStyle patches.T ext text.Arrow patches.Matplotlib.el which automates many important ReST tasks like building and updateing table-of-contents.9 Emacs helpers There is an emacs mode rst. Here is the basic .Arc patches.txt$" .RegularPolygon lines.Circle patches.9.emacs conﬁguration: (require ’rst) (setq auto-mode-alist (append ’(("\\.Artist lines._AnnotationBase text. Release 1.YAArrow text.ConnectionPatch artist.0.rst-toc-insert Insert table of contents at point C-c C-u .CirclePolygon patches. rst-mode) ("\\.

Release 1.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.0.Matplotlib. Documenting matplotlib .

py and bump the version number When doing a release 28.1 Testing • Make sure examples/tests/backend_driver. • remove font cache and tex cache from . On the bracnh. Michael Droettboom should probably handle this step. PS and SVG backends • Run unit/memleak_hawaii3. you need to create a release branch and conﬁgure svn-merge to use it.py and make sure all the unit tests are passing • try some GUI examples.matplotlib and test with and without cache on some example script 28. eg simple_plot.CHAPTER TWENTYEIGHT DOING A MATPLOLIB RELEASE A guide for developers who are doing a matplotlib release • Edit __init__. etc.py runs without errors and check the output of the PNG. do any additional testing you want to do.py with GTKAgg.in us up to date and remove MANIFEST so it will be rebuilt by MANIFEST.3 Packaging • Make sure the MANIFEST. but if he is not available see instructions at Setting up svnmerge.2 Branching Once all the tests are passing and you are ready to do a release. 28.. and then build binaries and source distributions for testing as release candidates.py and make sure there are no memory leaks • Run unit/nose_tests. TkAgg. PDF.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 ..

tgz jdh2358.Matplotlib.gz Uploading matplotlib-0.98.1 • Use setup.matplotlib@shell.html 28.98. the default backend should be TkAgg.DLL-and-%09mingw-td23971661.98. • We have a Makeﬁle for the win32 mingw builds in the mpl source dir release/win32 which you can use this to prepare the windows releases.4 Release candidate testing: Post the release candidates to http://matplotlib.gz to /incoming/j/jd/jdh2358/uploads/matplotlib-0. you also need to make sure that you delete the build dir after any changes to ﬁle:setup.tar. Doing a matplolib release .net Connecting to frs. and upload them to the sourceforge release area.. For windows and OSX.cfg before rebuilding since cruft in the build dir can get carried along.. 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.tar.gz • go https://sourceforge.2.98.sf.6 as described at http://www.sourceforge.0. unix2dos the rc ﬁle • We have a Makeﬁle for the OS X builds in the mpl source dir release/osx.net/project/admin/explorer. To post to the server.php?group_id=80706 and do a ﬁle release.2. binaries and eggs.tar.tar. see Using svnmerge.sf. you can do: > scp somefile. Pester us if we don’t respond • ftp the source and binaries to the anonymous FTP site: mpl> svn-clean mpl> python setup.2.5 Uploading • Post the win32 and OS-X binaries for testing and make a request on matplotlib-devel for testing.2. Any changes to ﬁx bugs in the release candidate should be ﬁxed in the release branch and merged into the trunk with svn-merge.gz sftp> put matplotlib-0. When the release candidate is signed oﬀ on.net.sourceforge. Importantly.6–libpngsegfault%2C-MSVCR90.com/binary-installers-for-python2. • on windows.cfg to set the default backends. Release 1.nabble.net:/home/groups/m/ma/matplotlib/htdocs/release-candidate replacing ‘jdh2358’ with your sourceforge login. so use this to prepare the OS X releases.py sdist mpl> cd dist/ dist> sftp jdh2358@frs.net/release-candidates and post a message to matplotlibusers and devel requesting testing. You should also turn on or oﬀ any platform speciﬁc build options you need. but this is currently broken for python2. build the ﬁnal sdist. 28. sftp> cd uploads sftp> ls sftp> lls matplotlib-0. Click on the “Admin” tab to log in as an admin. and then the “File Releases” tab.

You will then be taken to a fairly self explanatory page where you can enter the Change notes.6. Announcing 249 .6 Announcing Announce the release on matplotlib-announce. You will then be prompted for the “New release name” at which point you can add the version number. and select which packages from the incoming ftp archive you want to include in this release.Matplotlib.1 and click “Create this release”. and when you are done you click on the “notify users who are monitoring this package link” 28. eg somepackage-0.0. the release notes. 28.1 box. For each binary. matplotlib-users and matplotlib-devel. you will need to select the platform and ﬁle type. Release 1. Include a summary of highlights from the CHANGELOG and/or post the whole CHANGELOG since the last release.

0. Doing a matplolib release . Release 1.1 250 Chapter 28.Matplotlib.

it is recomputed to reﬂect those changes. The next time an invalidated transform is accessed. and contributes to better interactive performance. their parents are automatically invalidated.transforms matplotlib includes a framework for arbitrary geometric transformations that is used determine the ﬁnal position of all elements drawn on the canvas.CHAPTER TWENTYNINE WORKING WITH TRANSFORMATIONS Aﬃne2D BlendedAﬃne2D T ransformedBbox CompositeAﬃne2D BboxBase Bbox BboxT ransformT o Path AﬃneBase Aﬃne2DBase 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. here is a graph of the transform tree used to plot data to the graph: 251 .1 matplotlib. This invalidation/caching approach prevents unnecessary recomputations of transforms. Transforms are composed into trees of TransformNode objects whose actual value depends on their children. When the contents of children change. For example.

Matplotlib.1 The framework can be used for both aﬃne and non-aﬃne transformations. However. For any transform: full transform == non-affine part + affine part The backends are not expected to handle non-aﬃne transformations themselves. it is possible to perform just the aﬃne or non-aﬃne part of a transformation on a set of data.0. The aﬃne is always assumed to occur after the non-aﬃne. Working with transformations . 252 Chapter 29. we want use the backend renderers to perform aﬃne transformations whenever possible. Release 1. for speed. Therefore.

bounds (property) Returns (x0. invalidate() Invalidate this TransformNode and all of its ancestors. c: may be either: •a sequence (cx.0. Release 1.‘C’ for centered . such as bounding boxes. frozen() Returns a frozen copy of this transform node.Matplotlib.transforms. class matplotlib. container=None) Return a copy of the Bbox. The canonical representation is as two points.BboxBase Bases: matplotlib. right and top edges and width and height. it defaults to the initial Bbox. y0. Should be called from the constructor of any transforms that depend on other transforms. height). containsx(x) Returns True if x is between or equal to x0 and x1. This includes classes that are not really transforms. Creates a new TransformNode. width. since some transforms depend on bounding boxes to compute their values. set_children(*children) Set the children of the transform. anchored(c. but these are not stored explicity. Convenience properties are provided to get the left. 29. where 0 is left or bottom and 1 is right or top •a string: . shifted to position c within a container. Creates a new TransformNode. matplotlib.TransformNode This is the base class of all bounding boxes. with no restrictions on their ordering.1. Optional argument container is the box within which the Bbox is positioned. Useful for storing a previously known state of a transform where copy. A mutable bounding box is provided by the Bbox class.transforms. y) is a coordinate inside the bounding box or on its edge. The frozen copy will not update when its children change.transforms.deepcopy() might normally be used. Should be called any time the transform changes. bottom. cy) where cx and cy range from 0 to 1. contains(x.‘SE’ for bottom-left . and provides read-only access to its data.‘E’ for left . to let the invalidation system know which transforms can invalidate this transform.1 class matplotlib.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.‘S’ for bottom-center .etc.transforms 253 . y) Returns True if (x.

bboxes is a sequence of BboxBase objects expanded(sw. b). corners() Return an array of points which are the four corners of this rectangle. since some transforms depend on bounding boxes to compute their values. intervaly (property) intervaly is the pair of y coordinates that deﬁne the bounding box. y) is a coordinate inside the bounding box. extents (property) Returns (x0. corners() returns (a. It is not guaranteed to be sorted from bottom to top. For example. y) Returns True if (x. vertices is a Nx2 Numpy array. such as bounding boxes. y0. fully_contains(x. x1. (c. It may be negative if y1 < y0. sh) Return a new Bbox which is this Bbox expanded around its center by the given factors sw and sh. intervalx (property) intervalx is the pair of x coordinates that deﬁne the bounding box. but not on its edge alone. if this Bbox is deﬁned by the points (a. It is not guaranteed to be sorted from left to right. fully_containsy(y) Returns True if y is between but not equal to y0 and y1. fully_overlaps(other) Returns True if this bounding box overlaps with the given bounding box other. y1). but not on its edge. inverse_transformed(transform) Return a new Bbox object. 254 Chapter 29.Matplotlib. b) and (c. statically transformed by the inverse of the given transform. count_contains(vertices) Count the number of vertices contained in the Bbox. This includes classes that are not really transforms.1 containsy(y) Returns True if y is between or equal to y0 and y1. (a. frozen() TransformNode is the base class for anything that participates in the transform tree and needs to invalidate its parents or be invalidated. d). fully_containsx(x) Returns True if x is between but not equal to x0 and x1. count_overlaps(bboxes) Count the number of bounding boxes that overlap this one.0. Release 1. Working with transformations . b) and (c. d). height (property) The height of the bounding box. d).

. splitx(*args) e. rotated(radians) Return a new bounding box that bounds a rotated version of this bounding box by the given radians.splitx(f1.. y) coordinates that deﬁne the bounding box. matplotlib. . box_aspect.Matplotlib. shrunk by the factor mx in the x direction and the factor my in the y direction. Normally mx and my will be less than 1. f2.0) Return a copy of the Bbox. The new bounding box is still aligned with the axes. f2. It is not guaranteed to be the top-right corner.0...) Returns a list of new Bbox objects formed by splitting the original one with horizontal lines at fractional positions f1. . not the relative dimensions.. Release 1. fractions of a larger box such as a ﬁgure—then the physical aspect ratio of that ﬁgure is speciﬁed with ﬁg_aspect. shrunk so that it is as large as it can be while having the desired aspect ratio..g.1. f2. my) Return a copy of the Bbox.. For that.. bbox. . 1). p0 (property) p0 is the ﬁrst pair of (x.transforms 255 . max (property) max is the top-right corner of the bounding box. bbox. use min. shrunk_to_aspect(box_aspect. y) coordinates that deﬁne the bounding box. so that box_aspect can also be given as a ratio of the absolute dimensions. 29.1 is_unit() Returns True if the Bbox is the unit bounding box from (0. container=None. size (property) The width and height of the bounding box. p1 (property) p1 is the second pair of (x. min (property) min is the bottom-left corner of the bounding box. padded(p) Return a new Bbox that is padded on all four sides by the given value. in the same way as width and height.splitx(f1. May be negative. use max. 0) to (1.. .) Returns a list of new Bbox objects formed by splitting the original one with vertical lines at fractional positions f1. shrunk(mx. ﬁg_aspect=1.g. of course. It is not guaranteed to be the bottom-left corner. The lower left corner of the box remains unchanged. splity(*args) e. If the box coordinates are relative—that is. f2. For that.. overlaps(other) Returns True if this bounding box overlaps with the given bounding box other. but this is not enforced.

y1]] If you need to create a Bbox object from another form of data. xmax (property) xmax is the right edge of the bounding box.transforms. width and height. y1 is not guaranteed to be greater than y0. bottom.transforms. consider the static methods unit(). static union(bboxes) Return a Bbox that contains all of the given bboxes. use xmax. use xmin. x1 (property) x1 is the second of the pair of x coordinates that deﬁne the bounding box. translated(tx. y0]. ty) Return a copy of the Bbox. If you require that. y0 is not guaranteed to be less than y1. Working with transformations . class matplotlib. [x1. points: a 2x2 numpy array of the form [[x0. static from_extents(*args) (staticmethod) Create a new Bbox from left.BboxBase A mutable bounding box.0. x0 (property) x0 is the ﬁrst of the pair of x coordinates that deﬁne the bounding box. ymin (property) ymin is the bottom edge of the bounding box. If you require that. y1 (property) y1 is the second of the pair of y coordinates that deﬁne the bounding box. use ymax. statically translated by tx and ty. x0 is not guaranteed to be less than x1. If you require that. width and height may be negative.Matplotlib.1 transformed(transform) Return a new Bbox object. use ymin. height) (staticmethod) Create a new Bbox from x0. xmin (property) xmin is the left edge of the bounding box. width. It may be negative if x1 < x0. 256 Chapter 29. ymax (property) ymax is the top edge of the bounding box. Release 1. y0. y0 (property) y0 is the ﬁrst of the pair of y coordinates that deﬁne the bounding box. y0. static from_bounds(x0. statically transformed by the given transform. x1 is not guaranteed to be greater than x0. right and top. width (property) The width of the bounding box.Bbox(points) Bases: matplotlib. If you require that. from_bounds() and from_extents().

y. matplotlib. set_points(points) Set the points of the bounding box directly from a numpy array of the form: [[x0. [x1. x0 and y0 will be the minimal values. 0) to (1. use the last value passed to ignore(). update_from_data(x. After updating. After updating.Matplotlib. subsequent calls to update_from_data() will include the existing bounds of the Bbox. ignore the existing bounds of the Bbox. ignore=None) Update the bounds of the Bbox based on the passed in data. updatey=True) Update the bounds of the Bbox based on the passed in data.0.1 The y-axis increases upwards. 1). update_from_data_xy(xy. 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. No error checking is performed. [x1. get_points() Get the points of the bounding box directly as a numpy array of the form: [[x0. y1]]. y0]. updatex=True. x0 and y0 will be the minimal values.transforms 257 . y0]. 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. • when False. y1]]. the bounds will have positive width and height.1. ignore=None. value: •When True. • when None. x: a numpy array of x-values y: a numpy array of y-values ignore: • when True. Release 1. static unit() (staticmethod) Create a new unit Bbox from (0. the bounds will have positive width and height. subsequent calls to update_from_data() will ignore the existing bounds of the Bbox. as this method is mainly for internal use. include the existing bounds of the Bbox. •When False.

updatex: when True. y0].0. updatey=True) Update the bounds of the Bbox based on the passed in data. 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. ignore=None. ignore the existing bounds of the Bbox. Release 1. use the last value passed to ignore(). class matplotlib. update the x values updatey: when True. use the last value passed to ignore(). updatex: when True. • when None. include the existing bounds of the Bbox.1 ignore: • when True. All non-aﬃne transformations should be subclasses of this class.transforms. • when False. updatex=True. the bounds will have positive width and height.transforms. include the existing bounds of the Bbox.transforms. update the y values update_from_path(path.TransformNode The base class of all TransformNode instances that actually perform a transformation. [x1. y1]].TransformedBbox(bbox. Subclasses of this class should override the following members (at minimum): •input_dims •output_dims •transform() •is_separable 258 Chapter 29. the bounds of this bbox will update accordingly. update the y values class matplotlib.Transform Bases: matplotlib. When either the child bounding box or transform changes. • when None. update the x values updatey: when True. New aﬃne transformations should be subclasses of Affine2D. Working with transformations . transform) Bases: matplotlib.BboxBase A Bbox that is automatically transformed by a given transform. x0 and y0 will be the minimal values.Matplotlib. path: a Path instance ignore: • when True. After updating. ignore the existing bounds of the Bbox. • when False.transforms.

radians=False. The return value of this method should be treated as temporary.Path objects. pts. In aﬃne transformations.. x === self.transforms 259 . Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). The pts must be a two-column numpy array of x. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). transform_angles(angles.0000000000000001e-05) Performs transformation on a set of angles anchored at speciﬁc locations.inverted(). get_affine() Get the aﬃne part of this transform. numpy array).0. it should override: •transform_path() Creates a new TransformNode. An update to self does not cause a corresponding update to its inverted copy. The generic version of this method uses a very generic algorithm that transforms pts.e. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). 29. The angles must be a column vector (i. the default).1.1 •has_inverse •inverted() (if has_inverse() can return True) If the transform needs to do something non-standard with mathplotlib.path. Release 1. such as adding curves where there were once line segments. inverted() Return the corresponding inverse transformation.y positions (angle transforms currently only work in 2D). In non-aﬃne transformations. radians indicates whether or not input angles are given in radians (True) or degrees (False.transform(x)) transform(values) Performs the transformation on the given array of values. matplotlib. to ﬁnd the angle in the transformed system. The transformed angles are returned in an array with the same size as angles. this is generally a no-op.transform(self. as well as locations very close to pts. pushoﬀ is the distance to move away from pts for determining transformed angles (see discussion of method below). This array must have the same number of rows as angles. this is equivalent to transform(values).Matplotlib. pushoﬀ=1. transform_affine(values) Performs only the aﬃne part of this transformation on the given array of values.

path: a Path instance. Working with transformations . transformed only by the non-aﬃne part of this transform. frozen() Returns a frozen copy of this transform node. so the child transform may only be replaced with another child transform of the same dimensions. In non-aﬃne transformations. The frozen copy will not update when its children change. The point is given as a sequence of length input_dims. The transformed point is returned as a sequence of length output_dims. path: a Path instance. this is generally equivalent to transform(values). Release 1. transform_path(path) Returns a transformed copy of path. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).Matplotlib.0. this is always a no-op.TransformWrapper(child) Bases: matplotlib.transforms.1 transform_non_affine(values) Performs only the non-aﬃne part of the transformation. 260 Chapter 29. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). Note that TransformWrapper instances must have the same input and output dimensions during their entire lifetime. transform_path_affine(path) Returns a copy of path. class matplotlib. This child may later be replaced with set().transforms. This class allows that replacement to correctly trigger invalidation. In some cases. this transform may insert curves into the path that began as line segments. path: a Path instance. This is useful if a node of the transform tree must be replaced at run time with a transform of a diﬀerent type.deepcopy() might normally be used. transformed only by the aﬃne part of this transform. In aﬃne transformations. Useful for storing a previously known state of a transform where copy. 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. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path. child: A class:Transform instance.Transform A helper class that holds a single child transform and acts equivalently to it.

For a mutable 2D aﬃne transformation. class matplotlib.transforms.Transform The base class of all aﬃne transformations of any number of dimensions. path: a Path instance. 2D aﬃne transformations are performed using a 3x3 numpy array: a c e b d f 0 0 1 This class provides the read-only interface.Matplotlib.AffineBase The base class of all 2D aﬃne transformations.transforms. The frozen copy will not update when its children 29. transform_path_affine(path) Returns a copy of path.AffineBase Bases: matplotlib. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).transforms.Affine2DBase Bases: matplotlib. use Affine2D. path: a Path instance. get_matrix() Get the underlying transformation matrix as a numpy array. this is generally equivalent to transform(values).transforms 261 . frozen() Returns a frozen copy of this transform node. transform_non_affine(points) Performs only the non-aﬃne part of the transformation. transformed only by the non-aﬃne 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). In aﬃne transformations.1. get_affine() Get the aﬃne part of this transform. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values class matplotlib. matplotlib.1 set(child) Replace the current child of this transform with another one. Release 1. The new child must have the same number of input and output dimensions as the current child. In non-aﬃne transformations. this is always a no-op.0. Subclasses of this class will generally only need to override a constructor and get_matrix() that generates a custom 3x3 matrix.transforms. transformed only by the aﬃne part of this transform.

transform_affine(points) Performs only the aﬃne part of this transformation on the given array of values. this is equivalent to transform(values). this is generally a no-op. this is equivalent to transform(values). Release 1.Matplotlib. An update to self does not cause a corresponding update to its inverted copy.Affine2D(matrix=None) Bases: matplotlib. c. 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. In non-aﬃne transformations.0. The transformed point is returned as a sequence of length output_dims. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).c. Initialize an Aﬃne transform from a 3x3 numpy ﬂoat array: 262 Chapter 29.e. inverted() Return the corresponding inverse transformation.1 change. e. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). Useful for storing a previously known state of a transform where copy. In aﬃne transformations. x === self. b.inverted().f) transform(points) Performs only the aﬃne part of this transformation on the given array of values.transform(self.deepcopy() might normally be used. The point is given as a sequence of length input_dims.transforms. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). this is generally a no-op. d. Working with transformations . class matplotlib.transforms. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).d. In aﬃne transformations. The return value of this method should be treated as temporary. In non-aﬃne transformations.transform(x)) static matrix_from_values(a.b. transform_point(point) A convenience function that returns the transformed copy of a single point.Affine2DBase A mutable 2D aﬃne transformation.

so this method can easily be chained with more calls to rotate(). rotate_around(x. y.Matplotlib. so this method can easily be chained with more calls to rotate(). the same scale is applied in both the x. matplotlib.and y-directions. Returns self.transforms 263 . translate() and scale(). Unless this transform will be mutated later on. y) in place. b. rotate_deg_around(x. degrees) Add a rotation (in degrees) around the point (x. Returns self. If sy is None. c. static from_values(a. consider using the faster IdentityTransform class instead. rotate(theta) Add a rotation (in radians) to this transform in place. Returns self. rotate_deg(). scale(sx. rotate_deg(). rotate_deg(). y. clear() Reset the underlying matrix to the identity transform. initialize with the identity transform. rotate_deg(degrees) Add a rotation (in degrees) to this transform in place. translate() and scale().1 a c e b d f 0 0 1 If matrix is None. sy=None) Adds a scale in place. translate() and scale(). translate() and scale(). so this method can easily be chained with more calls to rotate(). y) in place. Release 1.1. f ) (staticmethod) Create a new Aﬃne2D 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. so this method can easily be chained with more calls to rotate(). Returns self. rotate_deg(). theta) Add a rotation (in radians) around the point (x. 29. d. e.0.

Release 1. Returns self.transforms. get_affine() Return the corresponding inverse transformation. translate() and scale(). translate() and scale(). rotate_deg().Matplotlib.inverted(). x === self.transform(x)) get_matrix() Get the underlying transformation matrix as a numpy array. In non-aﬃne transformations. class matplotlib. so this method can easily be chained with more calls to rotate().IdentityTransform Bases: matplotlib. In aﬃne transformations. Working with transformations . transform(values) is always equivalent to transform_affine(transform_non_affine(values)). An update to self does not cause a corresponding update to its inverted copy.deepcopy() might normally be used.transform(x)) transform(points) Performs only the non-aﬃne part of the transformation. The frozen copy will not update when its children change. 264 Chapter 29. this is generally equivalent to transform(values). set_matrix(mtx) Set the underlying transformation matrix from a 3x3 numpy array: a c e b d f 0 0 1 translate(tx.inverted().Affine2DBase A special class that does on thing. frozen() Returns a frozen copy of this transform node.transform(self. An update to self does not cause a corresponding update to its inverted copy. rotate_deg(). Useful for storing a previously known state of a transform where copy.transforms. inverted() Return the corresponding inverse transformation. so this method can easily be chained with more calls to rotate().0. The return value of this method should be treated as temporary. ty) Adds a translation in place. the identity transform.1 Returns self. in a fast way. The return value of this method should be treated as temporary. x === self. this is always a no-op.transform(self. set(other) Set this transformation from the frozen copy of another Affine2DBase object.

this is generally equivalent to transform(values). transformed only by the non-aﬃne part of this transform.BlendedGenericTransform(x_transform. y_transform) Bases: matplotlib. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path. 29. transform_non_affine(points) Performs only the non-aﬃne part of the transformation. this is always a no-op. this is generally equivalent to transform(values). Create a new “blended” transform using x_transform to transform the x-axis and y_transform to transform the y-axis. This “generic” version can handle any given child transform in the x. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).1. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values class matplotlib. transform_path(path) Returns a copy of path. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). Release 1. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). You will generally not call this constructor directly but use the blended_transform_factory() function instead.transforms.Matplotlib. transform(values) is always equivalent to transform_affine(transform_non_affine(values)).0. In aﬃne transformations. matplotlib. transformed only by the non-aﬃne part of this transform. path: a Path instance.transforms. this is always a no-op. which can determine automatically which kind of blended transform to create. In non-aﬃne transformations. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_affine(path) Returns a copy of path. path: a Path instance. path: a Path instance. In non-aﬃne transformations.1 Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).and y-directions. In aﬃne transformations. transformed only by the non-aﬃne part of this transform.transforms 265 . and another transform for the ydirection. transform_affine(points) Performs only the non-aﬃne part of the transformation.Transform A “blended” transform uses one transform for the x-direction.

and another transform for the ydirection. Working with transformations . this is equivalent to transform(values). Both x_transform and y_transform must be 2D aﬃne transforms.Matplotlib.1 frozen() Returns a frozen copy of this transform node. class matplotlib.deepcopy() might normally be used. Create a new “blended” transform using x_transform to transform the x-axis and y_transform to transform the y-axis. Release 1. this is generally equivalent to transform(values). In aﬃne transformations. transform_affine(points) Performs only the aﬃne part of this transformation on the given array of values. This version is an optimization for the case where both child transforms are of type Affine2DBase. x === self.transform(x)) transform(points) Performs the transformation on the given array of values. y_transform) Bases: matplotlib.BlendedAffine2D(x_transform. this is always a no-op. In non-aﬃne transformations.transforms.inverted(). get_affine() Get the aﬃne part of this transform. In non-aﬃne transformations. The return value of this method should be treated as temporary. Useful for storing a previously known state of a transform where copy.transform(self.transforms. 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)). Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). inverted() Return the corresponding inverse transformation. The frozen copy will not update when its children change. In aﬃne transformations.Affine2DBase A “blended” transform uses one transform for the x-direction. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). transform_non_affine(points) Performs only the non-aﬃne part of the transformation.0. 266 Chapter 29. this is generally a no-op. 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).

inverted(). which can determine automatically which kind of blended transform to create.0. inverted() Return the corresponding inverse transformation.transforms 267 . transform(values) is always equivalent to transform_affine(transform_non_affine(values)).CompositeGenericTransform(a. y_transform) Create a new “blended” transform using x_transform to transform the x-axis and y_transform to transform the y-axis.deepcopy() might normally be used. class matplotlib. matplotlib. The return value of this method should be treated as temporary. You will generally not call this constructor directly but use the composite_transform_factory() function instead. A faster version of the blended transform is returned for the case where both child transforms are aﬃne. This “generic” version can handle any two arbitrary transformations.transform(self.transform(x)) transform(points) Performs the transformation on the given array of values. An update to self does not cause a corresponding update to its inverted copy. transform_affine(points) Performs only the aﬃne part of this transformation on the given array of values.blended_transform_factory(x_transform.transforms.1. get_matrix() Get the underlying transformation matrix as a numpy array. Release 1. which can automatically choose the best kind of composite transform instance to create. matplotlib. frozen() Returns a frozen copy of this transform node. Create a new composite transform that is the result of applying transform a then transform b. In non-aﬃne transformations. get_affine() Get the aﬃne part of this transform. The frozen copy will not update when its children change.1 You will generally not call this constructor directly but use the blended_transform_factory() function instead.Matplotlib. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). x === self. b) Bases: matplotlib. In aﬃne transformations. this is equivalent to transform(values).Transform A composite transform formed by applying transform a then transform b.transforms.transforms. 29. Useful for storing a previously known state of a transform where copy. this is generally a no-op.

which can automatically choose the best kind of composite transform instance to create.transforms. this is generally equivalent to transform(values). Shortcut versions of the blended transform are provided for the case where both child transforms are aﬃne. this is always a no-op. In some cases.transforms. transform_path(path) Returns a transformed copy of path. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values class matplotlib. Release 1. transformed only by the non-aﬃne part of this transform. transform_path_affine(path) Returns a copy of path. Working with transformations . transform_non_affine(points) Performs only the non-aﬃne part of the transformation.transforms. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). path: a Path instance. This version is an optimization that handles the case where both a and b are 2D aﬃnes.Affine2DBase A composite transform formed by applying transform a then transform b. Both a and b must be instances of Affine2DBase. this transform may insert curves into the path that began as line segments. Create a new composite transform that is the result of applying transform a then transform b. matplotlib. 268 Chapter 29.CompositeAffine2D(a.0. path: a Path instance. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). transformed only by the aﬃne part of this transform. get_matrix() Get the underlying transformation matrix as a numpy array. or one or the other is the identity transform. In aﬃne transformations. b) Create a new composite transform that is the result of applying transform a then transform b. In non-aﬃne transformations.Matplotlib. path: a Path instance.1 Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). b) Bases: matplotlib.composite_transform_factory(a. You will generally not call this constructor directly but use the composite_transform_factory() function instead. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values transform_path_non_affine(path) Returns a copy of path.

get_transformed_path_and_affine() Return a copy of the child path. This cached copy is automatically updated when the non-aﬃne part of the transform changes. after xt and yt have been transformad by the given transform scale_trans.transforms. Release 1. Create a new BboxTransformTo that linearly transforms points from the unit bounding box to boxout. Create a new BboxTransform that linearly transforms points from boxin to boxout.Affine2DBase BboxTransformFrom linearly transforms points from a given Bbox to the unit bounding box.TransformedPath(path.transforms. boxout) Bases: matplotlib. class matplotlib. class matplotlib.transforms.TransformNode A TransformedPath caches a non-aﬃne transformed copy of the Path. yt. transform) Bases: matplotlib. with the non-aﬃne part of the transform already applied. get_matrix() Get the underlying transformation matrix as a numpy array.transforms.: c = a + b class matplotlib.1 Composite transforms may also be created using the ‘+’ operator. 29.transforms.BboxTransformFrom(boxin) Bases: matplotlib. get_matrix() Get the underlying transformation matrix as a numpy array.0. along with the aﬃne part of the path necessary to complete the transformation.transforms.BboxTransform(boxin.transforms. class matplotlib.transforms. get_matrix() Get the underlying transformation matrix as a numpy array. e.1.transforms 269 .Matplotlib.Affine2DBase BboxTransform linearly transforms points from one Bbox to another Bbox.transforms. scale_trans) Bases: matplotlib.ScaledTranslation(xt. Create a new TransformedPath from the given Path and Transform.g.Affine2DBase BboxTransformTo is a transformation that linearly transforms points from the unit bounding box to a given Bbox.BboxTransformTo(boxout) Bases: matplotlib. get_fully_transformed_path() Return a fully-transformed copy of the child path. class matplotlib. matplotlib.Affine2DBase A transformation that translates by xt and yt. get_matrix() Get the underlying transformation matrix as a numpy array.transforms.

with the non-aﬃne part of the transform already applied.001.transforms. expander=0.Matplotlib. along with the aﬃne part of the path necessary to complete the transformation. vmax. Working with transformations .0000000000000001e-15. If either is inf or -inf or nan. 270 Chapter 29. return . Release 1. Unlike get_transformed_path_and_affine(). they will be swapped. each will be moved by the ‘expander’. expander.expander. increasing=True) Ensure the endpoints of a range are ﬁnite and not too close together. “too close” means the interval is smaller than ‘tiny’ times the maximum absolute value. no interpolation will be performed. If ‘increasing’ is True and vmin > vmax.1 get_transformed_points_and_affine() Return a copy of the child path.nonsingular(vmin. regardless of whether they are too close. matplotlib. If they are too close.0. tiny=1.

and non-separable transformations. • A function to limit the range of the axis to acceptable values (limit_range_for_scale()).ScaleBase. are called “scales”. Unlike limit_range_for_scale().scale.1 Creating a new scale Adding a new scale consists of deﬁning a subclass of matplotlib. for example. 271 . • Locators (major and minor) that determine where to place ticks in the plot. which is always enforced.g. e. y. The necessary code for scales and projections can be included anywhere: directly within a plot script. This is used. Projections can be chosen using the projection keyword argument to the plot() or subplot() functions. to convert mouse positions from screen space back into data space. the range setting here is only used when automatically setting the range of the plot. would prevent the range from including values less than or equal to zero. or in the matplotlib source tree itself. • An inverse of that transformation. 30. in third-party code. Separable transformations.: plot(x. that includes the following elements: • A transformation from data coordinates into display coordinates. and optionally. for instance. the scale of a plot can be set with set_xscale() and set_xscale(). that handle data in two or more dimensions at a time.CHAPTER THIRTY ADDING NEW SCALES AND PROJECTIONS TO MATPLOTLIB Matplotlib supports the addition of custom procedures that transform the data before it is displayed. From the user’s perspective. working on a single dimension. how to adjust the limits of the plot to some “good” values. A log scale. projection="custom") This document is intended for developers and advanced users who need to create new scales and projections for matplotlib. are called “projections”. • Formatters (major and minor) that specify how the tick labels should be drawn. There is an important distinction between two kinds of transformations.

set_default_locators_and_formatters(axis) Set the locators and formatters to reasonable defaults for linear scaling. • An inverse of that transformation. and matplotlib has a facility to help with doing so. The polar plot functionality in matplotlib. to convert mouse positions from screen space back into data space. • Any additional methods for additional convenience or features.py.polar may also be of interest. Release 1. • Deﬁning custom locators and formatters for the projection. • Setting up default values (overriding cla()). an elliptical axes. This is used. but there is an example of this for polar plots in matplotlib. For example.scale. 30.3 API documentation 30. for example.scale class matplotlib. Once the class is deﬁned. it may be more convenient to display the grid in degrees. A full-ﬂedged and heavily annotated example is in examples/api/custom_scale_example. it must be registered with matplotlib so that the user can select it. Adding new scales and projections to matplotlib . since the defaults for a rectilinear axes may not be appropriate. that includes the following elements: • A transformation from data coordinates into display coordinates. There are also some classes in matplotlib.LinearScale(axis.axes.scale that may be used as starting points. 272 Chapter 30.py.Matplotlib. A full-ﬂedged and heavily annotated example is in examples/api/custom_projection_example.ScaleBase The default linear scale. that will be used to draw the background of the plot and for clipping any data elements. in a geographic projection. • Set up interactive panning and zooming. get_transform() The transform for linear scaling is just the IdentityTransform. ticks and ticklabels. it must be registered with matplotlib so that the user can select it. for example.polar. • Deﬁning the shape of the axes.projections.2 Creating a new projection Adding a new projection consists of deﬁning a subclass of matplotlib.projections. 30.3. even if the data is in radians.1 matplotlib. Custom projections will often need to place these elements in special locations.Axes.scale. **kwargs) Bases: matplotlib. • Transformations for the gridlines.0.1 Once the class is deﬁned. This is left as an “advanced” feature left to the reader.

working on a single dimension. **kwargs) Bases: matplotlib.ScaleBase A standard logarithmic scale.ScaleBase Bases: object The base class for all scales. Release 1.scale. 5. Should be a sequence of integers.Matplotlib. this scale provides diﬀerent 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.3. 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. 9] will place 10 logarithmically spaced minor ticks between each major tick. Care is taken so non-positive values are not plotted.1 class matplotlib. Scales are separable transformations. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick. For example. API documentation 273 . minpos) Limit the domain to positive values.scale. vmax. class matplotlib. get_transform() Return a Transform instance appropriate for the given logarithm base.scale. limit_range_for_scale(vmin. 1. 3. For computational eﬃciency (to push as much as possible to Numpy C code in the common cases). 2. 30.0. in a log10 scale: [0. 8. 4. 7. 6. set_default_locators_and_formatters(axis) Set the locators and formatters to specialized versions for log scaling.LogScale(axis.

4. This is used by log scales to determine a minimum value. 5. For example. matplotlib.scale. 1.scale.ScaleBase The symmetrical logarithmic scale is logarithmic in both the positive and negative directions from the origin. there is a need to have a range around zero that is linear. Should be a sequence of integers.projections. ACCEPTS: [ linear | log | symlog ] 30. 6. minpos) Returns the range vmin. set_default_locators_and_formatters(axis) Set the Locator and Formatter objects on the given axis to match this scale. **kwargs) Bases: matplotlib. minpos should be the minimum positive value in the data. Since the values close to zero tend toward inﬁnity.1 limit_range_for_scale(vmin.3.register_scale(scale_class) Register a new kind of scale. Release 1. scale_class must be a subclass of ScaleBase. linthresh). 9] will place 10 logarithmically spaced minor ticks between each major tick. 7. set_default_locators_and_formatters(axis) Set the locators and formatters to specialized versions for symmetrical log scaling. get_transform() Return a SymmetricalLogTransform instance.scale. get_projection_class(name) Get a projection class from its name.Matplotlib.2 matplotlib. matplotlib.scale. 274 Chapter 30. 3. x) within which the plot is linear (to avoid having the plot go to inﬁnity around zero).0.SymmetricalLogScale(axis. The parameter linthresh allows the user to specify the size of this range (-linthresh. in a log10 scale: [0. matplotlib. axis. 8.get_scale_docs() Helper function for generating docstrings related to scales. **kwargs) Return a scale class by name. basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. possibly limited to the domain supported by this scale.ProjectionRegistry Bases: object Manages the set of projections available to the system. 2. Adding new scales and projections to matplotlib .scale_factory(scale. vmax.scale.projections class matplotlib. vmax. class matplotlib. subsx/subsy: Where to place the subticks between each major tick.

transform(x)) transform(xy) Performs the transformation on the given array of values.projections.projections.3.projection_factory(projection.inverted().get_projection_names() Get a list of acceptable projection names. limits) Bases: matplotlib.Transform The inverse of the polar transform.projections. class InvertedPolarTransform(axis=None) Bases: matplotlib.transforms.polar.projections. rect. ﬁgure is a ﬁgure to add the axes to. a standard rectilinear projection is returned. mapping Cartesian coordinate space x and y back to theta and r. Release 1.Axes A polar graph projection.polar class matplotlib. r. matplotlib. inverted() Return the corresponding inverse transformation.transform(self. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).PolarAxes(*args.PolarAffine(scale_transform. matplotlib. API documentation 275 .0. matplotlib. where the input dimensions are theta. An update to self does not cause a corresponding update to its inverted copy. ﬁgure.axes. class PolarAxes. projection is a projection name.Matplotlib. The return value of this method should be treated as temporary. rect is a Bbox object specifying the location of the axes within the ﬁgure.projections.Affine2DBase 30. x === self.transforms.get_projection_class(projection=None) Get a projection class from its name. register(*projections) Register a new set of projection(s).1 get_projection_names() Get a list of the names of all projections currently registered. **kwargs) Get a new projection instance. If projection is None. **kwargs) Bases: matplotlib. Any other kwargs are passed along to the speciﬁc projection constructor being used. matplotlib. Theta starts pointing east and goes anti-clockwise.

This handles projection theta and r into Cartesian coordinate space x and y. inverted() Return the corresponding inverse transformation. In non-aﬃne transformations. transform_path(path) Returns a copy of path.0.PolarTransform(axis=None) Bases: matplotlib. transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(va transform_path_non_affine(path) Returns a copy of path. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims).Transform The base polar transform.transform(self.inverted(). Scales the output so that maximum radius rests on the edge of the axes circle. get_matrix() Get the underlying transformation matrix as a numpy array. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). Release 1.transform(x)) transform(tr) Performs only the non-aﬃne part of the transformation. but does not perform the ultimate aﬃne transformation into the correct position. class PolarAxes. An update to self does not cause a corresponding update to its inverted copy. path: a Path instance. path: a Path instance. x === self. Accepts a numpy array of shape (N x input_dims) and returns a numpy array of shape (N x output_dims). The only part of its bounds that is used is ymax (for the radius maximum). this is always a no-op. transformed only by the non-aﬃne part of this transform. this is generally equivalent to transform(values). The theta range is always ﬁxed to (0.Matplotlib. The return value of this method should be treated as temporary.transforms. transform_non_affine(tr) Performs only the non-aﬃne part of the transformation. transformed only by the non-aﬃne part of this transform. In aﬃne transformations. this is always a no-op. In non-aﬃne transformations. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). Adding new scales and projections to matplotlib . transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(va 276 Chapter 30. 2pi). this is generally equivalent to transform(values). limits is the view limit of the data.1 The aﬃne part of the polar projection. In aﬃne transformations.

For a polar plot. 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 ﬂoat (0. rpad=None. r) Return a format string formatting the coordinate using Unicode characters.set_rgrids(radii.Formatter Used to format the theta tick labels. If labels is None.0 PolarAxes.Bbox instance [True | False] [ (Path. angle=None. labels=None. label). PolarAxes.Locator Used to locate radius ticks. **kwargs) Set the radial locations and labels of the r grids. where line is Line2D instances and the label is Text instances. For all other tasks. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] 30. API documentation 277 . The labels will appear at radial distances radii at the given angle in degrees.0 transparent through 1. class PolarAxes.Matplotlib. PolarAxes.can_zoom() Return True if this axes support the zoom box PolarAxes.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.ticker.1 class PolarAxes. Release 1.ThetaFormatter Bases: matplotlib.RadialLocator(base) Bases: matplotlib. rpad is a fraction of the max of radii which will pad each of the radial labels in the radial direction. labels. is a len(radii) list of strings of the labels to use at each radius.format_coord(theta. the built-in formatter will be used. Return value is a list of tuples (line.0. it delegates to the base Locator (which may be diﬀerent depending on the scale of the r-axis.3. this should always be 1.transforms. fmt=None.ticker.get_data_ratio() Return the aspect ratio of the data itself. if not None. Ensures that all ticks are strictly positive. Converts the native unit of radians into degrees and adds a degree symbol.

figure.1 Table 30. Adding new scales and projections to 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’ | ﬂoat ﬂoat any number ACCEPTS: sequence of ﬂoats PolarAxes. 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.Matplotlib. **kwargs) call signature: set_yscale(value) Set the scaling of the y-axis: ‘linear’ | ‘log’ | ‘symlog’ ACCEPTS: [’linear’ | ‘log’ | ‘symlog’] Diﬀerent kwargs are accepted.font_manager.set_rscale(value.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.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. Release 1. or clipped to a very small positive number 278 Chapter 30.Figure instance a matplotlib.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.

3. where line is Line2D instances and the label is Text instances. frac=None. 3. 6.set_rticks(ticks. labels=None. if not None. 8. is a len(angles) list of strings of the labels to use at each angle. 7. 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 ﬂoat (0. 4. in a log10 scale: [0. fmt=None. 5. 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). For example. 6.1 subsx/subsy: Where to place the subticks between each major tick. 2. Should be a sequence of integers. 8. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. label). PolarAxes.0. 1. If labels is None. x) within which the plot is linear (to avoid having the plot go to inﬁnity around zero).set_thetagrids(angles. 1. 5.0 transparent through 1. For example. angles is in degrees. 7. labels. subsx/subsy: Where to place the subticks between each major tick. Release 1. API documentation 279 . Should be a sequence of integers.05 is outside the axes and 0. 4.Matplotlib. minor=False) Set the y ticks with list of ticks ACCEPTS: sequence of ﬂoats Keyword arguments: minor: [ False | True ] Sets the minor ticks if True PolarAxes. 2. **kwargs) Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). Eg.95 is inside the axes.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.transforms. 3. 9] will place 10 logarithmically spaced minor ticks between each major tick. 1.Bbox instance [True | False] [ (Path. 9] will place 10 logarithmically spaced minor ticks between each major tick. Transform) | Patch | None ] any matplotlib color 30. in a log10 scale: [0. Return value is a list of tuples (line.

Release 1.1 Table 30. Adding new scales and projections to 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’ | ﬂoat ﬂoat any number ACCEPTS: sequence of ﬂoats 280 Chapter 30.Figure instance a matplotlib.0.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.figure.Matplotlib.font_manager.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.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.

annotations fonts et al pyplot tut conﬁguration win32 install os x install linux install artist api event handling navigation interactive usage widgets ui . who has responsibility for them.mathtext text .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 . 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 . The “unit” doesn’t have to be a full chapter (though in some cases it will be).usetex text . and who reviews them. it may be a chapter or a section in a chapter.CHAPTER THIRTYONE DOCS OUTLINE Proposed chapters for the docs.

agg ? no author ? backend .1 Table 31.ps Darren has author ? backend .Matplotlib. Please be sure to follow the few guidelines described in Formatting. Once it is converted.svg ? no author ? backend . much less ﬂeshed 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.cairo ? no author ? Here is the ouline for the dev guide. Release 1.wx ? no author ? ui . Module backend_agg backend_cairo backend_cocoa backend_emf backend_ﬂtkagg 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.pdf Jouni ? no author ? backend .tk ? no author ? ui . Docs outline Darren Darren Darren Darren Darren 282 . we can ﬁgure out how best to organize the API Reference and continue from there.qt Darren has author ? backend . Eric.1 – continued from previous page ui . Mike? Eric ? We also have some work to do converting docstrings to ReST for the API Reference. Once docstring conversion is complete and all the modules are available in the docs.0. please include the module in the API documentation and update the status in the table to “converted”.

Release 1.2 – continued from previous page backend_wxagg needs conversion backends/tkagg needs conversion conﬁg/checkdep Darren needs conversion conﬁg/cutils Darren needs conversion conﬁg/mplconﬁg Darren needs conversion conﬁg/mpltraits Darren needs conversion conﬁg/rcparams Darren needs conversion conﬁg/rcsetup Darren needs conversion conﬁg/tconﬁg Darren needs conversion conﬁg/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 ﬁgure Darren needs conversion ﬁnance Darren needs conversion font_manager Mike converted fontconﬁg_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.0.1 Table 31.

Matplotlib. The backend chapters should cover backend speciﬁc conﬁguration (eg PS only options). and then pester them! Your only two responsibilities are getting your author to produce and checking their work. Maybe I should just take the link in the user’s guide out. you can change the status to “submitted” and try to ﬁnd a reviewer if you don’t have one. installation.. what features are missing.e. 284 Chapter 31. so don’t be shy. they should be removed. The UI chapters should give an example or two of using mpl with your GUI and any relevant info. volunteer to review or author a chapter. you can put them here. and change the status to “has author”. such as version. 31. As the author cleans them up or addresses them. test. . If mathtext. etc. You are free to lift and convert as much material from the web site or the existing latex user’s guide as you see ﬁt. if you have an author pester the author for a submission every so often. 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..py were to be documented. Release 1. this is pretty clear from readin ghte rc ﬁle.1 ticker transforms type1font units widgets Table 31. This section might also beneﬁt from a little more detail on the customizations that are possible (eg an example ﬂeshing out the rc options a little bit). conﬁg. Once you have signed up to be an editor.1.. Docs outline . but it might be helpful to a newbie..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. If you don’t have an author. The more the better. but that may also be overkill. ﬁnd one.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. remove the question mark by your name (or add your name if there is no candidate). give feedback and pester! 31. etc.0.MGD 2.. The reviewer should read your chapter. Once you have completed draft and checked it in. It is probably easiest to be an editor. etc. Admittedly.. If you agree to author a unit.1 Reviewer notes If you want to make notes for the authorwhen you have reviewed a submission. I would put it in the developer’s docs. test it for correctness (eg try your examples) and change the status to “complete” when done. • There’s nothing in the mathtext module that I really consider a “public” API (i.. Please feel free to add units. 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..

MGD 3.1 • The only rcParam that is currently useful is mathtext..fontset. which is documented here. .fontset == ‘custom’.. which I’d like to declare “unsupported”.Matplotlib. There is still a TODO in the ﬁle to include a complete list of symbols • Done.0. thanks to STIX. It’s pretty extensive. Release 1. The others only apply when mathtext. like sub/superscripts.MGD 31. . It’s really hard to get a good set of math fonts working that way. Reviewer notes 285 . though it might be useful in a bind when someone has to use a speciﬁc wacky font for mathtext and only needs basics.1.

Release 1.0.Matplotlib. Docs outline .1 286 Chapter 31.

Part IV The Matplotlib API 287 .

.

The limit kwargs have been renamed to left and right instead of xmin and xmax.Axes. this list may help describe what changes may be necessary in your code. – matplotlib.axes. and tick label formatting.ticklabel_format() is a convenience method for controlling the matplotlib.hist() color kwarg now accepts a sequence of color specs to match a sequence of datasets.axes.viewLim based on the matplotlib.1 Changes beyond 0. size.axes.Axes. and matplotlib.ScalarFormatter that is used by default with linear axes.EllipseCollection’ has been changed in two ways: 289 . and their corresponding pyplot functions.CHAPTER THIRTYTWO API CHANGES This chapter is a log of changes to matplotlib that aﬀect the outward-facing API.x • The default behavior of matplotlib.set_ylim(). tick location. has been changed: when view limits are set explicitly with one of these methods.axes.axes. the – matplotlib. A new auto kwarg is available to control this behavior. • There are ﬁve new Axes methods with corresponding pyplot functions to facilitate autoscaling.99.ticker. The old names may still be used.Axes. and the general appearance of ticks and tick labels: – matplotlib.axes.autoscale() turns autoscaling on or oﬀ.margins() sets margins used to autoscale matplotlib. and color of ticks and their labels.Axes.Axes.tick_params() controls direction. and bottom and top instead of ymin and ymax.Axes. • The matplotlib.axes.Axes.Axes. it is a dictionary of kwargs to be passed to the errorbar function.axes.Axes. autoscaling is turned oﬀ for the matching axis. – matplotlib. however.collections.bar() method accepts a error_kw kwarg.axis(). 32. – matplotlib.axes. • The matplotlib. • The :class:’~matplotlib. If updating matplotlib breaks your scripts.axes.Axes. visibility.Axes.axes.Axes.dataLim.locator_params() allows one to adjust axes locator parameters such as nbins.axes.set_xlim(). matplotlib. and applies it.

which are only required by the experimental traited conﬁg and are somewhat out of date. Therefore: draw_path_collection(self. gc. – The height and width kwargs have been changed to specify the height and width. This matches the :class:’~matplotlib. • You can now print several ﬁgures to one pdf ﬁle and modify the document information dictionary of a pdf ﬁle. linestyles. meshWidth. master_transform. matplotlib. antialiaseds. linewidths.savefig() if its fname argument lacks an extension. offsets. clippath_trans. clippath. install them independently.0. cliprect.patches. linewidths. coordinates. offsetTrans. • Removed conﬁgobj and enthought. bbox. showedges) draw_image(self.color.PdfPages for more information.Figure. even on collections and images. all clipping rectangles and paths are now passed in using GraphicsContext objects. clippath=None. master_transform. and the color cycle is now independent of the rc parameter lines.backend_pdf. im. gc. clippath_trans=None) # is now draw_image(self. edgecolors. • The new rc parameter savefig. See the docstrings of the class matplotlib. x. coordinates. gc. x. facecolors.set_default_color_cycle() is deprecated.Axes. offsetTrans. • In an eﬀort to simplify the backend API. im) • There are four new Axes methods with corresponding pyplot functions that deal with unstructured 290 Chapter 32. master_transform.Matplotlib. offsets. API Changes . that scales the ellipse with the data units. antialiased. all_transforms. y. ‘xy’. previously they speciﬁed the halfheight and half-width. showedges) # is now draw_quad_mesh(self.color_cycle. • There is a new rc parameter axes. meshHeight. antialiaseds. master_transform. antialiased. urls) draw_quad_mesh(self. Release 1.extension sets the ﬁlename extension that is used by matplotlib. y. clippath_trans. linestyles. clippath. edgecolors. meshHeight. offsetTrans.backends. offsets. paths. facecolors. facecolors. offsets. all_transforms. again for consistency with Ellipse. cliprect. paths.Ellipse‘ scaling. meshWidth. facecolors.traits packages. offsetTrans.1 – There is a new units option. If needed. and to better match their names. urls) # is now draw_path_collection(self.figure.

• Deprecated numerix package. Release 1.cm.save and np.tripcolor() draws a pseudocolor plot on a triangular grid. nonposy to matplotlib.2 Changes in 0. • Added new matplotlib. – matplotlib.axes.csv2rec since this is partially broken • Axes instances no longer have a “frame” attribute.pyplot. • Added new matplotlib. For other axes (such as polar axes). Instead. These are available in matplotlib. these artists are Line2D instances.imsave() and exposed it to the matplotlib. The previous behavior was more of an oversight than a design decision.axes.Axes.99 • pylab no longer provides a load and save function.set_cmap().axes. Changes in 0.g.fignum_exists() and matplotlib.Axes.99 291 .x • psd(). or np.Axes methods that set log scale parameters. This is much more sensible behavior and makes them consistent with specgram(). Spines is a dictionary where the keys are the names of the spines (e.Axes. 32. ‘left’. The default is still to mask out non-positive values. • Remove support for pyExcelerator in exceltools – use xlwt instead • Changed the defaults of acorr and xcorr to use usevlines=True. they merely expose information that had been hidden in matplotlib. Colormaps can be made the default and applied to the current image using matplotlib.triplot() draws a triangular grid as lines and/or markers.image. csd().loadtxt and numpy. maxlags=10 and normed=True since these are the best defaults 32.1 triangular grids: – matplotlib.2. • Added new keyword parameters nonposx. For normal (rectilinear) axes. • Polar plots no longer accept a resolution kwarg. Instead. that should be done before passing it to matplotlib.load for binary numpy arrays.tricontour() draws contour lines on a triangular grid.get_fignums().pyplot. but the kwargs accept ‘clip’.Matplotlib. • changed use_mrecords default to False in mlab.3 Changes for 0._pylab_helpers. – matplotlib.pyplot. and cohere() will now automatically wrap negative frequency components to the beginning of the returned arrays.axes.get_cmap(). This is unlikely to be a user-visible change – if interpolation of data is required.mlab.axes.savetxt for text ﬁles.pyplot interface.Axes. or you can use numpy.tricontourf() draws ﬁlled contours on a triangular grid. use the new “spines” attribute. – matplotlib. each Path must specify its own number of interpolation steps.’right’ and so on) and the values are the artists that draw the spines. which causes non-positive values to be replaced with a very small positive value. these artists may be Patch instances. • User-generated colormaps can now be added to the set recognized by matplotlib.0. 32.98.

default is 0. but should be closer to what was requested. Some fonts may be diﬀerent in plots.pyplot.axes.axes.contour.axesFrame renamed matplotlib. • Deprecated (raise NotImplementedError) all the mlab2 functions from matplotlib. API Changes .labelAttribute.1 • Following keyword parameters for matplotlib.specgram() to scale one-sided densities by a factor of 2.axes.Collection.0. but returns a guess based on the required FontName attribute.Axes. • matplotlib.mlab.csd(). matplotlib. Also. matplotlib.cl_cvalues 292 Chapter 32. and the string value ‘present’ is used for sparse arrays only to show ﬁlled locations.afm. • matplotlib.figurePatch renamed matplotlib. . The new parameters are given as a fraction of the font-size.patch.EllipseCollection added.Matplotlib.Figure.afm. matplotlib. matplotlib.pyplot. • matplotlib.Axes.axesPatch renamed matplotlib.Axes.Axes. The corresponding matplotlib.psd().get_offsets() and matplotlib. • Font lookup now uses a nearest-neighbor approach rather than an exact match.cl.Label are now deprecated and new set of parameters are introduced.collections.get_familyname() no longer raise an exception if the AFM ﬁle does not specify these optional attributes.label. Deprecated pad labelsep handlelen handlestextsep axespad New borderpad labelspacing handlelength handletextpad borderaxespad • Removed the conﬁgobj and experimental traits rc support • Modiﬁed matplotlib. This also gives better MATLAB compatibility.cl_xy and . • Added angles kwarg to matplotlib.mlab.figure.collections.get_fullname() and matplotlib.Axes.set_xlim().Collection.AFM.cohere().clabel() function) so that they all have a form like .set_ylim() now return a copy of the viewlim array to avoid modify-in-place surprises. Also.mlab.patch. fancybox and columnspacing are added as keyword parameters.collections.patch. which returns matplotlib. scatteryoﬀsets. optionally scale the densities by the sampling frequency.frame. which gives true values of densities that can be integrated by the returned frequency values. • Changes in the matplotlib.Figure.mlab.set_offsets() added to Collection base class.mlab out of concern that some of them were not clean room implementations.get_frame(). .figure.axes.axes. is deprecated.spy().axes. The three attributes that are most likely to be used by end users. Release 1.axes.Axes. • matplotlib. • Changed precision kwarg in matplotlib. and matplotlib. • Methods matplotlib.pyplot.pyplot functions were updated as well.quiver() for more ﬂexible speciﬁcation of the arrow angles.ContourLabeler attributes (matplotlib. matplotlib.Axes methods and matplotlib. matplotlib.Axes.axes.AFM.axes.Axes.

98. it will return a MxN or MxNx3 array if possible.ticker. • New axes method and pyplot function. This also means that the last bin doesn’t contain upper outliers any more by default. but they are deprecated and will eventually be removed. 32. Changes for 0.hist() now uses future Numpy 1.ScalarMappable callback infrastructure to use matplotlib.cbook into a separate module matplotlib.mlab and matplotlib. It makes something like a pcolor() of a 2-D histogram. hexbin().toolkits) 32.axes.CallbackRegistry rather than custom callback handling.Matplotlib. which was implicitly set to +inﬁnity in Numpy 1.image.4 Changes for 0. • In Numpy 1. Also uint8 is no longer always forced to ﬂoat.x 32. Providing binedges.cm. Release 1.cm.cbook.numerical_methods because they were unrelated to the initial purpose of mlab or cbook and appeared more coherent elsewhere.ScalarMappable. reversed() or izip() compatibility functions.98.callbacks CallbackRegistry instead.1 have been maintained for the moment (in addition to their renamed versions).Axes.axes3d support and replaced it with a non-implemented error pointing to 0.ScalarMappable. symmetric. bins are speciﬁed by the left edges only.91. • Moved several functions in matplotlib. • Rewrote the matplotlib.5 Changes for 0.0 • matplotlib. enumerate(). so matplotlib.MaxNLocator allows one require an axis to be centered around zero. Any users of matplotlib.0. is an alternative to scatter() for large datasets. • New axes function and Axes method provide control over the color cycle: matplotlib.axes.1 Notes about the transforms refactoring A major new feature of the 0.set_color_cycle().set_default_color_cycle() matplotlib.5. the last value gives the upper-right edge now. in matplotlib. • Toolkits must now be imported from mpl_toolkits (not matplotlib.98 series is a more ﬂexible and extensible transformation infrastructure.1 • Removed broken matplotlib. plot and • matplotlib now requires Python 2.98.Axes.1 293 .imread() now no longer always returns RGBA data—if the image is luminance or RGB. • New kwarg.cbook will no longer provide set.add_observer() of the ScalarMappable should use the matplotlib. 32. The axes method matplotlib. but uses hexagonal bins. written in Python/Numpy rather than a custom C extension.0.3 semantics for histograms.axes.4.4.cm.0.

Locator. 294 Chapter 32.transforms for a description of the design of the new transformation framework. which in turn looks up its limits from the Axes. Release 1. a dummy axis must be created to store its bounds. In particular. Its methods now all return copies rather than modifying in place. (e. API Changes . This is mostly an internal improvement. The functionality of Pbox has been merged with Bbox.ticker. many of these functions return views into Numpy arrays. their contents may change. For eﬃciency. The view intervals are now stored only in one place – in the matplotlib.contour). See matplotlib. not in the locator instances as well. If you want to store a snapshot of their current values. This means that if you hold on to a reference to them.create_dummy_axis() to do so.Matplotlib. and the possible user-visible changes it allows are yet to come. use the Numpy array method copy(). in matplotlib.1 The primary goal of this refactoring was to make it easier to extend matplotlib to support new kinds of projections.Axes instance. whereas methods that alter an object in place are named with a verb in the present tense. The following lists many of the simple changes necessary to update code from the old transformation framework to the new one.g. This means locators must get their limits from their matplotlib. Call matplotlib. If a locator is used temporarily and not assigned to an Axis or Axes.axis.Axis.axes. methods that return a copy are named with a verb in the past tense.0.

inverted(). ytrans) ytrans) scale_transform(xs.ymin() transforms.height() transforms.Bbox.intervalx Bbox.] lbwh_to_bbox(l.set_bounds() [Bbox.xmax() transforms.overlaps(bboxes)Bbox.intervaly().contains_open(v) Interval. x0 is not necessarily the left edge of the box.contains(v) interval_contains(tuple. w.Bbox.get_bounds() transforms. y0.Bbox.Bbox.intervaly Bbox.Bbox. Bbox. Aﬃne2D(). To get the left edge of the Bbox.Bbox. y1) and there is no deﬁned order to these points.intervalx is now a property. 1 32.ymax() transforms.y0 or transforms.union(bboxes) [transforms.Bbox.] Bbox.IdentityTransform tity_transform() blend_xy_sep_transform(xtrans.count_overlaps(bboxes) bbox_all(bboxes) Bbox. y0) to (x1.ymax 1 Bbox.inverse_xy_tup(points) The Bbox is bound by the points (x0. that is.y1 or transforms.1 matplotlib.xmin() transforms. v) idenmatplotlib. BboxTransform(boxin.intervalx(). boxout) or BboxTransformFrom(boxin) or boxout) BboxTransformTo(boxout) TransTransform. ys]) ys) get_bbox_transform(boxin.inverse_transformed(trans) verse_transform_bbox(trans.Bbox.x1 or transforms.width Bbox.height Bbox.Bbox.intervaly().seq_xy_tup(points) TransTransform.Bbox. Changes for 0. h) [transforms.Matplotlib.get_bounds() transforms.0 295 .xmax 1 Bbox.98.ymin 1 Bbox.Bbox. use the read-only property xmin.x0 or transforms.transform(points) form.bounds Bbox.xmin 1 Bbox.scale(xs[.intervalx().transform(points) form.width() transforms.union() is a staticmethod.5.Bbox.] Bbox. b.intervaly is now a property.Bbox.from_bounds(x0.get_bounds() transforms.0. v) val.set_bounds() [Bbox.from_bounds() is a w.Bbox.transforms.transforms Old method New method Bbox. Release 1. h) staticmethod. bbox) Interinterval_contains_open(tuple.] inBbox. blended_transform_factory(xtrans.Bbox.

path. 3 matplotlib.set_position() now accepts either four scalars or a matplotlib.toggle_log_lineary() matplotlib.e.collections Old method linestyle New method linestyles 6 matplotlib.Axes.set_position() matplotlib.Axes.transforms.axes Old method New method Axes.Matplotlib. Axes.] matplotlib.toggle_log_lineary() has been removed._segments 2 New method matplotlib.transforms.Transform that will be applied to the path immediately before clipping.to_rgba_array() returns an Nx4 Numpy array of RGBA color quadruples.Path instance and a matplotlib.projections.artist.get_position() 2 Axes. The Polar class has moved to matplotlib.transforms.get_position() used to return a list of points.contour. i.polar.get_position() matplotlib.axes.set_position() 3 Axes.0.Contour.set_clip_path(path.Bbox instance.Axes.axes. a single value or multiple values may be provided.path. 6 Linestyles are now treated like all other collection attributes.to_rgba_array(c) tor.artist Old method New method Artist. now it returns a matplotlib.] matplotlib.to_rgba_list(c) [matplotlib. API Changes . 4 Since the recfactoring allows for more than two scale types (‘log’ or ‘linear’).colors Old method New method ColorConverColorConvertor.set_clip_path(path) Artist.Bbox instance.axes. Release 1.ColorConvertor.Artist.axes.set_clip_path() now accepts a matplotlib. it no longer makes sense to have a toggle.Axes.contour Old method Contour.axes.Path instances.colors.1 matplotlib.Axes. matplotlib. transform) 5 matplotlib. 296 Chapter 32. 5 matplotlib.get_paths‘() [Returns a list of matplotlib.set_yscale() 4 Subplot class removed.

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, aﬃne_transform), where path is a matplotlib.path.Path instance and aﬃne_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 deﬁnes 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 ﬁle now has a parser for ﬁles like psfonts.map and pdftex.map, to map TeX font names to external ﬁles.

298

Chapter 32. API Changes

Matplotlib, Release 1.0.1

• The ﬁle matplotlib.type1font contains a new class for Type 1 fonts. Currently it simply reads pfa and pfb format ﬁles and stores the data in a way that is suitable for embedding in pdf ﬁles. 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 ﬁle in addition to a pfa/pfb ﬁle, 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=’ﬂat’; 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 eﬀect 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 aﬀect 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 ﬁnd that some font sizes and line widths appear diﬀerent 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 eﬃciency, pcolor and scatter have been rewritten to use polygon collections, which are a new set of objects from matplotlib.collections designed to enable eﬃcient 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 signiﬁcantly 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 diﬀerent elements of a collection to vary on a property, eg to have diﬀerent 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 ﬁx) 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 deﬁne 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 diﬀerent API than the Bound2D. Eg, if you want to get the width and height of the bbox OLD:: width = ﬁg.bbox.x.interval() height = ﬁg.bbox.y.interval() New:: width = ﬁg.bbox.width() height = ﬁg.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 deﬁne 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.Aﬃne. 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 diﬀerent 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 diﬀerent. 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

draw() and canvas.py. dpi=100) canvas = FigureCanvasGTK(fig) # a gtk. Ditto with state change. Eg.Matplotlib. this in now intialized with a FigureCanvas.0. Now the Figure class is independent of the backend. FigureGTK subclassed gtk.DrawingArea.py. In order to include figures into your apps.31 Changes for 0.4). eg by caching a font or layout instance in a dict with the prop tup as a key -. Release 1. Changes for 0. not a Figure.not needed with double buffered drawing. All prior calls to figure. 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. Figure instances used subclass GUI widgets that enabled them to be placed directly into figures. 32.DrawingArea canvas. and mpl_with_glade. so I hope the inconvenience is worth it.print_figure(args) Apologies for the inconvenience.draw() and figure.pack_start(canvas) If you use the NavigationToolbar. for example # gtk example fig = Figure(figsize=(5. Text drawing and get_window_extent functionality will be moved to the Renderer.get_pango_layout in backend_gtk for an example.AxisTextBase is now text. 32. The examples embedding_in_gtk.Text module * All the erase and reset functionality removed frmo AxisText .see RendererGTK. you now need to do. * backend_bases.31.42 * Refactoring AxisText to be backend independent.py all reflect the new API so use these as a guide.1 API There is one important API change for application developers.42 315 . embedding_in_gtk2.print_figure(args) should now be canvas. This refactorization brings significant more freedom in developing matplotlib and should bring better plotting capabilities. and FigureCanvas takes over the functionality formerly handled by Figure.show() vbox.

. . If True.y. bbox. Release 1.axes to matplotlib.32 Changes for 0.1 * Text.GcfBase attribute pagesize renamed to figsize 316 Chapter 32.matlab. Artists now clip themselves with their box * added _clipOn boolean attribute. API Changes .Matplotlib.axes into matplotlib.Patches * Initialized with a transx. gc clip to bbox.interval() is width.0.window for GTK and figManager.. transy * Initialized with a transx. Axis.axis * moved process_text_args to matplotlib. bbox. height.legend * Moved Tick._get_current_fig_manager renamed to matplotlib.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. etc. replaced by bbox and dpi * the clip_gc method is removed. bbox.get_current_fig_manager to allow user access to the GUI window attribute. YTick. for example. attributes.Line2D Patches now take transx.get_xy_display * Artist set_renderer and wash_brushes methods removed * Moved Legend class from matplotlib. transy which are Transform instances .40 .min is left.x.AxisTextBase * Initialized with a transx.max is top.. etc. the import process is much cleaner since there are no longer cyclic dependencies * matplotlib._get_xy_display renamed Text. YAxis from matplotlib. XAxis.frame for wx 32.text * After getting Text handled in a backend independent fashion.matlab. width. These are now accessible as.. eg figManager. transy which are Transform instances .. XTick.FigureBase attributes dpi is a DPI intance rather than scalar and new attribute bbox is a Bound2D in display coords. transy which are Transform instances * set_drawing_area removed * get_left_right and get_top_bottom are replaced by get_window_extent . and I got rid of the left.x.

dpi). something missing in my backend code. * FigureManagerBase moved to backend_bases * Gcf.1 .get_all_fig_managers Jeremy: Make sure to self. Release 1. figsize. Bound2D and Transform instances and more ._set_font. Changes for 0.3 compatible way . .Subplot * added fig instance to __init__ ._reset = False in AxisTextWX.new module transforms supplies Bound1D.Matplotlib. gcFace=None takes the place of filled=False . they provide a factory function new_figure_manager(num. The destroy method of the GcfDerived from the backends is moved to the derived FigureManager. Instead.True and False symbols provided by cbook in a python2.Axes * removed figbg attribute * added fig instance to __init__ * resizing is handled by figure call to resize.GcfBase is renamed by Gcf. Backends no longer need to derive from this class.get_all_figwins renamed to Gcf. This was 32.0.Changes to the MATLAB helpers API * _matlab_helpers.Renderer methods for patches now take gcEdge and gcFace instances.32.40 317 .

Matplotlib. Release 1.1 318 Chapter 32.0. API Changes .

1 matplotlib This is an object-orient plotting library. and savefig().artist deﬁnes the Artist base class for all classes that draw things. e. Modules include: matplotlib. subplots(). matplotlib. A procedural interface is provided by the companion pyplot module. show(). use: from pylab import * or using ipython: ipython -pylab For the most part.lines deﬁnes the Line2D class for drawing lines and markers matplotlib.pyplot import * To include numpy functions too. and Annotate classes matplotlib. matplotlib. pyplot is primarily for working interactively. subplot(). TextWithDash. The axes module is the highest level of OO access to the library.image deﬁnes the AxesImage and FigureImage classes matplotlib. direct use of the object-oriented library is encouraged when programming. The exceptions are the pyplot commands figure(). matplotlib.g: from matplotlib.figure deﬁnes the Figure class. which can greatly simplify scripting.text deﬁnes the Text.colors classes for interpreting color speciﬁcations and for making colormaps 319 . Most pylab commands are wrappers for Axes methods.CHAPTER THIRTYTHREE MATPLOTLIB CONFIGURATION 33.patches deﬁnes classes for drawing polygons matplotlib.axes deﬁnes the Axes class.collections classes for eﬃcient drawing of groups of lines or polygons matplotlib. which may be imported directly.

matplotlib was initially written by John D. It is initialized by code which may be overridded by a matplotlibrc ﬁle.cm colormaps and the ScalarMappable mixin class for providing color mapping functionality to other classes matplotlib. eg: rc(’lines’. In particular.ticker classes for calculating tick mark locations and for formatting tick labels matplotlib.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’.linewidth’] = 2 rcParams[’lines.. for axes.Matplotlib. matplotlib conﬁguration . it must be called before importing pylab (if pylab is imported). Release 1. for lines. Hunter (jdh2358 at gmail. eg.backends a subpackage with modules for various gui libraries and output formats The base matplotlib namespace includes: rcParams a global dictionary of default conﬁguration settings.rc(group. this function must be called immediately after importing matplotlib for the ﬁrst time. c=’r’) Note you can use python’s kwargs dictionary facility to store dictionaries of default parameters. and so on. matplotlib. you can customize the font rc as follows: 320 Chapter 33. Inc. kwargs is a dictionary attribute name/value pairs.facecolor. Group may also be a list or tuple of group names. **kwargs) Set the current rc params. eg. Occasionally the internal documentation (python docstrings) will refer to MATLAB®.0. (xtick.1 matplotlib. linewidth=2. Eg. If used. rc() a function for setting groups of rcParams values use() a function for setting the matplotlib backend. Group is the grouping for the rc.linewidth the group is lines. lw=2. color=’r’) sets the current rc params and is equivalent to: rcParams[’lines. the group is axes. a registered trademark of The MathWorks.com) and is now developed and maintained by a host of others. ytick).

’weight’ : ’bold’.Matplotlib. Release 1.switch_backends.0. For the Cairo backend. or. it must be called before importing matplotlib. warn=True) Set the matplotlib backend to one of the known backends. ’size’ : ’larger’} rc(’font’. **font) # pass in the font dict as kwargs This enables you to easily switch between several conﬁgurations. eg pyplot.1 font = {’family’ : ’monospace’.these are not the params loaded by the rc ﬁle. In certain black magic use cases. eg pure image backends) so one can set warn=False to supporess the warnings 33. if you are not using pylab.1.use(arg. we are doing the reloading necessary to make the backend switch work (in some cases.rcdefaults() Restore the default rc params . but mpl’s internal params. Use rcdefaults() to restore the default rc params after changes. Example: use(‘cairo. a warning is issued if you try and callthis after pylab or pyplot have been loaded. The argument is case-insensitive. matplotlib 321 .backends. See rc_ﬁle_defaults for reloading the default params from the rc ﬁle matplotlib. Note: this function must be called before importing pylab for the ﬁrst time.pdf’) will specify a default of pdf output generated by Cairo. the argument can have an extension to indicate the type of output. matplotlib. If warn is True.

Matplotlib. Release 1.0.1 322 Chapter 33. matplotlib conﬁguration .

898] AUTHOR: John D. copyrighted or used a non-BSD compatible license 2.get_bbox_font() [-168. had too many dependencies and I wanted a free standing lib 3. ’f’) 0 >>> afm. 238.get_fontname() ’Times-Roman’ >>> afm. 676] >>> afm.get_bbox_char(’!’) [130. Hunter <jdh2358@gmail.AFM(fh) Parse the AFM ﬁle in ﬁle object fh get_angle() Return the fontangle as ﬂoat get_bbox_char(c.1 matplotlib.CHAPTER THIRTYFOUR MATPLOTLIB AFM 34. Did more than I needed and it was easier to write my own than ﬁgure out how to just get what I needed from theirs It is pretty easy to use.afm’) >>> afm = AFM(fh) >>> afm.afm. and requires only built-in python libs: >>> from afm import AFM >>> fh = file(’ptmr8a.0 >>> afm.get_kern_dist(’A’.get_kern_dist(’A’. 683) >>> afm. -9. isord=False) 323 . ’y’) -92. 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. 1000.string_width_height(’What the heck?’) (6220. -218.com> class matplotlib.afm This is a python interface to Adobe Font Metrics Files.0.

isord=False) Get the height of character c from the bounding box. c2) Return the kerning pair distance (possibly 0) for chars c1 and c2 get_kern_dist_from_name(name1. h) tuple.0. ie. get_kern_dist(c1. isord=False) Get the name of the character. dkernpairs. ‘Times-Roman’ get_fullname() Return the font full name.1 get_capheight() Return the cap height as ﬂoat get_familyname() Return the font family name. or None if not speciﬁed in AFM ﬁle. eg.Matplotlib. ‘. This is the ink height (space is 0) get_horizontal_stem_width() Return the standard horizontal stem width as ﬂoat. eg. Release 1. ‘Bold’ or ‘Roman’ get_width_char(c. eg. dcomposite) tuple where dhead is a _parse_header() dict. name2) Return the kerning pair distance (possibly 0) for chars name1 and name2 get_name_char(c. matplotlib afm . ‘Times-Roman’ get_height_char(c. eg. or None if not speciﬁed in AFM ﬁle. get_weight() Return the font weight. Return value is a (dhead. matplotlib. ‘Times’ get_fontname() Return the font name. dcmetrics.parse_afm(fh) Parse the Adobe Font Metics ﬁle in ﬁle handle fh.’ 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 ﬂoat get_vertical_stem_width() Return the standard vertical stem width as ﬂoat. dcmetrics is a 324 Chapter 34. isord=False) Get the width of the character from the character metric WX ﬁeld get_width_from_char_name(name) Get the width of the character from a type1 character name get_xheight() Return the xheight as ﬂoat string_width_height(s) Return the string width (including kerning) and string height as a (w.afm.

Matplotlib. dkernpairs is a _parse_kern_pairs() dict (possibly {}).1 _parse_composites() dict. Release 1.afm 325 . matplotlib. and dcomposite is a _parse_composites() dict (possibly {}) 34.0.1.

matplotlib afm .0.1 326 Chapter 34.Matplotlib. Release 1.

PathPatch patches.Patch patches.ConnectionPatch artist.OﬀsetFrom patches.T extWithDash text.Arc patches.Arrow patches.ConnectionStyle patches.Ellipse text.VertexSelector patches.CHAPTER THIRTYFIVE MATPLOTLIB ARTISTS patches._Style patches.FancyArrowPatch patches.artist.Line2D patches.FancyBboxPatch patches. 327 .Artist Bases: object Abstract base class for someone who renders into a FigureCanvas.Polygon patches.1 matplotlib.Shadow patches.Circle patches.T ext text.Artist lines.ArrowStyle patches.Rectangle patches.RegularPolygon lines.Annotation 35.artist class matplotlib.YAArrow text.FancyArrow patches.W edge patches._AnnotationBase text.CirclePolygon patches.BoxStyle patches.

match can be •None: return all objects contained in artist (including artist) •function with signature boolean = match(artist) used to ﬁlter matches •class instance: eg Line2D. convert x using xaxis unit type convert_yunits(y) For artists in an axes.artist. Returns the truth value and a dictionary of artist speciﬁc details of selection. Only return artists of class type get_agg_filter() return ﬁlter function to be used for agg ﬁlter get_alpha() Return the alpha value used for blending . Release 1. Returns an id that is useful for removing the callback with remove_callback() later. convert y using yaxis unit type draw(renderer. convert_xunits(x) For artists in an axes. matplotlib artists .Matplotlib. contains(mouseevent) Test whether the artist contains the mouse event.Artist instances contained in self. such as which points are contained in the pick radius. See individual artists for details.0.not supported on all backends get_animated() Return the artist’s animated state get_axes() Return the Axes instance the artist resides in. match=None) Recursively ﬁnd all :class:matplotlib. *args. 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.1 add_callback(func) Adds a callback function that will be called whenever one of the Artist‘s properties changes. if the yaxis has units support. **kwargs) Derived classes drawing method findobj(match=None) pyplot signature: ﬁndobj(o=gcf(). or None get_children() Return a list of the child Artist‘s this :class:‘Artist contains.

get_figure() Return the Figure instance the artist belongs to. or None for default.0.5 3.0 2.1 20 15 10 5 0 0. get_gid() Returns the group id get_label() Get the label used for this artist in the legend.1.5 1. Release 1.0 Message length ---> Minimum Message Length Model length Data length Total message length 0. round to the nearest pixel center 35.0 get_contains() Return the _contains test used by the artist. 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.0 Model complexity ---> 2. matplotlib.5 1.Matplotlib.artist 329 .

calling all of the registered callbacks. is_figure_set() Returns True if the artist is assigned to a Figure. and the remaining aﬃne part of its transformation. The eﬀect will not be visible until the ﬁgure is redrawn. get_transformed_clip_path_and_affine() Return the clip path with the non-aﬃne part of its transformation applied. get_transform() Return the Transform instance used by this artist.. Call matplotlib.Axes. pick(mouseevent) call signature: pick(mouseevent) each child artist will ﬁre a pick event if mouseevent is over the artist and the artist has picker set pickable() Return True if Artist is pickable.g. pchanged() Fire an event when property changed. is_transform_set() Returns True if Artist has a transform explicitly set. properties() return a dictionary mapping property name -> value for all Artist props remove() Remove the artist from the ﬁgure if possible.axes.Matplotlib. with matplotlib.draw_idle(). e.relim() to update the axes limits if desired. 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.0. matplotlib artists . Note: relim() will not see collections even if the collection was added to axes with autolim = True. get_url() Returns the url get_visible() Return the artist’s visiblity get_zorder() Return the Artist‘s zorder.1 Only supported by the Agg and MacOSX backends.Axes. Note: there is no support for removing the artist’s legend entry. 330 Chapter 35.axes. Release 1.

which may be: •a Patch (or subclass) instance •a Path instance. if any. The new picker should be a callable function which determines whether the artist is hit by the mouse event: 35.0 opaque) set_animated(b) Set the artist’s animation state. ACCEPTS: [ (Path.0 transparent through 1.not supported on all backends.1 remove_callback(oid) Remove a callback based on its id.0. Release 1. ACCEPTS: an Axes instance set_clip_box(clipbox) Set the artist’s clip Bbox.Matplotlib. See Also: add_callback() For adding callbacks set(**kwargs) A tkstyle set command. this method will set the clipping box to the corresponding rectangle and set the clipping path to None. Transform) | Patch | None ] set_contains(picker) Replace the contains test used by this artist.1. to remove the clipping path For eﬃciency.artist 331 . which will be applied to the path before using it for clipping. set_alpha(alpha) Set the alpha value used for blending . transform=None) Set the artist’s clip path. ACCEPTS: [True | False] set_axes(axes) Set the Axes instance in which the artist resides. in which case an optional Transform instance may be provided.Bbox instance set_clip_on(b) Set whether artist uses clipping. ACCEPTS: a matplotlib. ACCEPTS: ﬂoat (0. if the path happens to be an axis-aligned rectangle. •None. matplotlib. pass kwargs to set properties set_agg_filter(ﬁlter_func) set agg_ﬁlter fuction. ACCEPTS: [True | False] set_clip_path(path.transforms.

matplotlib artists . if the mouse event is over the artist. ACCEPTS: any string set_lod(on) Set Level of Detail on or oﬀ. For some artists like lines and patch collections. mouseevent) If the mouse event is over the artist. it is a user supplied function which determines whether the artist is hit by the mouse event: hit.Matplotlib. 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 ﬁre a pick event if the mouse event is over the artist •A ﬂoat: if picker is a number it is interpreted as an epsilon tolerance in points and the artist will ﬁre oﬀ an event if it’s data is within epsilon of the mouse event. return hit=True and props is a dictionary of properties you want added to the PickEvent attributes. the indices of the data within epsilon of the pick event •A function: if picker is callable. ACCEPTS: a matplotlib.figure. return hit = True and props is a dictionary of properties you want returned with the contains test.0. props = picker(artist. props = picker(artist. If on. Release 1. 332 Chapter 35.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.1 hit. e. the artist may provide additional data to the pick event that is generated.g. ACCEPTS: a callable function set_figure(ﬁg) Set the Figure instance the artist belongs to. mouseevent) to determine the hit test. ACCEPTS: [None|ﬂoat|boolean|callable] set_rasterized(rasterized) Force rasterized (bitmap) drawing in vector backend output.

0. aliased_name(s) return ‘PROPNAME or alias’ if s has an alias. for the line markerfacecolor property. else return PROPNAME formatted for ReST 35.artist 333 . ACCEPTS: [True | False] set_zorder(level) Set the zorder for the artist. return ‘markerfacecolor or mfc’ and for the transform property.1. set_transform(t) Set the Transform instance used by this artist. E.g. which has an alias. which does not. 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. ACCEPTS: any number update(props) Update the properties of this Artist from the dictionary prop. Initialize the artist inspector with an Artist or sequence of Artists. Artists with lower zorder values are drawn ﬁrst. ACCEPTS: Transform instance set_url(url) Sets the url for the artist ACCEPTS: a url string set_visible(b) Set the artist’s visiblity. round to the nearest pixel center Only supported by the Agg and MacOSX backends. class matplotlib. If a sequence is used. matplotlib.ArtistInspector(o) A helper class to inspect an Artist and return information about it’s settable properties and their current values.1 Defaults to None. target) return ‘PROPNAME or alias’ if s has an alias. 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. else return PROPNAME. return ‘transform’ aliased_name_rest(s. Release 1. update_from(other) Copy properties from other to self.artist.Matplotlib.

return “[ ’-’ | ’--’ | ’-. return a list of strings of all settable properies and their valid values. pprint_setters(prop=None. pprint_setters_rest(prop=None.artist.Matplotlib.’ | ’:’ | ’steps’ | ’None’ ]” is_alias(o) Return True if method object o is an alias for another function.1 E.Artist instances contained in self. get_valid_values(attr) Get the legal arguments for the setter associated with attr. for a line linestyle.. matplotlib artists . it is a valid property name and that property will be returned as a string of property : valid values... return ‘transform’ findobj(match=None) Recursively ﬁnd all matplotlib.g. Eg.]. return ‘markerfacecolor or mfc’ and for the transform property. it is a valid property name and that property will be returned as a string of property : valid values. which has an alias. Release 1. This is done by querying the docstring of the function set_attr for a line that begins with ACCEPTS: Eg. pprint_getters() Return the getters and actual values as list of strings. Format the output for ReST If prop is not None. .0. If prop is not None. Eg. properties() return a dictionary mapping property name -> value 334 Chapter 35. which does not. } get_setters() Get the attribute strings with setters for object. return a list of strings of all settable properies and their valid values. leadingspace=2) If prop is None... If match is not None. for the line markerfacecolor property.. for a line. ’linewidth’. return [’markerfacecolor’. leadingspace=2) If prop is None. get_aliases() Get a dict mapping fullname -> alias for each alias in the ArtistInspector. ’linewidth’ : ’lw’. for lines: {’markerfacecolor’: ’mfc’. it can be •function with signature boolean = match(artist) •class instance: eg Line2D used to ﬁlter matches.

In the output. as well as to do introspection on the object.artist 335 .allow_rasterization(draw) Decorator for Artist. matplotlib. you can do: 35. ’linestyle’) # get the linestyle property obj is a Artist instance.text.0. **kwargs) matplotlib supports the use of setp() (“set property”) and getp() to set and get object properties.artist.getp(obj. For example. aliases and full property names will be listed as: property or alias = value e. e.get(obj. matplotlib.Matplotlib. If the property is ‘somename’. Provides routines that run before and after the draw call.g. property is an optional string for the property you want to return Example usage: getp(obj) # get all the object properties getp(obj.1.kwdoc(a) matplotlib.Text. ‘lw’ is an alias for ‘linewidth’. property=None) Return the value of object’s property. aliases and full property names will be listed as: property or alias = value e.get_somename() getp() can be used to query all the gettable properties with getp(obj). to set the linestyle of a line to be dashed.setp(obj.g. ‘lw’ is an alias for ‘linewidth’. eg Line2D or an instance of a Axes or matplotlib.text. Release 1.g. Many properties have aliases for shorter typing.artist.artist. Many properties have aliases for shorter typing.g.draw method. e.artist. In the output. property=None) Return the value of object’s property.: linewidth or lw = 2 matplotlib. The before and after functions are useful for changing artist-dependant renderer attributes or making other setup function calls.get_somename() getp() can be used to query all the gettable properties with getp(obj).artist. *args.1 matplotlib. If the property is ‘somename’. eg Line2D or an instance of a Axes or matplotlib.: linewidth or lw = 2 matplotlib. property is an optional string for the property you want to return Example usage: getp(obj) # get all the object properties getp(obj. this function returns obj. this function returns obj. ’linestyle’) # get the linestyle property obj is a Artist instance. such as starting and ﬂushing a mixed-mode renderer.Text.

For example. 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. all the instances will be set.1. line instances that make up the legend class matplotlib. y2) setp(lines..01) y1 = sin(2*pi*x) y2 = sin(4*pi*x) lines = plot(x. long output listing omitted setp() operates on a single instance or a list of instances.0.legend. Release 1.legend Place a legend on the axes at location loc. ‘upper left’ : 2. ’color’.offsetbox. y1. 2.g. evt) finalize_offset() 336 Chapter 35. ‘lower center’ : 8. only the ﬁrst instance in the sequence is used.’ | ’:’ | ’steps’ | ’None’ ] If you want to see all the properties that can be set. the following are equivalent: >>> setp(lines.DraggableOffsetBox artist_picker(legend. the following will make both lines thicker and red: >>> >>> >>> >>> >>> x = arange(0. use_blit=False) Bases: matplotlib. ’linestyle’) linestyle: [ ’-’ | ’--’ | ’-.DraggableLegend(legend.3]) >>> setp(line. r’) >>> setp(lines. (only implemented for axis legends) ‘upper right’ : 1.1 >>> line. If you are in query mode introspecting the possible values. When actually setting values. color=’r’) setp() works with the MATLAB style string/value pairs or with python kwargs. ‘lower right’ : 4. ‘upper center’ : 9. Return value is a sequence of text. and their possible values. ’linewidth’. ‘right’ : 5. linestyle=’--’) If you want to know the valid types of arguments.0. you can provide the name of the property you want to set without a value: >>> setp(line.2. you can do: >>> setp(line) . E. linewidth=2.Matplotlib.. = plot([1. suppose you have a list of two lines. ‘center right’ : 7. ‘center left’ : 6. ‘center’ : 10. linewidth=2.0. ‘lower left’ : 3. x.. matplotlib artists .2 matplotlib. color=’r’) # MATLAB style # python style 35.

borderaxespad=None. labelsep=None. 8. 7. prop=None. scatterpoints=3.legend 337 . pad=None. handles. handlelen=None.artist. (only implemented for axis legends) 1. axespad=None. title=None. ncol=1. 9. matplotlib. columnspacing=None.Legend(parent. handlelength=None. handletextpad=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. labels. shadow=None. Release 1. 5. 2. scatteryoﬀsets=None. loc=None.2.0. numpoints=None. 6. borderpad=None. 3.legend. 10.Artist Place a legend on the axes at location loc.1 class matplotlib. 4. mode=None. labelspacing=None. bbox_transform=None. frameon=True) Bases: matplotlib. markerscale=None. bbox_to_anchor=None.Matplotlib. Return value is a sequence of text. fancybox=None. loc can be a tuple of the noramilzed coordinate values with respect its parent. line instances that make up the legend •parent : the artist that contains the legend •handles : a list of artists (lines. patches) to add to the legend •labels : a list of strings to label the legend Optional keyword arguments: 35. handletextsep=None.

use rc if True. draw a frame (default is True) if True. 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 transform for the bbox. use_blit=False) Set the draggable state – if state is •None : toggle the current state •True : turn draggable on •False : turn draggable oﬀ If draggable is on. Release 1. original the number of points in the legend for line the number of points in the legend for scatter plot a list of yoﬀsets for scatter symbols in legend if True. 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. draggable(state=None.0. renderer. If None. a fontsize of 10 points and a handlelength=5 implies a handlelength of 50 points. *args. See set_bbox_to_anchor() for more detail. The legend location can be speciﬁed by setting loc with a tuple of 2 ﬂoats. Users can specify any arbitrary location for the legend using the bbox_to_anchor keyword argument. The DraggableLegend helper instance is returned if draggable is on.. E.Matplotlib. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 ﬂoats.1 Keyword loc prop markerscale numpoints scatterpoints scatteryoﬀsets 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. transAxes if None. matplotlib artists . draw a frame with a round fancybox. The pad and spacing parameters are measure in font-size units.g. which is interpreted as the lower-left corner of the legend in the normalized axes coordinate. you can drag the legend on the canvas with the mouse. **kwargs) Draw everything that belongs to the legend draw_frame(b) b is a boolean. draw(artist. Values from rcParams will be used if None.

bottom] where the width and height will be assumed to be zero.Artist A line .the line can have both a solid linestyle connecting all the vertices.lines. linestyle=None. markerfacecoloralt=’none’. **kwargs) Bases: matplotlib.0. bottom. ﬁllstyle=’full’. solid_joinstyle=None. color=None. pickradius=5. eg one can create “stepped” lines in various styles. matplotlib.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. antialiased=None.3 matplotlib. markeredgewidth=None. dash_joinstyle=None. markersize=None. class matplotlib. bbox can be a BboxBase instance. ydata. the drawing of the solid line is inﬂuenced by the drawstyle.3. dash_capstyle=None.Matplotlib. markeredgecolor=None.lines This module contains all the 2D line class which can draw with a variety of line styles. markevery=None.Line2D instances in the legend get_patches() return a list of patch instances in the legend get_texts() return a list of text. width. and a marker at each vertex. marker=None. drawstyle=None.lines 339 . transform=None) set the bbox that the legend will be anchored.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. height] in the given transform (normalized axes coordinate if None). 35. set_frame_on(b) Set whether the legend box patch is drawn ACCEPTS: [ True | False ] set_title(title) set the legend title 35. solid_capstyle=None. markers and colors.artist. Additionally. a tuple of [left. or a tuple of [left. markerfacecolor=None. linewidth=None.Line2D(xdata. Release 1.

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 ﬂoat (0. ydata.0.transforms.’ | ’. stride) ﬂoat distance in points or callable pick function fn(artist. Release 1.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind.1 Create a Line2D instance with x and y data in sequences xdata. matplotlib artists .Transform instance a url string [True | False] 1D array 1D array any number 340 Chapter 35. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.transforms.Matplotlib.0 transparent through 1.figure. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.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/oﬀ ink in points 2D array (rows are x.Bbox instance [True | False] [ (Path.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.

contains(mouseevent) Test whether the mouse event occurred on the line. If orig is True. return the original data get_drawstyle() get_fillstyle() return the marker ﬁllstyle 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}. renderer. Returns True if any values are within the radius along with {’ind’: pointlist is the set of points within the radius.1 See set_linestyle() for a decription of the line styles. set_marker() for a description of the markers. matplotlib.Matplotlib. The pick radius determines the precision of the location test (usually within ﬁve points of the value). Use get_pickradius() or set_pickradius() to view or modify it. where 35.lines 341 . TODO: sort returned indices by distance draw(artist.3. *args. **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. and set_drawstyle() for a description of the draw styles. ydata.0. Release 1.

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. matplotlib artists . Release 1. get_ydata(orig=True) Return the ydata. If orig is True.Matplotlib.0. else the processed data. If orig is True. get_xydata() Return the xy data as a Nx2 numpy array.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. is_dashed() return True if line is dashstyle recache(always=False) recache_always() set_aa(val) alias for set_antialiased 342 Chapter 35. return the original data. else the processed data.

matplotlib.3. ‘steps’ is equivalent to ‘steps-pre’ and is maintained for backward-compatibility.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. sequence of dashes with on oﬀ ink in points. ‘full’ means ﬁll the whole marker. The steps variants produce step-plots. if any.0.lines 343 . The other options are for half ﬁlled markers ACCEPTS: [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] set_linestyle(linestyle) Set the linestyle of the line (also accepts drawstyles) 35. If seq is empty or if seq = (None. ACCEPTS: sequence of on/oﬀ ink in points set_data(*args) Set the x and y data ACCEPTS: 2D array (rows are x.Matplotlib. 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. Release 1. y) or two 1D arrays set_drawstyle(drawstyle) Set the drawstyle of the plot ‘default’ connects the points with lines. ACCEPTS: [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] set_fillstyle(fs) Set the marker ﬁll style. None). the linestyle will be set to solid.

set_linewidth(w) Set the line width in points ACCEPTS: ﬂoat 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 ’.’ ’.1 linestyle ’-’ ’--’ ’-.’ ’:’ ’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. ’steps--’. See Also: set_drawstyle() To set the drawing style (stepping) of the plot.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a linestyle. e.Matplotlib.0.g.’ ’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. Release 1. matplotlib artists 344 . ACCEPTS: [ ’-’ | ’--’ | ’-.

.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 ‘$. ACCEPTS: any matplotlib color set_markerfacecoloralt(fc) Set the alternate marker face color. matplotlib. ACCEPTS: any matplotlib color set_markersize(sz) Set the marker size in points ACCEPTS: ﬂoat 35.$’] set_markeredgecolor(ec) Set the marker edge color ACCEPTS: any matplotlib color set_markeredgewidth(ew) Set the marker edge width in points ACCEPTS: ﬂoat value in points set_markerfacecolor(fc) Set the marker face color.lines 345 .Matplotlib..$’ render the string using mathtext ACCEPTS: [ ’+’ | ’*’ | ’..3.’ | ’.1 Table 35.0. Release 1..’ ’1’ | ’2’ | ’3’ | ’4’ ’<’ | ’>’ | ’D’ | ’H’ ’^’ | ’_’ | ’d’ | ’h’ ’o’ | ’p’ | ’s’ | ’v’ ’x’ | ’|’ TICKUP | TICKDOWN | TICKLEFT | TICKRIGHT CARETUP | CARETDOWN | CARETLEFT | CARETRIGHT ’None’ | ’ ’ | ” | ’$.

0.array for y ACCEPTS: 1D array 346 Chapter 35. 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.Transform instance set_xdata(x) Set the data np. every 5-th marker will be plotted.1 set_markevery(every) Set the markevery property to subsample the plot when using markers. ACCEPTS: ﬂoat distance in points or callable pick function fn(artist.Matplotlib. event) set_pickradius(d) Sets the pick radius used for containment tests ACCEPTS: ﬂoat 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.transforms.array for x ACCEPTS: 1D array set_ydata(y) Set the data np. matplotlib artists . Release 1. Eg if markevery=5. 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. N) will start at point start and plot every N-th marker ACCEPTS: None | integer | (startind.

y. **kwargs): lines.set_data(xs.draw() fig = plt.patches. width.patches.Matplotlib. The line should already be added to some matplotlib.VertexSelector. matplotlib. line. ys): self. y = np.axes.lines.markers.Axes instance and should have the picker property set. theta2=360. **kwargs) Bases: matplotlib. Because it performs various optimizations. = self. Release 1.lines as lines class HighlightSelected(lines.show() Initialize the class with a matplotlib. process_selected(ind.patches 347 . update the set of selected indicies. 35.patches class matplotlib. An elliptical arc.VertexSelector): def __init__(self. **kwargs) def process_selected(self.add_subplot(111) x.random. Here is an example which highlights the selected verts with red circles: import numpy as np import matplotlib. ind. ’bs-’. xs.__init__(self.Ellipse angle=0.markers.lines. y. ys) self.axes. matplotlib.VertexSelector(line) Manage the callbacks to maintain a list of selected vertices for matplotlib.canvas. height. it can not be ﬁlled.Line2D.figure() ax = fig.rand(2.pyplot as plt import matplotlib. []. Derived classes should override process_selected() to do something with the picks.4.4 matplotlib.0. xs.Line2D instance.plot([]. ind are the indices of the selected vertices.plot(x. fmt.lines.1 update_from(other) copy properties from other to self class matplotlib. onpick(event) When the line is picked. cy. theta1=0. 35.segment_hits(cx. fmt=’ro’. 30) line.Arc(xy.0.lines. radius) Determine if any line segments are within radius of a point. picker=5) selector = HighlightSelected(line) plt. line) self. x. ys) Default “do nothing” implementation of the process_selected() method.0. = ax.0. Returns the list of line segments that are within that radius. xs and ys are the coordinates of the selected vertices.

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. Release 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 Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. renderer.0. or ‘none’ for no color a matplotlib. or None for default. *args. The 348 Chapter 35.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.Matplotlib.transforms. or ‘none’ for no color mpl color spec.Bbox instance [True | False] [ (Path. or None for default.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number draw(artist. the arc will form a complete ellipse.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. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. matplotlib artists .figure. **kwargs) Ellipses are normally drawn using an approximation that uses eight cubic bezier splines.

Geometry for Computer Graphics: Formulae. **kwargs) Bases: matplotlib. Draws an arrow.0. according to this unveriﬁed source: Lancaster. (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. starting at (x. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines.Arrow(x.Proceeding counterclockwise starting in the positive x-direction. dy. width=1. This uses the “line intersecting a circle” algorithm from: Vince.patches. Examples & Proofs. y.89818e-6. Valid kwargs are: 35. direction and length given by (dx.0. In that case. 3. class matplotlib.com/glib/ellipse4.pdf There is a use case where very large ellipses must be drawn with very high accuracy.path. London: Springer-Verlag.The points where the ellipse intersects the axes bounding box are located.1 error of this approximation is 1.patches 349 . a diﬀerent technique is used. only the visible parts of the ellipse are drawn.Matplotlib.The angles of each of the intersection points are calculated. dx. y). Don.tinaja.Path. matplotlib. Release 1.arc(). each of the visible arcsegments between the pairs of vertices are drawn using the bezier arc approximation technique implemented in matplotlib. http://www.Patch An arrow patch. dy) the width of the arrow is scaled by width. 2005. Therefore. The algorithm proceeds as follows: 1. and it is too expensive to render the entire ellipse with enough segments (either splines or line segments). with each visible arc using a ﬁxed number of spline segments (8). 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 oﬀset from the ideal).patches.4. John.

ArrowStyle Bases: matplotlib.Bbox instance [True | False] [ (Path. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. head_length=. Release 1.4.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib.4") 350 Chapter 35. These are mainly used with FancyArrowPatch.4. or None for default. or None for default. head_width=.transforms. or ‘none’ for no color 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 get_patch_transform() get_path() Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.0. or ‘none’ for no color a matplotlib.4. head_width=.Fancy(head_length=. tail_width=.4.figure.4. head_width=.patches. tail_width=. matplotlib artists . which is used to create an arrow path along a given path.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.4) or: ArrowStyle("Fancy". head_length=. A arrowstyle object can be either created as: ArrowStyle.Matplotlib.4._Style ArrowStyle is a container class which deﬁnes several arrowstyle classes.4) or: ArrowStyle("Fancy.patches. tail_width=.

angleB=None) Bases: matplotlib.2 <|-|> head_length=0.head_width=0. widthA width of the bracket lengthA length of the bracket 35.4.2.angleA=None.4.2 widthB=1.2 head_length=0.0. linewidth.4.lengthB=0.head_width=0. lengthA=0.4.Matplotlib. angleA=None. linewidth is a line width to be stroked.angleB=None head_length=0. path is a Path instance along witch the arrow will be drawn.head_width=0. class BarAB(widthA=1.0.0.head_width=0.0.angleB=None An instance of any arrow style class is an callable object. widthB=1._Bracket An arrow with a bracket(]) at its end.2 head_length=0.widthB=1.0.widthB=1. whose call signature is: __call__(self.head_width=0._Bracket An arrow with a bracket(]) at both ends. angleA=None) Bases: matplotlib.head_width=0.0.1 The following classes are deﬁned Class Curve CurveB BracketB CurveFilledB CurveA CurveAB CurveFilledA CurveFilledAB BracketA BracketAB Fancy Simple Wedge BarAB Name -> -[ -|> <<-> <|Attrs None head_length=0.20000000000000001.lengthA=0.tail_width=0.4.angleA=None.4.2.2 ]]-[ fancy simple wedge |-| widthA=1.BracketA(widthA=1.2 head_length=0. This is meant to be used to correct the location of the head so that it does not overshoot the destination point.0.5.shrink_factor=0. but not all classes support it. aspect_ratio=1.angleB=None head_length=0.patches.4.2. mutation_size and aspect_ratio has a same meaning as in BoxStyle.tail_width=0.lengthA=0.5 widthA=1.4.patches.0.5.head_width=0.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 tail_width=0.) and it returns a tuple of a Path instance and a boolean value.lengthB=0.0.patches 351 .0.4.2. mutation_size.4 head_length=0. path. Release 1. matplotlib.3.angleA=None widthA=1.

Matplotlib. Release 1. matplotlib artists .1 -> -[ -| > <<.> <|- <|-| > ]]-[ fancy simple wedge |-| 352 Chapter 35.0.

patches.CurveB(head_length=0.20000000000000001) Bases: matplotlib.1 angleA angle between the bracket and the line class ArrowStyle. angleB=None) Bases: matplotlib.40000000000000002.patches.CurveA(head_length=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.0.BracketAB(widthA=1. head_width=0._Bracket An arrow with a bracket([) at its end. angleA=None. 35.20000000000000001) Bases: matplotlib._Curve An arrow with a head at its begin point. class ArrowStyle.20000000000000001.Matplotlib.20000000000000001. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.patches.patches. lengthB=0.40000000000000002.20000000000000001) Bases: matplotlib.BracketB(widthB=1. head_width=0.patches 353 .0. lengthA=0.40000000000000002._Curve An arrow with a head at its end point.20000000000000001.0. lengthB=0.Curve Bases: matplotlib._Curve A simple curve without any arrow head. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.patches. matplotlib.0.CurveAB(head_length=0._Bracket An arrow with a bracket(]) at both ends.patches._Curve An arrow with heads both at the begin and the end point. widthB=1. widthB width of the bracket lengthB length of the bracket angleB angle between the bracket and the line class ArrowStyle. Release 1. head_width=0.4. angleB=None) Bases: matplotlib.

_Base A simple arrow.40000000000000002. tail_width=0. head_width=0.1 head_length length of the arrow head head_width width of the arrow head class ArrowStyle.20000000000000001) Bases: matplotlib. tail_width=0.CurveFilledAB(head_length=0.5. 354 Chapter 35. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.0.patches.40000000000000002. head_width=0._Curve An arrow with ﬁlled triangle head at the end.patches. Only works with a quadratic bezier curve.20000000000000001) Bases: matplotlib._Curve An arrow with ﬁlled triangle heads both at the begin and the end point.20000000000000001) Bases: matplotlib. Release 1. linewidth) class ArrowStyle.40000000000000002. mutation_size. head_length length of the arrow head head_with width of the arrow head tail_width width of the arrow tail transmute(path.patches.Simple(head_length=0. Only works with a quadratic bezier curve.patches.20000000000000001) Bases: matplotlib. head_width=0. head_length length of the arrow head head_width width of the arrow head class ArrowStyle.40000000000000002._Curve An arrow with ﬁlled triangle head at the begin._Base A fancy arrow.CurveFilledA(head_length=0. head_length length of the arrow head head_with width of the arrow head tail_width width of the arrow tail head_width=0.CurveFilledB(head_length=0.Fancy(head_length=0.Matplotlib.5.40000000000000002) Bases: matplotlib. head_width=0. head_length length of the arrow head head_width width of the arrow head class ArrowStyle. matplotlib artists .patches.40000000000000002.

29999999999999999) Bases: matplotlib. mutation_scale determines the overall size of the mutation (by which I mean the transformation of the rectangle to the fancy box).rounding_size=None pad=0.0. the width is shrink_factor*tail_width.3. x0.2) or: BoxStyle("Round.3.3 An instance of any boxstyle class is an callable object. matplotlib. width.3.tooth_size=None pad=0._Style BoxStyle is a container class which deﬁnes several boxstyle classes.BoxStyle Bases: matplotlib. Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0.patches. A style object can be created as: BoxStyle.Matplotlib. tail_width width of the tail shrink_factor fraction of the arrow width at the middle point transmute(path.Wedge(tail_width=0. class LArrow(pad=0.rounding_size=None pad=0. height.2) or: BoxStyle("Round".tooth_size=None pad=0. pad=0. y0.patches._Base Wedge(?) shape.3.) and returns a Path instance.Round(pad=0. x0. shrink_factor=0.4. pad=0. Release 1. The begin point has a width of the tail_width and the end point has a width of 0. aspect_ratio=1.3 pad=0. linewidth) class matplotlib.5) Bases: matplotlib. mutation_size. which are used for FancyBoxPatch.patches.2") Following boxstyle classes are deﬁned.1 transmute(path.3 pad=0. width and height specify the location and size of the box to be drawn. mutation_size.29999999999999999. linewidth) class ArrowStyle. mutation_size. whose call signature is: __call__(self.patches._Base 35. y0. Only wokrs with a quadratic bezier curve. At the middle. mutation_aspect determines the aspect-ratio of the mutation.patches 355 .

1 square sawtooth roundtooth rarrow larrow round4 round 356 Chapter 35.Matplotlib. Release 1.0. matplotlib artists .

patches.patches.1 (left) Arrow Box transmute(x0. y0. matplotlib. mutation_size) class BoxStyle.LArrow (right) Arrow Box transmute(x0.29999999999999999.patches._Base Another box with round edges._Base A box with round corners.29999999999999999._Base A sawtooth box.Round4(pad=0. height. y0.Sawtooth(pad=0. y0. pad* if None transmute(x0. mutation_size) class BoxStyle. Release 1.patches.4. height.Sawtooth A roundtooth(?) box. pad if None transmute(x0._Base A simple square box. pad* if None transmute(x0. width. width.Roundtooth(pad=0.29999999999999999. y0. pad if None transmute(x0.0. tooth_size=None) Bases: matplotlib.Matplotlib. mutation_size) class BoxStyle. pad amount of padding 35. pad amount of padding tooth_size size of the sawtooth. pad amount of padding rounding_size rounding radius of corners. mutation_size) class BoxStyle.RArrow(pad=0. height. height. rounding_size=None) Bases: matplotlib.Round(pad=0. y0.patches. height. width.29999999999999999) Bases: matplotlib.29999999999999999.Square(pad=0. pad amount of padding rounding_size rounding size of edges.patches 357 . width. y0. mutation_size) class BoxStyle. width. tooth_size=None) Bases: matplotlib. rounding_size=None) Bases: matplotlib.patches. height. pad amount of padding tooth_size size of the sawtooth. mutation_size) class BoxStyle. width.29999999999999999) Bases: 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 Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. Release 1. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. height.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. width. y) with given radius.Bbox instance [True | False] [ (Path. or None for default.Matplotlib.patches. this uses Bézier splines and is much closer to a scale-free circle.1 transmute(x0. or None for default. or ‘none’ for no color mpl color spec. Unlike CirclePolygon which is a polygonal approximation. radius=5.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|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: ﬂoat 358 Chapter 35. **kwargs) Bases: matplotlib.transforms.0.Ellipse A circle patch. mutation_size) class matplotlib.Circle(xy. or ‘none’ for no color a matplotlib.patches. Create true circle at center xy = (x.figure. y0. matplotlib artists .

mutation_aspect=None.patches. shrinkB=0. **kwargs) Bases: matplotlib. connectionstyle=’arc3’. This circle is approximated by a regular polygon with resolution sides. resolution=20. patchA=None. connector=None. radius=5.0. 35. 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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.figure.patches.0.CirclePolygon(xy.FancyArrowPatch A ConnectionPatch class is to make connecting lines between two points (possibly in diﬀerent axes). axesA=None.0. or ‘none’ for no color a matplotlib.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib. axesB=None.transforms. arrowstyle=’-‘. Create a circle at xy = (x.0.patches 359 .Matplotlib. see Circle. coordsA. or None for default.1 class matplotlib. y) with given radius. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.0. arrow_transmuter=None. xyB. or None for default. shrinkA=0. patchB=None. For a smoother circle drawn with splines. clip_on=False. mutation_scale=10.ConnectionPatch(xyA.Bbox instance [True | False] [ (Path. dpi_cor=1. coordsB=None. matplotlib.patches. **kwargs) Bases: matplotlib. or ‘none’ for no color mpl color spec.RegularPolygon A polygon-approximation of a circle patch.patches.4. Release 1.

get_annotation_clip() Return annotation_clip attribute. right points from lower left corner of axes pixels from lower left corner of axes 0. Property ‘ﬁgure points’ ‘ﬁgure pixels’ ‘ﬁgure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘oﬀset points’ ‘polar’ Description points from the lower left corner of the ﬁgure pixels from the lower left corner of the ﬁgure 0. even in cartesian plots. any key for matplotlib.0.5. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system.0 is lower left of ﬁgure and 1.1 is upper right use the coordinate system of the object being annotated (default) Specify an oﬀset (in points) from the xy value you can specify theta.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.1 is upper.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. r for the annotation.PathPatch coordsA and coordsB are strings that indicate the coordinates of xyA and xyB. get_path_in_displaycoord() Return the mutated path of the arrow in the display coord 360 Chapter 35. See set_annotation_clip() for the meaning of return values. Release 1.patches. matplotlib artists . 0.1 is lower left of axes and 1. Note that if you are using a polar axes.Matplotlib. draw(renderer) Draw.

0.fraction=0..0 rad=0.2) or: ConnectionStyle("Arc3._Style ConnectionStyle is a container class which deﬁnes several connectionstyle classes.0.) and it returns a Path instance.angle=None An instance of any connection style class is an callable object.2") The following classes are deﬁned Class Angle Angle3 Arc Arc3 Bar Name angle angle3 arc arc3 bar Attrs angleA=90. the returned path is clipped so that it start (or end) from the boundary of the patch. posA and posB are tuples of x. patchB=None. Release 1.rad=0.Matplotlib.rad=0. These are mainly used with FancyArrowPatch. rad=0. The path is further shrunk by shrinkA (or shrinkB) which is given in points.armB=0. The connecting edges are rounded with rad. 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).Arc3(rad=0.0 angleA=90.angleB=0. shrinkA=2.patches._Base Creates a picewise continuous quadratic bezier path between two points. matplotlib.patches.4.xy will be checked only if xycoords is “data” class matplotlib. posA.0 armA=0. rad=0.ConnectionStyle Bases: matplotlib. A connectionstyle object can be either created as: ConnectionStyle. •True : the annotation will only be drawn when self.xy is inside the axes.patches. class Angle(angleA=90. •False : the annotation will always be drawn regardless of its position.armA=None. •None : the self.0) Bases: matplotlib. angleA starting angle of the path angleB ending angle of the path rad rounding radius of the edge 35.1 set_annotation_clip(b) set annotation_clip attribute.patches 361 . whose call signature is: __call__(self.angleB=0 angleA=0. patchA=None. shrinkB=2. angleB=0. rad=0.0.armB=None. which is used to create a path between two points.angleB=0. patchA (or patchB) is given.y coordinates of the two points to be connected. posB.3.2) or: ConnectionStyle("Arc3".

rad curvature of the curve.0. a point placed at the distance of armA and angle of angleA from point A. The path can have two passing-through points.Angle3(angleA=90. angleB=0) Bases: matplotlib. One of the arm is extend so that they are connected in a right angle. armA=None._Base Creates a picewise continuous quadratic bezier path between two points. another point with respect to point B.0. posB) class ConnectionStyle.patches.1 connect(posA. The edges are rounded with rad. connect(posA._Base Creates a simple quadratic bezier curve between two points.patches. angle : anlge of the connecting line (if None._Base Creates a simple quadratic bezier curve between two points. 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. posB) class ConnectionStyle.Bar(armA=0. armB=0. fraction=0.Matplotlib. parallel to A and B) connect(posA. posB) class ConnectionStyle._Base A line with angle between A and B with armA and armB. The length of armA is determined by (armA + fraction x AB distance).0) Bases: matplotlib.29999999999999999.Arc(angleA=0. posB) class ConnectionStyle.Arc3(rad=0. 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. Same for armB. angleA starting angle of the path angleB ending angle of the path connect(posA.0.0) Bases: matplotlib. 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.patches. posB) 362 Chapter 35. armB=None.patches. Release 1. matplotlib artists . angle=None) Bases: matplotlib. angleB=0. rad=0. 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).

1 class matplotlib.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 35.Ellipse(xy.Patch A scale-free ellipse.Matplotlib. or None for default. angle=0.patches 363 . Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or None for default. or ‘none’ for no color a matplotlib. height. or ‘none’ for no color mpl color spec.patches.0. Release 1.4.transforms. matplotlib.Bbox instance [True | False] [ (Path. **kwargs) Bases: matplotlib.0.figure. width.patches. 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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.

y.0. but lets you set head width and head height independently. width=0. or ‘none’ for no color mpl color spec.Polygon Like Arrow.FancyArrow(x.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. or ‘none’ for no color a matplotlib.figure. shape=’full’.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 364 Chapter 35. matplotlib artists . 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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. shape: [’full’. head_length=None. or None for default. Constructor arguments length_includes_head: True if head is counted in calculating the length. the head starts being drawn at coordinate 0 instead of ending at coordinate 0. dy. head_width=None.1 class matplotlib.001. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. head_starts_at_zero=False.patches. head_starts_at_zero: If True. overhang=0.patches. **kwargs) Bases: matplotlib. ‘left’. Release 1.transforms. length_includes_head=False. dx. or None for default.Matplotlib. ‘right’] overhang: distance that the arrow is swept back (0 overhang means triangular shape).Bbox instance [True | False] [ (Path.

posB=None.g.patches. Class Angle Angle3 Arc Arc3 Bar Name angle angle3 arc arc3 bar Attrs angleA=90.FancyArrowPatch(posA=None.0.4.head_width=0.0.0. and shrinkB are ignored. dpi_cor=1.angle=None The arrowstyle describes how the fancy arrow will be drawn. connectionstyle=’arc3’.Matplotlib.0.4.0.4. arrow_transmuter=None.angleA=None.angleA=None widthA=1. shrinkB=2. path=None.0.4. patchB. The optional attributes are meant to be scaled with the mutation_scale.angleA=None.5 widthA=1.head_width=0. The connectionstyle describes how posA and posB are connected.shrink_factor=0. patchA=None..fraction=0.4. The following arrow styles are available. matplotlib.2 tail_width=0.armB=None.0.head_width=0.0. shrinkA=2.2 <|-|> head_length=0.2 head_length=0.3. mutation_scale=1.0.tail_width=0.head_width=0.4.2. connector=None.lengthB=0.0 rad=0. An arrow is drawn along this resulting path using the arrowstyle parameter.armA=None.4. arrowstyle=’simple’.0 angleA=90.2.lengthB=0.0. mutation_aspect=None.0. shrinkA.5. with optional comma-separated attributes.4 head_length=0.angleB=0.widthB=1.0. head_length) will be scaled.4. or one of the ArrowStyle instance.1 class matplotlib.rad=0. a path connecting two point are created according to the connectionstyle. It can be string of the available arrowstyle names.5. with optional comma-separated attributes.0 armA=0. It can be an instance of the ConnectionStyle class (matplotlib.patches 365 .armB=0. **kwargs) Bases: matplotlib.2 widthB=1. If posA and posB is given.ConnectionStlye) or a string of the connectionstyle name.angleB=None mutation_scale [a value with which attributes of arrowstyle] (e.2. The path will be clipped with patchA and patchB and further shirnked by shrinkA and shrinkB.2 head_length=0. de35.rad=0.head_width=0.patches.Patch A fancy arrow patch. an arrow is drawn along this path and patchA.angleB=None head_length=0.tail_width=0.0.patches. Release 1.4.3.angleB=0.lengthA=0.head_width=0.head_width=0. Class Curve CurveB BracketB CurveFilledB CurveA CurveAB CurveFilledA CurveFilledAB BracketA BracketAB Fancy Simple Wedge BarAB Name -> -[ -|> <<-> <|Attrs None head_length=0. patchB=None. The following connection styles are available. If path provided.angleB=0 angleA=0.widthB=1.2 ]]-[ fancy simple wedge |-| widthA=1.angleB=None head_length=0.2 head_length=0.head_width=0.2. It draws an arrow using the :class:ArrowStyle.lengthA=0.

transforms.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number .figure. or ‘none’ for no color mpl color spec. 366 Chapter 35.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.1 fault=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 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. get_mutation_aspect() Return the aspect ratio of the bbox mutation. matplotlib artists Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.Bbox instance [True | False] [ (Path. Mutation scale is not aﬀected by this. 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. or None for default.0. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. default=None.Matplotlib. Release 1. or ‘none’ for no color a matplotlib. or None for default.

head_length=0. set_arrowstyle(“Fancy.angleA=0. Use get_path_in_displaycoord() method to retrieve the arrow path in the disaply coord. posB) set the begin end end positions of the connecting path.armA=30.head_length=0. set_patchB(patchB) set the begin patch set_positions(posA. arrowstyle can be a string with arrowstyle name with optional comma-separated attributes.rad=10”) gleA=0. return available styles as a list of strings. Mutation scale is not aﬀected by this. ACCEPTS: ﬂoat set_mutation_scale(scale) Set the mutation scale.4. connectionstyle can be a string with connectionstyle name with optional comma-separated attributes. **kw) Set the arrow style. Without argument (or with connectionstyle=None).2) Old attrs simply are forgotten. Alternatively. the attrs can be probided as keywords. Without argument (or with arrowstyle=None). set_connectionstyle(connectionstyle.1 get_mutation_scale() Return the mutation scale.Matplotlib. return available box styles as a list of strings. set_connectionstyle(“arc. **kw) Set the connection style.armA=30. ACCEPTS: ﬂoat set_patchA(patchA) set the begin patch. matplotlib.0.2”) set_arrowstyle(“fancy”. the attrs can be provided as keywords. get_path_in_displaycoord() Return the mutated path of the arrow in the display coord set_arrowstyle(arrowstyle=None.patches 367 . get_path() return the path of the arrow in the data coordinate. set_mutation_aspect(aspect) Set the aspect ratio of the bbox mutation. Release 1. Alternatively. an- 35. Use current vlaue if None. set_dpi_cor(dpi_cor) dpi_cor is currently used for linewidth-related things and shink factor. set_connectionstyle(“arc”.rad=10) Old attrs simply are forgotten.

rounding_size=None pad=0. **kwargs) Bases: matplotlib. It can be a string of the style name with a comma separated attribute. Valid kwargs are: 368 Chapter 35. default=1.patches.g. but it draws a fancy box around the rectangle.3 pad=0.0.3.Patch Draw a fancy box around a rectangle with lower left at xy*=(*x.3. mutation_scale=1. Release 1.1 class matplotlib.3 pad=0. Following box styles are available.tooth_size=None pad=0. mutation_aspect=None. Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0. height boxstyle determines what kind of fancy box will be drawn. bbox_transmuter=None.. height.3. xy = lower left corner width. pad) will be scaled. 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. FancyBboxPatch class is similar to Rectangle class.rounding_size=None pad=0.3. y) with speciﬁed width and height. boxstyle=’round’.tooth_size=None pad=0.0. default=None. matplotlib artists .Matplotlib. width.FancyBboxPatch(xy.3 mutation_scale : a value with which attributes of boxstyle (e. or an instance of BoxStyle. The transformation of the rectangle box to the fancy box is delegated to the BoxTransmuterBase and its derived classes.patches.

or ‘none’ for no color mpl color spec.transforms.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. Release 1.4.Bbox instance [True | False] [ (Path. get_mutation_scale() Return the mutation scale. matplotlib.0. or None for default.Matplotlib.figure. 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.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|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.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.patches 369 . Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. or None for default. or ‘none’ for no color a matplotlib.

rounding_size=None pad=0. ACCEPTS: ﬂoat set_width(w) Set the width rectangle ACCEPTS: ﬂoat set_x(x) Set the left coord of the rectangle Name larrow rarrow round round4 roundtooth sawtooth square Attrs pad=0. pad=0. bottom. Release 1.3. matplotlib artists .3.3. Without argument (or with boxstyle = None). ACCEPTS: ﬂoat set_mutation_scale(scale) Set the mutation scale. it returns available box styles.2") set_boxstyle("round". the attrs can be provided as keywords: set_boxstyle("round.1 get_y() Return the bottom coord of the rectangle set_bounds(*args) Set the bounds of the rectangle: l.Matplotlib.rounding_size=None pad=0.2) Old attrs simply are forgotten.3 pad=0. Alternatively. **kw) Set the box style.3 pad=0.3 370 Chapter 35. ACCEPTS: [ Class LArrow RArrow Round Round4 Roundtooth Sawtooth Square ] set_height(h) Set the width rectangle ACCEPTS: ﬂoat set_mutation_aspect(aspect) Set the aspect ratio of the bbox mutation.pad=0.3.tooth_size=None pad=0.h ACCEPTS: (left.0.b. width.w. boxstyle can be a string with boxstyle name with optional comma-separated attributes. height) set_boxstyle(boxstyle=None.tooth_size=None pad=0.

linestyle=None.Artist A patch is a 2D thingy with a face color and an edge color.transforms. linewidth. matplotlib. Release 1. facecolor=None. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.patches 371 . linewidth=None.Matplotlib. or None for default. If any of edgecolor. antialiased=None.0.figure. or None for default.1 ACCEPTS: ﬂoat set_y(y) Set the bottom coord of the rectangle ACCEPTS: ﬂoat class matplotlib. facecolor. hatch=None. 35.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|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.4. or antialiased are None.Bbox instance [True | False] [ (Path. 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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. ﬁll=True.Patch(edgecolor=None. or ‘none’ for no color a matplotlib. color=None.artist. or ‘none’ for no color mpl color spec. path_eﬀects=None. they default to their rc params setting.patches. **kwargs) Bases: matplotlib.

get_ls() Return the linestyle. get_antialiased() Returns True if the Patch is to be drawn with antialiasing. get_fill() return whether ﬁll is set get_hatch() Return the current hatching pattern get_linestyle() Return the linestyle. Will be one of [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] get_lw() Return the line width in points.Matplotlib. {} contains_point(point) Returns True if the given point is inside the path (transformed with its transform attribute).1 Returns T/F. get_edgecolor() Return the edge color of the Patch. matplotlib artists . draw(artist. get_extents() Return a Bbox object deﬁning the axis-aligned extents of the Patch.0. get_data_transform() get_ec() Return the edge color of the Patch. Release 1. get_patch_transform() get_path() Return the path of this patch get_path_effects() 372 Chapter 35. renderer. *args. get_fc() Return the face color of the Patch. fill return whether ﬁll 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. **kwargs) Draw the Patch to the given renderer. get_facecolor() Return the face color of the Patch.

the curves will be interpolated by line segments. set_edgecolor() For setting the edge or face color individually. Release 1. To access the curves as curves. ACCEPTS: matplotlib color spec See Also: set_facecolor(). get_window_extent(renderer=None) set_aa(aa) alias for set_antialiased set_alpha(alpha) Set the alpha tranparency of the patch. or ‘none’ for no color set_fc(color) alias for set_facecolor set_fill(b) Set whether to ﬁll the patch ACCEPTS: [True | False] set_hatch(hatch) Set the hatching pattern hatch can be one of: 35.Matplotlib.1 get_transform() Return the Transform applied to the Patch. or ‘none’ for no color set_facecolor(color) Set the patch face color ACCEPTS: mpl color spec.4. set_ec(color) alias for set_edgecolor set_edgecolor(color) Set the patch edge color ACCEPTS: mpl color spec. matplotlib. ACCEPTS: ﬂoat 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. or None for default.patches 373 . get_verts() Return a copy of the vertices used in this patch If the patch contains Bezier curves. or None for default.0. use get_path().

path. Release 1.0.Patch A general polycurve path patch.patches. it increases the density of hatching of that pattern. Hatching is supported in the PostScript. PDF. update_from(other) Updates this Patch from the properties of other. in which case all the speciﬁed hatchings are done. class matplotlib. SVG and Agg backends only. matplotlib artists . **kwargs) Bases: matplotlib.Path object. If same letter repeats.patches.PathPatch(path.Matplotlib. which should be a list of instances of matplotlib. path is a matplotlib.patheﬀect.1 / \ | + x o O . ACCEPTS: [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. * - diagonal hatching back diagonal vertical horizontal crossed crossed diagonal small circle large circle dots stars Letters can be combined._Base class or its derivatives. Valid kwargs are: 374 Chapter 35.’ | ‘*’ ] set_linestyle(ls) Set the patch linestyle ACCEPTS: [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] set_linewidth(w) Set the patch linewidth in points ACCEPTS: ﬂoat or None for default set_ls(ls) alias for set_linestyle set_lw(lw) alias for set_linewidth set_path_effects(path_eﬀects) set path_eﬀects.

Patch A general polygon patch. or ‘none’ for no color mpl color spec. closed=True. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Matplotlib.Bbox instance [True | False] [ (Path.transforms. Release 1.0. or None for default. xy is a numpy array with shape Nx2.figure.Polygon(xy. If closed is True.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.patches. or ‘none’ for no color a matplotlib. Valid kwargs are: 35. or None for default. matplotlib. the polygon will be closed so the starting and ending points are the same.patches 375 . **kwargs) Bases: matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib.patches.4.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.

’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Set/get the vertices of the polygon. y) with speciﬁed width and height. Release 1.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.transforms. or ‘none’ for no color a matplotlib. 376 Chapter 35.91. This property is provided for backward compatibility with matplotlib 0.Patch Draw a rectangle with lower left at xy = (x.0. height.patches. or None for default. or None for default. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.patches. width. class matplotlib. or ‘none’ for no color mpl color spec. **kwargs) Bases: matplotlib.Matplotlib.figure.Bbox instance [True | False] [ (Path.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.x only.Rectangle(xy. matplotlib artists . New code should use get_xy() and set_xy() instead.

or ‘none’ for no color mpl color spec.4.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|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. or None for default. or ‘none’ for no color a matplotlib.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.Matplotlib. or None for default.patches 377 .1 ﬁll is a boolean indicating whether to ﬁll 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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.Bbox instance [True | False] [ (Path. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.0.figure. Release 1.transforms. matplotlib.

RegularPolygon(xy. Constructor arguments: xy A length 2 tuple (x.b. radius The distance from the center to each of the vertices. width.patches. **kwargs) Bases: matplotlib.Matplotlib.h ACCEPTS: (left. bottom. orientation rotates the polygon (in radians). numVertices. 378 Chapter 35. Valid kwargs are: radius=5. height) set_height(h) Set the width rectangle ACCEPTS: ﬂoat set_width(w) Set the width rectangle ACCEPTS: ﬂoat set_x(x) Set the left coord of the rectangle ACCEPTS: ﬂoat 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: ﬂoat xy Return the left and bottom coords of the rectangle class matplotlib. orientation=0.0. numVertices the number of vertices. Release 1.w.Patch A regular polygon patch. matplotlib artists .patches. 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.

If None.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.4. props=None.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.patches. oy.patches.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib. the shadow will have have the same color as the face. ox. oy. matplotlib.Matplotlib. **kwargs) Bases: matplotlib. or None for default. or ‘none’ for no color mpl color spec. is a patch property update dictionary.transforms. or ‘none’ for no color a matplotlib.Patch Create a shadow of the given patch oﬀset by ox.Shadow(patch.figure. Release 1.0. or None for default. but darkened.patches 379 . kwargs are 35. props. if not None.Bbox instance [True | False] [ (Path.

Wedge(center.0.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. r. or None for default.figure. Release 1. y center with radius r that sweeps theta1 to theta2 (in degrees). or ‘none’ for no color mpl color spec. or None for default.Matplotlib.transforms.Patch Wedge shaped patch. theta2. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. width=None.patches. theta1. Valid kwargs are: 380 Chapter 35. matplotlib artists . Draw a wedge centered at x. then a partial wedge is drawn from inner radius r . or ‘none’ for no color a matplotlib.Bbox instance [True | False] [ (Path. **kwargs) Bases: matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib.width to outer radius r. If width is given.patches.

’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number class matplotlib. or ‘none’ for no color a matplotlib.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. y) location of arrow tip xybase (x. **kwargs) Bases: matplotlib. frac=0. xybase.4.YAArrow(ﬁgure.patches. This is an arrow that is deﬁned in display space and has a tip at x1.patches 381 . Release 1.10000000000000001.Bbox instance [True | False] [ (Path. or None for default. xytip. y2. or None for default.Patch Yet another arrow class. y) location the arrow base mid point ﬁgure The Figure instance (ﬁg. matplotlib.Matplotlib.0. width=4. or ‘none’ for no color mpl color spec.patches.transforms.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.figure. Constructor arguments: xytip (x. y1 and a base at x2. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. headwidth=12.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.

or None for default. renderer. color=’k’. y2) return the points on the line that is perpendicular to the line and intersects (x2. or ‘none’ for no color mpl color spec. y1.patches. y2) and the distance from (x2.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. or None for default.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 382 Chapter 35. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.0. y1) and (x2. to test whether the artist is returning the correct bbox.transforms.bbox_artist(artist. matplotlib. y2) of the returned points is k. ﬁll=True) This is a debug function to draw a rectangle around the bounding box returned by get_window_extent() of an artist. props=None. y2. trans=None) This is a debug function to draw a rectangle around the bounding box returned by get_window_extent() of an artist.Bbox instance [True | False] [ (Path. matplotlib artists . k) For line segment deﬁned by (x1. to test whether the artist is returning the correct bbox. Release 1.Matplotlib. props is a dict of rectangle props with the additional property ‘pad’ that sets the padding around the bbox in points.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. renderer.patches.draw_bbox(bbox. Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.figure. x2. matplotlib. or ‘none’ for no color a matplotlib.

is a dictionary of line properties (see matplotlib.Line2D) for the arrow that connects annotation to the point. 35. ie.5.text.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.lines. Otherwise. defaults to xycoords).text 383 . If d is the distance between the text and annotated point. Release 1. shrink will shorten the arrow so the tip and base are shink percent of the distance d away from the endpoints.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.text.Text. If the dictionary has a key arrowstyle.0. class matplotlib. any key for matplotlib. y location xytext. xy.text. defaults to xy. y point xy with text s at x. Axes. 0. etc. easier. textcoords=None. and if textcoords = None.text Classes for including text in a ﬁgure. **kwargs) Bases: matplotlib. shrink=0. a FancyArrowPatch instance is created with the given dictionary and is drawn. Rectangle. arrowprops.Annotation(s. xycoords=’data’.5. matplotlib._AnnotationBase A Text class to make annotating things in the ﬁgure. a YAArow patch instance is created and drawn. annotation_clip=None. if not None. matplotlib.05 is 5% any key for matplotlib. xytext=None.Matplotlib.5 matplotlib..1 35.patches. 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 xytext = None.patches. arrowprops=None. such as Figure. Annotate the x.PathPatch xycoords and textcoords are strings that indicate the coordinates of xy and xytext.

Matplotlib. r for the annotation. which behave as True only if xycoords is”data”. Release 1. the annotation will only be drawn when the xy is inside the axes. See Annotating Axes for more details. Transform) | Patch | None ] 384 Chapter 35. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system. If False. If a ‘points’ or ‘pixels’ option is speciﬁed.1 is upper right use the coordinate system of the object being annotated (default) Specify an oﬀset (in points) from the xy value you can specify theta.1 is upper.-5).Bbox instance [True | False] [ (Path.0 is lower left of ﬁgure and 1. xycoords=’axes points’ You may use an instance of Transform or Artist.1 Property ‘ﬁgure points’ ‘ﬁgure pixels’ ‘ﬁgure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘oﬀset points’ ‘polar’ Description points from the lower left corner of the ﬁgure pixels from the lower left corner of the ﬁgure 0. even in cartesian plots. matplotlib artists . the annotation will always be drawn regardless of its position. values will be added to the bottom-left and if negative. Eg: # 10 points to the right of the left border of the axes and # 5 points below the top border xy=(10. The annotation_clip attribute contols the visibility of the annotation when it goes outside the axes area. right points from lower left corner of axes pixels from lower left corner of axes 0. Note that if you are using a polar axes.0.transforms.1 is lower left of axes and 1. The default is None. If True.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. Additional kwargs are Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path Description unknown ﬂoat (0. values will be subtracted from the top-right.0 transparent through 1.

**kwargs) Draw the Annotation object to the given renderer. *args.text 385 .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. Release 1.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.1 Table 35. 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’ | ﬂoat ﬂoat any number contains(event) draw(artist.Matplotlib.figure.0. update_positions(renderer) Update the pixel positions of the annotated point and the text. This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox.Figure instance a matplotlib.font_manager. renderer.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. set_figure(ﬁg) update_bbox_position_size(renderer) Update the location and the size of the bbox. matplotlib. 35.5.

font_manager. ref_coord. horizontalalignment=’left’.Artist Handle storing and drawing of text in window or data coordinates.artist.OffsetFrom(artist.text.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.FT2Font() FT2Font class matplotlib. Release 1. rotation_mode=None.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.Bbox instance [True | False] [ (Path.0 transparent through 1. 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 ﬂoat (0. text=’‘. matplotlib artists .Text(x=0. verticalalignment=’baseline’. y=0. y with string text. Create a Text instance at x.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. path_eﬀects=None. rotation=None.0.Matplotlib.1 matplotlib. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. **kwargs) Bases: matplotlib. linespacing=None.figure. unit=’points’) Bases: object get_unit() set_unit(unit) class matplotlib. color=None.text.transforms.Figure instance a matplotlib.text. fontproperties=None. multialignment=None.

**kwargs) Draws the Text object to the given renderer. Returns None if the the FancyBboxPatch is not made. a hit is true anywhere in the axis-aligned bounding-box containing the text.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. Returns True or False. In the case of text.5. 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. get_bbox_patch() Return the bbox Patch object.text 387 . matplotlib. *args. 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’ | ﬂoat ﬂoat any number contains(mouseevent) Test whether the mouse event occurred in the patch. draw(artist.Matplotlib.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. Release 1.0.

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. matplotlib artists .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. ‘center’. Not intended to be human readable. get_rotation() return the text angle as ﬂoat 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’. get_name() Return the font name as string get_path_effects() get_position() Return the position of the text as a tuple (x. Release 1.Matplotlib. 388 Chapter 35. y) get_prop_tup() Return a hashable tuple of properties.0. ‘center’ or ‘right’. Will be one of ‘left’.

The mutation scale of the FancyBboxPath is set to the fontsize. alpha=0.Matplotlib. A FancyBboxPatch is initialized with rectprops and will be drawn.0. the renderer dpi is irrelevant. ACCEPTS: [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] 35.1 get_weight() Get the font weight as string or number get_window_extent(renderer=None. alpha=0. The ﬂag indicates if the given string s contains any mathtext. t. set_backgroundcolor(color) Set the background color of the text by updating the bbox. For the web application. it is simpler to call the method after saving the ﬁgure. matplotlib. Each string may be either a real font name or a generic font class name. dpi=None) Return a Bbox object bounding the text. determined by counting unescaped dollar signs. this is useful for specifying clickable regions in a png ﬁle on a web page.dpi.set_bbox(dict(facecolor=’red’. May be either a single string. then the value that was used must be speciﬁed as the dpi argument. If usetex is on. static is_math_text(s) Returns a cleaned string and a boolean ﬂag. if ﬁgure. rectprops are any settable properties for a rectangle. or a list of strings in decreasing priority.5. If the latter. the speciﬁc font names will be looked up in the matplotlibrc ﬁle. See Also: set_bbox() To change the position of the bounding box.dpi is not the value used when saving the ﬁgure. ACCEPTS: any matplotlib color set_bbox(rectprops) Draw a bounding box around self. 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. If no mathtext is present. renderer defaults to the _renderer attribute of the text object.5.5)) If rectprops has “boxstyle” key. eg facecolor=’red’.text 389 .ﬁgure. the ﬂag always has the value “TeX”. the cleaned string has its dollar signs unescaped. For getting web page regions. In addition to being used internally. so you must use this kwarg if you want to call get_window_extent() prior to the ﬁrst draw(). Release 1. This is not assigned until the ﬁrst execution of draw(). dpi defaults to self. in display units.

The layout of the bounding box of all the lines is determined bu the horizontalalignment and verticalalignment properties.0.font_manager.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. Release 1.2. matplotlib artists . but the multiline text within that box can be ACCEPTS: [’left’ | ‘right’ | ‘center’ ] set_name(fontname) alias for set_family set_path_effects(path_eﬀects) set_position(xy) Set the (x. fp must be a ACCEPTS: a matplotlib.FontProperties object. Default is 1.Matplotlib. ACCEPTS: ﬂoat (multiple of font size) set_ma(align) alias for set_verticalalignment set_multialignment(align) Set the alignment for multiple lines layout. y) position of the text 390 Chapter 35.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.font_manager. text.

matplotlib. May be either a size string. or an absolute font size in points. ACCEPTS: [ ‘normal’ | ‘italic’ | ‘oblique’] set_text(s) Set the text string s It may contain newlines (\n) or math in LaTeX syntax. If None (default). ACCEPTS: [ ‘normal’ | ‘small-caps’ ] set_verticalalignment(align) Set the vertical alignment ACCEPTS: [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] set_weight(weight) Set the font weight. and then will be rotated with the alignement reference point as a origin. either ‘normal’ or ‘small-caps’. 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. set_size(fontsize) Set the font size. Release 1. the text will be rotated ﬁrst then will be aligned.Matplotlib. ACCEPTS: string or anything printable with ‘%s’ conversion. the un-rotated text will ﬁrst aligned according to their ha and va. relative to the default font size.text 391 .y) set_rotation(s) Set the rotation of the text ACCEPTS: [ angle in degrees | ‘vertical’ | ‘horizontal’ ] set_rotation_mode(m) set text rotation mode.1 ACCEPTS: (x. set_va(align) alias for set_verticalalignment set_variant(variant) Set the font variant.0. If “anchor”. 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).5. ACCEPTS: [ a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ] 35.

as obtained by get_window_extent(). dashlength=0. (default = 0). in turn. where 0 draws the dash after the text and 1 before. in canvas units. verticalalignment) are ignored.0. multialignment=None. This. y=0. horizontalalignment=’center’. rotation=None. The dash always comes between the point speciﬁed by set_position() and the text. appears to depend on the font metrics as given by the rendering backend. Hence the quality of the “centering” of the label text with respect to the dash varies depending on the backend used. This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox.text. the dash takes its rotation from the text’s rotation). dashlength is the length of the dash in canvas units.Text This is basically a Text with a dash (drawn with a Line2D) before/after it. dashdirection is one of 0 or 1. 392 Chapter 35. dashpush=0) Bases: matplotlib. draw(renderer) Draw the TextWithDash object to the given renderer. the text alignment arguments (horizontalalignment. fontproperties=None.0. It is intended to be a drop-in replacement for Text. dashrotation=None. (default = 0) Note: The alignment of the two objects is based on the bounding box of the Text.text. and should generally stay None. (default = None) dashpad is a padding length to add (or subtract) space between the text and the dash. matplotlib artists . text=’‘.Matplotlib.TextWithDash(x=0. Note: I’m not sure that I got the get_window_extent() right. or whether that’s suﬃcient for providing the object bounding box. When a dash exists.0). dashdirection=0. color=None. update_from(other) Copy properties from other to self class matplotlib. Because the text center is projected onto the dash. In this case get_dashrotation() returns get_rotation(). dashrotation speciﬁes the rotation of the dash. verticalalignment=’center’. (I. Release 1. linespacing=None. major deviations in the rotation cause what may be considered visually unappealing results.. (default = 3) dashpush “pushes” the dash and text away from the point speciﬁed by set_position() by the amount in canvas units.1 set_x(x) Set the x position of the text ACCEPTS: ﬂoat set_y(y) Set the y position of the text ACCEPTS: ﬂoat update_bbox_position_size(renderer) Update the location and the size of the bbox.e. (default = 0. dashpad=3.0. and should behave identically to it when dashlength = 0.

0 is after) set_dashlength(dl) Set the length of the dash. The default is 0. ACCEPTS: ﬂoat (canvas units) set_dashpad(dp) Set the “pad” of the TextWithDash. so you must use this kwarg if you want to call get_window_extent() prior to the ﬁrst draw().0. For getting web page regions. it is simpler to call the method after saving the ﬁgure. get_dashlength() Get the length of the dash.Matplotlib. 1 is before the text and 0 is after. set_dashdirection(dd) Set the direction of the dash following the text. but useful for backends who want to cache derived information about text (eg layouts) and need to know if the text has changed. which is the extra spacing between the dash and the text. in canvas units. ACCEPTS: int (1 is before. Not intended to be human readable. Release 1. get_dashpad() Get the extra spacing between the dash and the text.5. 1 is before the text and 0 is after.text 393 .1 get_dashdirection() Get the direction dash. In addition to being used internally. y) get_prop_tup() Return a hashable tuple of properties. in canvas units. get_figure() return the ﬁgure instance the artist belongs to get_position() Return the position of the text as a tuple (x. get_window_extent(renderer=None) Return a Bbox object bounding the text. which is what you’d want for the typical case of ticks below and on the left of the ﬁgure. ACCEPTS: ﬂoat (canvas units) 35. matplotlib. get_dashrotation() Get the rotation of the dash in degrees. This is not assigned until the ﬁrst execution of draw(). get_dashpush() Get the extra spacing between the dash and the speciﬁed text position. in display units. in canvas units. renderer defaults to the _renderer attribute of the text object. this is useful for specifying clickable regions in a png ﬁle on a web page.

Transform instance used by this artist.transforms.text. ACCEPTS: a matplotlib. in degrees ACCEPTS: ﬂoat (degrees) set_figure(ﬁg) Set the ﬁgure instance the artist belong to. Since the rotation is with respect to the actual canvas’s coordinates we need to map back and forth. ACCEPTS: (x. or a numeric value in degrees.0. y and the dashlength. matplotlib.Matplotlib. Release 1.get_rotation(rotation) Return the text angle as ﬂoat. rotation may be ‘horizontal’. matplotlib artists . ‘vertical’. ACCEPTS: a matplotlib.Figure instance set_position(xy) Set the (x. which is the extra spacing between the beginning of the dash and the speciﬁed position.Transform instance set_x(x) Set the x position of the TextWithDash. y) set_transform(t) Set the matplotlib. y coordinates for text based on the input x.1 set_dashpush(dp) Set the “push” of the TextWithDash. ACCEPTS: ﬂoat set_y(y) Set the y position of the TextWithDash.figure. ACCEPTS: ﬂoat update_coords(renderer) Computes the actual x.transforms. 394 Chapter 35. y) position of the TextWithDash. ACCEPTS: ﬂoat (canvas units) set_dashrotation(dr) Set the rotation of the dash.

label=’‘. 395 . detrend=mlab. **kwargs) Plot the autocorrelation of x..Artist The Axes contains most of the ﬁgure elements: Axis.axes class matplotlib. Polygon. normalize the data by the autocorrelation at 0-th lag. 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. acorr(x. If usevlines is True. the plot style is determined by the kwargs. frameon=True. The Axes instance supports callbacks through a callbacks attribute which is a CallbackRegistry instance. usevlines=True. maxlags=10. xscale=None. yscale=None. If normed = True. Data are plotted as plot(lags.1 matplotlib.artist. **kwargs) Bases: matplotlib. c. 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’. sharex=None. and sets the coordinate system.axes. maxlags is a positive integer detailing the number of lags to show. rect.correlate() with mode = 2. normed=True. sharey=None. The default value of None will return all 2imeslen(x) − 1 lags. c.detrend_none. which are Line2D properties. **kwargs) call signature: acorr(x. The cross correlation is performed with numpy. Otherwise.CHAPTER THIRTYSIX MATPLOTLIB AXES 36. Tick. axisbg=None. vlines() rather than plot() is used to draw vertical lines from the origin to the acorr. x is detrended by the detrend callable (default no normalization). etc. though these can be overridden with keyword args. Text.Axes(ﬁg. **kwargs) Return value is a tuple (lags. Line2D.

0. Example: xcorr() above.260 40 20 0 20 40 60 40 20 0 20 40 60 add_artist(a) Add any Artist to the axes.2060 1. autolim=True) Add a Collection instance to the axes.05 0.2 0. and acorr() below. matplotlib axes . linecol. Returns the artist.4 0. See Also: plot() or vlines() For documentation on valid kwargs.1 The return value is a tuple (lags.05 0.15 0. b) where •linecol is the LineCollection •b is the x-axis.Matplotlib. c. Returns the collection. add_collection(collection. Release 1.0 0.20 0.00 0.0 0.8 0. Example: 0. 396 Chapter 36.10 0.10 0.6 0.15 0.

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. arrowprops=None. the clipbox will be set to the Axes clipping box. add_patch(p) Add a Patch p to the list of axes patches. matplotlib. defaults to xycoords). If the dictionary has a key arrowstyle.lines. **kwargs) Keyword arguments: Annotate the x.Line2D) for the arrow that connects annotation to the point. if not None. y location xytext. ie. If d is the distance between the text and annotated point. a YAArow patch instance is created and drawn. xy. and if textcoords = None. Release 1.polygon ? Valid keys for FancyArrowPatch are 36. is a dictionary of line properties (see matplotlib. arrowprops. it will be set to transData.Matplotlib. Returns the patch.axes 397 . a FancyArrowPatch instance is created with the given dictionary and is drawn.1 add_line(line) Add a Line2D to the list of plot lines Returns the line. If the transform is not set. defaults to xy. y point xy with text s at x.1. add_table(tab) Add a Table instance to the list of axes tables Returns the table. xycoords=’data’. shrink will shorten the arrow so the tip and base are shink percent of the distance d away from the endpoints. annotate(*args. Otherwise.patches. textcoords=’data’. shrink=0.0. (If xytext = None. **kwargs) call signature: annotate(s.05 is 5% any key for matplotlib. xytext=None.

values will be added to the bottom-left and if negative. xycoords=’axes points’ You may use an instance of Transform or Artist. If True. Release 1. If False.1 is lower left of axes and 1. even in cartesian plots.PathPatch xycoords and textcoords are strings that indicate the coordinates of xy and xytext.1 is upper right use the coordinate system of the object being annotated (default) Specify an oﬀset (in points) from the xy value you can specify theta.5. 398 Chapter 36.1 Key arrowstyle connectionstyle relpos patchA patchB shrinkA shrinkB mutation_scale mutation_aspect ? Description the arrow style the connection style default is (0. Eg: # 10 points to the right of the left border of the axes and # 5 points below the top border xy=(10.-5). any key for matplotlib. right points from lower left corner of axes pixels from lower left corner of axes 0. the annotation will only be drawn when the xy is inside the axes. Property ‘ﬁgure points’ ‘ﬁgure pixels’ ‘ﬁgure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘oﬀset points’ ‘polar’ Description points from the lower left corner of the ﬁgure pixels from the lower left corner of the ﬁgure 0. Note that if you are using a polar axes.Matplotlib. The annotation_clip attribute contols the visibility of the annotation when it goes outside the axes area.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. values will be subtracted from the top-right. matplotlib axes . 0. the annotation will always be drawn regardless of its position.patches. r for the annotation. The default is None.0 is lower left of ﬁgure and 1.0. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system. See Annotating Axes for more details.1 is upper. If a ‘points’ or ‘pixels’ option is speciﬁed. which behave as True only if xycoords is”data”.

0 transparent through 1.font_manager.axes 399 . 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’ | ﬂoat ﬂoat 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. Release 1.0. matplotlib.Figure instance a matplotlib.figure.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 ﬂoat (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.1.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.transforms.Matplotlib.Bbox instance [True | False] [ (Path.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x. 36.

Matplotlib. matplotlib axes .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. Release 1.0.

or ‘none’ for no color mpl color spec. **kwargs) Draws arrow on speciﬁed axis from (x. matplotlib. or ‘none’ for no color a matplotlib. dx.0. dx. dy. Release 1. **kwargs) call signature: arrow(x. it performs the autoscaling on the speciﬁed axis or axes. y + dy). enable: [True | False | None] True (default) turns autoscaling on. axis=’both’.1 arrow(x. autoscale(enable=True. or None for default. dy. or None for default. y) to (x + dx. and then. axis: [’x’ | ‘y’ | ‘both’] which axis to operate on.figure. if autoscaling for either axis is on. tight=None) Convenience method for simple axis view autoscaling. default is ‘both’ Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. It turns autoscaling on or oﬀ.1.Bbox instance [True | False] [ (Path.Matplotlib. 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.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 36. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. False turns it oﬀ. None leaves the autoscaling state unchanged. y. y.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.axes 401 .transforms.

eg.Axes. Eg.axes. eg. otherwise treat tight as False.0 opaque) [True | False] [True | False] an Axes instance 402 Chapter 36. The tight setting is retained for future autoscaling until it is explicitly changed. xmax=0.75) Valid kwargs are Line2D properties. with the set_xlim() command. Return value is the Line2D instance.1 tight: [True | False | None] If True. this line will always span the horizontal extent of the axes. xmax=1.0=right but the y location is in data coordinates. With the default values of xmin = 0 and xmax = 1. autoscale_view(tight=None. regardless of the xlim settings. axhline(y=0.Matplotlib. if None. •draw a thick red hline at y = 0 that spans the xrange >>> axhline(linewidth=4.0 transparent through 1. and can be used to control the line properties. **kwargs) Axis Horizontal Line Draw a horizontal line at y from xmin to xmax.relim() prior to calling autoscale_view.. use tight scaling if the only artist is an image. the horizontal extent is in axes coords: 0=left. xmin=0. Release 1. xmin=0. matplotlib axes . Returns None. color=’r’) •draw a default hline at y = 1 that spans the xrange >>> axhline(y=1) •draw a default hline at y = . In that case. with the exception of ‘transform’: Property agg_filter alpha animated antialiased or aa axes Description unknown ﬂoat (0. set view limits to data limits. That is. xmax=1. scaley=True) Autoscale the view limits using the data limits. xmin=0.5=middle.5. let the locator and margins expand the view limits. kwargs are the same as kwargs to plot. 0.5 that spans the the middle half of the xrange >>> axhline(y=. use matplotlib. The autoscaling preserves any axis direction reversal that has already been done. if False. the xaxis by setting scaley to False. scalex=True. even if you change them. 1.25.0. **kwargs) call signature: axhline(y=0. The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. You can selectively autoscale only a single axis.

0. Release 1. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’. xmax=1.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind.transforms.axes 403 . stride) ﬂoat distance in points or callable pick function fn(artist.Bbox instance [True | False] [ (Path.1.’ | ’.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.Transform instance a url string [True | False] 1D array 1D array any number See Also: axhspan() for example plot and source code axhspan(ymin.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. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. **kwargs) call signature: 36.transforms. ymax. matplotlib.Matplotlib.figure. xmin=0.

**kwargs) Axis Horizontal Span.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.75 that spans the horizontal extent of the axes >>> axhspan(0. xmin=0.5=middle. Examples: •draw a gray rectangle from y = 0.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.25. or ‘none’ for no color mpl color spec. 0.patches. matplotlib axes .1 axhspan(ymin. or None for default.25-0. even if you change them.figure.0=right but the y location is in data coordinates. xmax=1. Return value is a matplotlib.75. alpha=0. 1.Polygon instance. the horizontal extent is in axes coords: 0=left.Matplotlib. 0.5’. y coords are in data units and x coords are in axes (relative 0-1) units. Release 1.Bbox instance [True | False] [ (Path.transforms. facecolor=’0.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number 404 Chapter 36. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. regardless of the xlim settings. with the set_xlim() command. or ‘none’ for no color a matplotlib. Draw a horizontal span (rectangle) from ymin to ymax. ymax. With the default values of xmin = 0 and xmax = 1. or None for default. That is. eg. this always spans the xrange.0.

Release 1.0 0. 1.5 1.0 1. Return value is the Line2D instance.5 2. With the default values of ymin = 0 and ymax = 1. regardless of the ylim settings. even if you change them. ymin=0. ymax=1. matplotlib.01. color=’r’) 36.0.5 1.0 0. That is.5 0. **kwargs) Convenience method for manipulating the x and y view limits and the aspect ratio of the plot.1 Example: 2.0 0.0 0. kwargs are the same as kwargs to plot. the vertical extent is in axes coords: 0=bottom. •draw a thick red vline at x = 0 that spans the yrange >>> axvline(linewidth=4..5 1.Matplotlib. 0. ymax=1. eg. Eg. **kwargs) call signature: axvline(x=0. and can be used to control the line properties. ymin=0.0=top but the x location is in data coordinates. this line will always span the vertical extent of the axes.axes 405 .5=middle. kwargs are passed on to set_xlim() and set_ylim() axvline(x=0.0 axis(*v.1. with the set_ylim() command.0 1. **kwargs) Axis Vertical Line Draw a vertical line at x from ymin to ymax.5 0.

0.5 that spans the the middle half of the yrange >>> axvline(x=. 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 ﬂoat (0.Transform instance 406 Chapter 36.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. stride) ﬂoat distance in points or callable pick function fn(artist. ymin=0. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x. ymax=0.1 •draw a default vline at x = 1 that spans the yrange >>> axvline(x=1) •draw a default vline at x = .transforms. matplotlib axes . Release 1. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.5.25.transforms.figure.’ | ’. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.0 transparent through 1.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind.Bbox instance [True | False] [ (Path.75) Valid kwargs are Line2D properties.Matplotlib.

Release 1. even if you change them. 1. with the set_ylim() command. With the default values of ymin = 0 and ymax = 1. ymax=1.0=top but the y location is in data coordinates. matplotlib. ymin=0.axes 407 . **kwargs) call signature: axvspan(xmin. Draw a vertical span (rectangle) from xmin to xmax.25 to 1.patches. 0. this always spans the yrange. ymin=0.5) Valid kwargs are Polygon properties: 36. eg. x coords are in data units and y coords are in axes (relative 0-1) units. ymax=1. alpha=0. the vertical extent is in axes coords: 0=bottom.55.Matplotlib.1. That is. Examples: •draw a vertical green translucent rectangle from x=1.25.Polygon instance.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. 1.0. facecolor=’g’. xmax.55 that spans the yrange of the axes >>> axvspan(1.5=middle. xmax. Return value is the matplotlib. **kwargs) Axis Vertical Span. regardless of the ylim settings.

Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. bottom=None. or ‘none’ for no color a matplotlib. **kwargs) Make a bar plot with rectangles bounded by: left. height.figure. **kwargs) call signature: bar(left. bottom.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. or ‘none’ for no color mpl color spec. bottom + height (left. height. bottom=0. width. bottom and top edges) left. or None for default.80000000000000004. height. left + width.transforms. and bottom can be either scalars or sequences Return value is a list of matplotlib. right.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number axhspan() for example plot and source code bar(left. Release 1. width=0.patches.Matplotlib.Bbox instance [True | False] [ (Path. matplotlib axes . width=0. Required arguments: 408 Chapter 36. or None for default.Rectangle instances.0.8.

will be used to generate errorbars on the bar chart ecolor speciﬁes 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. The optional arguments color. and yerr can be either scalars or sequences of length equal to the number of bars. This enables you to use bar as the basis for stacked bar charts. will be used to generate errorbars on the bar chart yerr if not None. matplotlib. linewidth.Matplotlib. Other optional kwargs: 36. align = ‘edge’ aligns bars by their left edges in left. ecolor and capsize ror_kw may be speciﬁed here rather than as independent kwargs. so they can also have shape 2xN for independent speciﬁcation of lower and upper errors.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.axes 409 . None means use default linewidth. align = ‘edge’ aligns bars by their bottom edges in bottom.the colors of the bar edges color linewidthwidth of bar edges. edgecolor.1. while align = ‘center’ interprets these values as the y coordinates of the bar centers. align ‘edge’ (default) | ‘center’ orien. 0 means don’t draw edges. Detail: xerr and yerr are passed directly to errorbar(). while align = ‘center’ interprets these values as the x coordinates of the bar centers. For horizontal bars. xerr if not None.‘vertical’ | ‘horizontal’ tation log [False|True] False (default) leaves the orientation axis as-is. Release 1. True sets it to log scale For vertical bars. or candlestick plots.0. xerr.

**kw) Arguments: X. V. see pivot kwarg) U. If X and Y are absent. V. 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 Description unknown ﬂoat 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’ | ‘. call signatures: barb(U. **kw) Plot a 2-D ﬁeld of barbs. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. Y. **kw) U.figure. Release 1. or ‘none’ for no color mpl color spec. or ‘none’ for no color a matplotlib. matplotlib axes . they will be 410 Chapter 36. barb(X. **kw) U. C.transforms.Bbox instance [True | False] [ (Path. Y.Matplotlib. 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. V. Y: The x and y coordinates of the barb locations (default is head of barb. or None for default.0. barbs(*args.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Example: A stacked bar chart. V. barb(X. **kw) C. barb(U.

Default is 9 pivot: [ ‘tip’ | ‘middle’ ] The part of the arrow that is at the grid point.1. Default is ‘tip’ barbcolor: [ color | color sequence ] Speciﬁes the color all parts of the barb except any ﬂags. This parameter is analagous to the facecolor parameter for polygons. If this is not set (and C has not either) then ﬂagcolor will be set to match barbcolor so that the barb has a uniform color. If C has been set. Only those values one wishes to override need to be included.meshgrid(). and if len(X) and len(Y) match the column and row dimensions of U.axes 411 .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. the arrow rotates about this point. C may be masked arrays. the other parts of the barb are scaled against this. U. which can be used instead. Y are not supported at present. However this parameter will override facecolor. V. If U and V are 2-D arrays but X and Y are 1-D. but masked X. which can be used instead. This parameter is analagous to the edgecolor parameter for polygons. These 36. hence the name pivot. ﬂagcolor: [ color | color sequence ] Speciﬁes the color of any ﬂags on the barb.Matplotlib. ﬂagcolor has no eﬀect. Keyword arguments: length: Length of the barb in points. sizes: A dictionary of coeﬃcients specifying the ratio of a given feature to the length of the barb.0. However this parameter will override facecolor. Release 1. then X and Y will be expanded with numpy. matplotlib.

the barbs give more quantitative information about the vector magnitude by putting slanted lines or a triangle for various increments in magnitude.half barbs (Default is 5) • ‘full’ . and 5. of course. Default is True barb_increments: A dictionary of increments specifying values to associate with different parts of the barb.full barbs (Default is 10) • ‘ﬂag’ .radius of the circle used for low magnitudes ﬁll_empty: A ﬂag on whether the empty barbs (circles) that are drawn should be ﬁlled with the ﬂag color. If the magnitude is small and only needs a single half-line and no full lines or triangles.1 features include: • ‘spacing’ .ﬂags (default is 50) ﬂip_barb: Either a single boolean ﬂag or an array of booleans.Matplotlib.space between features (ﬂags. After those come full lines (barbs). the magnitude is simply truncated to the next lowest multiple.0. ever at most 1 half line. the magnitude is rounded to the nearest multiple of the half-barb increment. 10. twice the width of a full barb • ‘emptybarb’ . If they are not ﬁlled.) Default is False Barbs are traditionally used in meteorology as a way to plot the speed and direction of wind observations. which give vector magnitude by the length of the arrow.width of a ﬂag. There is only. Only those values one wishes to override need to be included. 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. If False. The magnitude for the barb shown above would nominally be 65. As opposed to arrows. full/half barbs) • ‘height’ . they will be drawn such that no color is applied to the center. the half-line is oﬀset from the end of the barb so that it can be easily distinguished from barbs with a single full line. Default is False rounding: A ﬂag to indicate whether the vector magnitude should be rounded when allocating barb components. If True. An array (which should be the same size as the other data arrays) indicates whether to ﬂip for each individual barb. The smallest increment is a half line. Release 1. matplotlib axes . 412 Chapter 36. but can technically be used to plot any two dimensional vector quantity. Single boolean indicates whether the lines and ﬂags should point opposite to normal for all barbs. as show schematically below: : /\ \ : / \ \ : / \ \ \ : / \ \ \ : ------------------------------ The largest increment is given by a triangle (or “ﬂag”). • ‘half’ .height (distance from shaft to top) of a ﬂag or full barb • ‘width’ . using the standard increments of 50.

Bbox instance [True | False] [ (Path.figure.Matplotlib.8.transforms. **kwargs) Make a horizontal bar plot with rectangles bounded by: 36.1 linewidths and edgecolors can be used to customize the barb.0. ‘dotted’ | (oﬀset. left=0. 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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats 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.axes 413 . ‘dashdot’. left=None.Figure instance an id string any string [’solid’ | ‘dashed’. width.1.80000000000000004. height=0. on-oﬀ-dash-seq) ] ﬂoat or sequence of ﬂoats [True | False] unknown ﬂoat or sequence of ﬂoats unknown [None|ﬂoat|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number Example: barh(bottom. **kwargs) call signature: barh(bottom. height=0. width. matplotlib. Release 1.

1 6 2. width.0 2 0. and left can be either scalars or sequences Return value is a list of matplotlib.5 4 1. right.0 6 6 4 2 0 2 4 6 1.0 1.Matplotlib.5 2 1.5 2 0 0.5 4 3 2 1 0 1 2 1. Release 1.0. 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.0 0.5 0 0.0 4 0.5 6 1. matplotlib axes . bottom and top edges) bottom.patches.0 2 0.5 4 1. bottom + height (left.0 4 6 6 4 2 0 2 4 6 1. height.Rectangle instances. bottom.5 4 3 2 1 0 1 2 left. left + width.

Matplotlib. 36.5 1.1.5 1. This enables you to use barh as the basis for stacked bar charts.0 1. while align = ‘center’ interprets these values as the y coordinates of the bar centers.axes 415 . xerr. Release 1.0 0. if not None. 0 means don’t draw edges. The optional arguments color.0.0 1.1 2. matplotlib.0 0.5 0. linewidth. or candlestick plots. and yerr can be either scalars or sequences of length equal to the number of bars. will be used to generate errorbars on the bar chart if not None. will be used to generate errorbars on the bar chart speciﬁes 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. True sets it to log scale Setting align = ‘edge’ aligns bars by their bottom edges in bottom. None means use default linewidth.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. edgecolor.

bootstrap=None) call signature: boxplot(x. or ‘none’ for no color a matplotlib. notch=0. notch=0.transforms. widths=None. •notch = 0 (default) produces a rectangular box plot. The whiskers extend from the box to show the range of the data.5. x is an array or a sequence of vectors. 416 Chapter 36.5.0. whis=1. or None for default. Flier points are those past the end of the whiskers. patch_artist=False) Make a box and whisker plot for each column of x or each vector in sequence x. with a line at the median.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. vert=1. positions=None. or None for default. The box extends from the lower to upper quartile values of the data. boxplot(x. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. •notch = 1 will produce a notched box plot sym (default ‘b+’) is the default symbol for ﬂier points.Bbox instance [True | False] [ (Path. Release 1. matplotlib axes . or ‘none’ for no color mpl color spec. sym=’b+’. vert=1. sym=’+’. whis=1. patch_artist=False. widths=None.Matplotlib. Enter an empty string (‘’) if you don’t want to show ﬂiers.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number positions=None.figure.

.Bbox instance [True | False] Continued on next page 417 36.5.. and Kendall and Stuart.15*(distance between extreme positions) if that is smaller. 1967). This seems goofy. and notches are calculated using a Gaussian-based asymptotic approximation (see McGill.. R. xranges.lines. They extend to the most extreme data point within ( whis*(75%-25%) ) data range.Line2D instances created. J. yrange... whis (default 1. Otherwise.A.BrokenBarHCollection properties: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on Description unknown ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib. W. The ticks and limits are automatically set to match the positions. **kwargs) call signature: broken_barh(self.. bootstrap (default None) speciﬁes whether to bootstrap the conﬁdence intervals around the median for notched boxplots. Required arguments: Argument xranges yrange Description sequence of (xmin. Example: broken_barh(xranges.1 •vert = 1 (default) makes the boxes vertical. but that’s how MATLAB did it. •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. ywidth) kwargs are matplotlib. bootstrap speciﬁes the number of times to bootstrap the median to determine it’s 95% conﬁdence intervals. matplotlib. widths is either a scalar or a vector and sets the width of each box. Values between 1000 and 10000 are recommended. xwidth) sequence of (ymin. The default is 0. or 0.transforms. positions (default 1.n) sets the horizontal positions of the boxes. •vert = 0 makes horizontal boxes. 1978. Tukey.0.5) deﬁnes the length of the whiskers as a function of the inner quartile range.W.collections. and Larsen.Matplotlib.2. no bootstrapping is performed.1. If bootstrap==None.. yrange. **kwargs) A collection of horizontal bars spanning yrange with a sequence of xranges. Release 1.axes .

1 Table 36. ‘dashdot’. **kwargs) adds labels to line contours in cs. ‘dotted’ | (oﬀset.figure.Matplotlib. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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. ie: facecolors = (’black’.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. ’red’. ie: facecolors = ’black’ or a sequence of arguments for the various bars. **kwargs) call signature: clabel(cs. *args. matplotlib axes . where cs is a ContourSet object returned by contour. 418 Chapter 36.5 – continued from previous page clip_path [ (Path. Release 1. 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. ’green’) Example: can_zoom() Return True if this axes support the zoom box cla() Clear the current axes clabel(CS.0.

Matplotlib. v. Release 1.html colors: • if None. less so for labels on curved contours. Defaults to 5.1. Optional keyword arguments: fontsize: See http://matplotlib. matplotlib.3f’ Alternatively. e. colors = ‘r’ or colors = ‘red’. diﬀerent labels will be plotted in diﬀerent colors in the order speciﬁed inline: controls whether the underlying contour is removed or not. rgb.net/fonts.g. **kwargs) only labels contours listed in v. ﬂoat. all labels will be plotted in this color • if a tuple of matplotlib color args (string.axes 419 . the color of each label matches the color of the corresponding contour • if one string color. this can be a dictionary matching contour levels with arbitrary strings to use for each contour level 36.0.1 200 150 100 50 0 50 100 1 clabel(cs. Default is ‘%1. inline_spacing: space in pixels to leave on each side of label when placing inline. fmt: a format string for the label. This spacing will be exact for labels at locations where the contour is straight. etc).sf. Default is True.

ClabelText class (instead of matplotlib.. detrend=<function detrend_none at 0x3a1c668>. Alternatively. label rotations will always be plus or minus 90 degrees from level. NFFT=256. ClabelText recalculates rotation angles of texts during the drawing time. and any other key will select a label location).Text) is used to create labels.Matplotlib. pad_to=None. window=<function window_hanning at 0x3a178c0>.1 200 150 100 50 0 50 100 (i. therefore this can be used if aspect of the axes changes. Click the ﬁrst button near a contour to add a label. sides=’default’. The third button can be used to remove the last label added. the keyboard can be used to select label locations (enter to end label placement. clear() clear the axes cohere(x. Release 1. fmt[level]=string) manual: if True. use_clabeltext: if True (default is False).e. y.0. noverlap=0. click the second button (or potentially both mouse buttons at once) to ﬁnish adding labels. matplotlib axes . Fs=2. **kwargs) call signature: 1 420 Chapter 36. scale_by_freq=None. contour labels will be placed manually using mouse clicks. delete or backspace act like the third mouse button. but only if labels are not inline. Fc=0. rightside_up: if True (default).

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 eﬃcient. 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 ﬀt-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 deﬁnes 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 diﬀerent from NFFT, which speciﬁes 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 ﬀt(). The default is None, which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes 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 Speciﬁes 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 oﬀsets the x extents of the plot to reﬂect the frequency range used when a signal is acquired and then ﬁltered 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 ﬂoat (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/oﬀ 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 ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’,’ | ’.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind, stride) ﬂoat distance in points or callable pick function fn(artist, event) ﬂoat 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 notiﬁed 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 deﬁned by the its patch). A pixel coordinate is required. contour(*args, **kwargs) contour() and contourf() draw contour lines and ﬁlled contours, respectively. Except as noted, function signatures and return values are the same for both versions. contourf() diﬀers 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 speciﬁed in sequence V
**

contourf(..., V)

**ﬁll 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 ﬁlled 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 speciﬁed 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, ﬂoat, rgb, etc), diﬀerent levels will be plotted in diﬀerent colors in the order speciﬁed. alpha: ﬂoat 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 ﬂoating 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 ﬁrst 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 speciﬁed 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 speciﬁed 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, diﬀerent levels will be plotted with diﬀerent linewidths in the order speciﬁed 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 speciﬁed 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 ﬁlls intervals that are closed at the top; that is, for boundaries z1 and z2, the ﬁlled 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 ﬁlled contours, respectively. Except as noted, function signatures and return values are the same for both versions. contourf() diﬀers 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 speciﬁed in sequence V
**

contourf(..., V)

**ﬁll 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 ﬁlled 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 speciﬁed 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, ﬂoat, rgb, etc), diﬀerent levels will be plotted in diﬀerent colors in the order speciﬁed. alpha: ﬂoat 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 ﬂoating 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 ﬁrst 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 speciﬁed 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 speciﬁed 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, diﬀerent levels will be plotted with diﬀerent linewidths in the order speciﬁed 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 speciﬁed 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 ﬁlls intervals that are closed at the top; that is, for boundaries z1 and z2, the ﬁlled 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 eﬃcient. 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 ﬀt-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 deﬁnes 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 diﬀerent from NFFT, which speciﬁes 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 ﬀt(). The default is None, which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes 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 Speciﬁes 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 oﬀsets the x extents of the plot to reﬂect the frequency range used when a signal is acquired and then ﬁltered 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 ﬂoat (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/oﬀ 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

’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind. Note: Intended to be overridden by new projection types. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. y) Called when the mouse moves during a pan operation. key. **kwargs) Draw everything (plot lines.axes 439 .transforms. Release 1. renderer. labels) 36. button is the mouse button number: •1: LEFT •2: MIDDLE •3: RIGHT key is a “shift” key x.Transform instance a url string [True | False] 1D array 1D array any number Example: disconnect(cid) disconnect from the Axes event. x.1. y are the mouse coordinates in display coords. draw(artist. axes.’ | ’. drag_pan(button. stride) ﬂoat distance in points or callable pick function fn(artist.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.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 [ ’-’ | ’--’ | ’-.0. matplotlib.Matplotlib. *args.

lolims=False.Matplotlib. y. yerr=None. **kwargs) call signature: errorbar(x. Horizontal errorbars are plotted if xerr is not None. Optional keyword arguments: 440 Chapter 36.) Note: Intended to be overridden by new projection types.6 1. errorbar(x. fmt=’-’. barsabove=False. and yerr can all be scalars. ecolor=None. capsize=3. It is used to eﬃciently update Axes data (axis ticks. xuplims=False.0. elinewidth=None. xerr=None. xlolims=False. Release 1. xerr.2 verbosity coefficient 0.8 draw_artist(a) This method can only be used after an initial draw which caches the renderer. barsabove=False. labels.0 0. xuplims=False) Plot x versus y with error deltas in yerr and xerr.6 0. y. x. uplims=False.2 1. y. capsize=3. y. xerr=None. etc are not updated) end_pan() Called when a pan operation completes (when the mouse button is up. elinewidth=None. matplotlib axes . fmt=’-‘. Vertical errorbars are plotted if yerr is not None. lolims=False. xlolims=False. yerr=None. uplims=False. which plots a single error bar at x. ecolor=None.1 Nonsense (3 masked regions) 2 sentence length anomaly 1 0 1 2 33 2 1 0 1 2 word length anomaly 1.

or 2xN array-like ] If a scalar number. matplotlib. use the marker color.0. If a sequence of shape 2xN. In that case a caret symbol is used to indicate this.0 1.0 0.axes 441 . elinewidth: scalar the linewidth of the errorbar lines. errorbars are drawn +/. lims-arguments may be of the same type as xerr and yerr.0 0. This is used for adding errorbars to a bar plot.5 xerr/yerr: [ scalar | N. for example.5 0.0 -0. ecolor: [ None | mpl color ] a matplotlib color arg which gives the color the errorbar lines. only the errorbars are plotted.5 1. Release 1. or an Nx1 array-like object.Matplotlib.value. will plot the errorbars above the plot symbols.0 1. Default is below. errorbars are drawn at -row1 and +row2 fmt: ‘-‘ The plot format symbol. capsize: scalar the size of the error bar caps in points barsabove: [ True | False ] if True. len(N) array-like object. Nx1.1. All other keyword arguments are passed on to the plot command for the markers. For example. If fmt is None.5 -1. 0 1.1 Listed colors (3 masked regions) 2 1 0 1 2 33 2 1 0 1 2 0.0 0. If None. if None.5 0. lolims/uplims/xlolims/xuplims: [ False | True ] These arguments can be used to indicate that a value gives only upper/lower limits. this code makes big red squares with thick green edges: 36.5 -1. use the linewidth.

5 2.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.yerr = rand(3. ms=20. Release 1. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] 442 Chapter 36.50 0 -0.0 transparent through 1. marker=’s’.0.0 0.0 x.0 3 2 1 0 1 2 0. markerfacecolor.0 1.transforms. mec.000 0.00 0 00 -1.0 0. mec=’green’. y.Bbox instance [True | False] [ (Path.500 0 1. mew=4) where mfc. yerr.Matplotlib.5 0. markersize and markeredgewith. ms and mew are aliases for the longer property names. matplotlib axes .1 Simplest default with labels 1. markeredgecolor.50 1.y. 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 ﬂoat (0.10) errorbar(x.5 1. mfc=’red’.5 1.

Release 1.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.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/oﬀ ink in points 2D array (rows are x.figure.1. **kwargs) call signature: fill(*args.axes 443 . y pairs with an optional color format string.Matplotlib. **kwargs) Plot ﬁlled polygons. stride) ﬂoat distance in points or callable pick function fn(artist. For example. args is a variable length argument. matplotlib. barlinecols): plotline: Line2D instance x.transforms.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind. 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. allowing for multiple x. see plot() for details on the argument parsing.Transform instance a url string [True | False] 1D array 1D array any number Returns (plotline. Example: fill(*args. to 36.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. caplines. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.’ | ’.0.

000 1.5 2.000 negative contours dashed 1.y. shade a region between 0 and y along x.5 1.0 3 2 -0.0 0. Release 1.500 1.0 00 0. y. ’b’ ) An arbitrary number of x.0 1.5 00 -1. kwargs control the Polygon properties: 444 Chapter 36.: ax.0. The same color strings that plot() supports are supported by the ﬁll format string.00 0 1 0 1 2 plot a polygon with vertices at x.0 0.5 1. color groups can be speciﬁed: ax.1 Single color -0.500 0. y1. ’r’) Return value is a list of Patch instances that were added.Matplotlib.5 0. If you would like to ﬁll below a curve. ’g’. x2. y in blue. matplotlib axes . eg. use fill_between() The closed kwarg will close the polygon when True (default).fill(x1. y2.fill(x.

000 1.5 2.0.500 0.5 1.0 1.500 1.0 00 0.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] 445 .0 3 2 -0. or ‘none’ for no color mpl color spec. or ‘none’ for no color a matplotlib.negative contours solid 1.5 00 -1. Release 1.Bbox instance [True | False] [ (Path. or None for default.Matplotlib.axes transform url visible Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.5 1. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec.0 0.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.1.figure.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.transforms. or None for default. matplotlib.000 .5 0.0 0.1 Single color0.

y1. y2=0. interpolate=False.0 00 0. Release 1. default to ﬁll between everywhere.500 -1.1 0.500 1.5 1. kwargs keyword args passed on to the PolyCollection kwargs control the Polygon properties: 446 Chapter 36.000 1.0. Otherwise.00 0 1 0 1 2 Example: fill_between(x.0 3 2 -0. If not None.5 1.5 0.Matplotlib. **kwargs) call signature: fill_between(x. y2=0. the start and end points of the ﬁlled region will only occur on explicit values in the x array.000 Crazy lines 0. y1.0 1. it is a a N length numpy boolean array and the ﬁll will only happen over the regions where where==True interpolate If True.5 2.5 00 1. interpolate between the two lines to ﬁnd the precise point of intersection. where=None. where=None. matplotlib axes .0 0. **kwargs) Create a PolyCollection ﬁlling 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.

2 1.6 3 2 1 0 1.8 0.5 1.0 Lines with colorbar 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.1 2.8 1.4 1.0 -1.5 1.Bbox instance [True | False] [ (Path.5 2.0.0 -0.transforms.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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib.0 1.2 2 3 1 1.0 0. Release 1.6 1.2 0.8 0.4 0. matplotlib.0 1.axes 447 .8 1.Matplotlib.0 0.figure.40.1.2 -0.0 0.4 0.0 0.Figure instance an id string any string Continued on next page 36.2 0.4 0.5 0.2 0.

9 – continued from previous page linestyle or linestyles or dashes [’solid’ | ‘dashed’.Matplotlib. it is a a N length numpy boolean array and the ﬁll 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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance Continued on next page 448 Chapter 36. x2=0. **kwargs) Create a PolyCollection ﬁlling 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. Release 1. where=None. default to ﬁll between everywhere.1 Table 36. where=None. **kwargs) call signature: fill_between(y. x1. matplotlib axes . If not None. x1. x2=0. ‘dotted’ | (oﬀset. ‘dashdot’. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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 ﬁlling between two sets of x-values fill_betweenx(y.

0.fmt_xdata if it is callable.figure. else will fall back on the xaxis major formatter format_ydata(y) Return y string formatted. y coord format_xdata(x) Return x string formatted. matplotlib.axes 449 . ‘dashdot’.1 Table 36. y) return a format string formatting the x.10 – continued from previous page clim a length 2 sequence of ﬂoats clip_box a matplotlib.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. ‘dotted’ | (oﬀset. This function will use the fmt_ydata attribute if it is callable. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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 ﬁlling between two sets of y-values format_coord(x.Matplotlib. else will fall back on the yaxis major formatter frame get_adjustable() 36. 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.Bbox instance clip_on [True | False] clip_path [ (Path.1.transforms. Release 1. This function will use the attribute self.

6 0.Matplotlib.0.0 0.8 . Release 1.2 2 1 0 1 2 word length anomaly 1. matplotlib axes 1.6 1.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.98.2 verbosity coefficient 0. Deprecated since version 0. get_children() return a list of child artists 450 Chapter 36.

matplotlib.0 1.0.1.5 -1.Legend instance.0 0.1 Listed colors (3 masked regions) 2 1 0 1 2 33 2 1 0 1 2 0.5 0.0 1. This method is intended to be overridden by new projection types. 0 1. Release 1.0 0.5 -1.Matplotlib. 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. or None if no legend is deﬁned get_legend_handles_labels() 36.5 1. where linewidth is a ﬂoat and color is an RGBA tuple get_data_ratio() Returns the aspect ratio of the raw data.5 get_cursor_props() return the cursor propertiess as a (linewidth.axes 451 . Will be used when both axis scales are in log. color) tuple.0 0. get_data_ratio_log() Returns the aspect ratio of the raw data in log scale.5 0.0 -0.

1 0.02 0. 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.06 0. ‘ZOOM’.00 0.04 0.legend(h.06 0.02 0. 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.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.08 0. Release 1.0. l = ax.get_legend_handles_labels() ax.04 0.legend() is equivalent to h. matplotlib axes .

0 0. Returns a 3-tuple of the form: (transform. halign) where valign and halign are requested alignments for the text.5 0.1 1. 36.5 4. get_window_extent(*args.5 1. The dimension of the Bbox in canvas coordinate.2 0. valign. 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 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. Note: This transformation is primarily used by the Axis class. which will add the given amount of padding (in points) between the axes and the label.5 3.2 1.40. **kwargs) get the axes bounding box in display space. 0. Release 1.0 0.4 in y 1.1.2 in x. The x-direction is in data coordinates and the y-direction is in axis coordinates.0. 0.0 3.2 0.Matplotlib.8 0. matplotlib.4 0.0 2.axes 453 .4 Simplest errorbars.5 2.0 1. and is meant to be overridden by new kinds of projections that may need to place axis elements in diﬀerent locations.0 0.6 0. get_title() Get the title text string.

Note: This transformation is primarily used by the Axis class. valign.0 Hor.5 0.2 6 0. 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.0 2Mixed sym.0 0. and is meant to be overridden by new kinds of projections that may need to place axis elements in diﬀerent locations. ticks and gridlines.5 H.6 0. which will add the given amount of padding (in points) between the axes and the label. symmetric 1.5 Vert. The x-direction is in data coordinates and the y-direction is in axis coordinates. 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. Release 1. V asymmetric 1. matplotlib axes . get_xaxis_transform(which=’grid’) Get the transformation used for drawing x-axis labels.0 0. halign) where valign and halign are requested alignments for the text. Note: This transformation is primarily used by the Axis class.0. and is meant to be overridden by new kinds of projections that may need to place axis elements in diﬀerent locations.5 2 0 2 4 0. Returns a 3-tuple of the form: (transform.0 0.4 0.Matplotlib.5 0.0 0. symmetric 1..1 1.5 2 0 2 4 1.8 0. The x-direction is in data coordinates and the y-direction is in axis coordinates.

2 0. matplotlib.0 0.6 0.1.5 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.axes 455 .2 0.Matplotlib.8 1.3 0.0 0.4 0.6 0.1 0.0 get_xlabel() Get the xlabel text string.1 0.4 0. get_xlim() Get the x-axis range [left. Release 1.2 0.0.1 0.

5 2.5 1.0 1.0 0.0 0.5 1.0 1.0 0.5 0. get_yaxis_transform(which=’grid’) Get the transformation used for drawing y-axis labels.5 2.5 0.0 0. The x-direction is in 456 Chapter 36.5 0. The x-direction is in axis coordinates and the y-direction is in data coordinates. valign.0. halign) where valign and halign are requested alignments for the text. Note: This transformation is primarily used by the Axis class.5 1.5 1. valign. The x-direction is in axis coordinates and the y-direction is in data coordinates.Matplotlib.5 1. and is meant to be overridden by new kinds of projections that may need to place axis elements in diﬀerent locations.0 0. Returns a 3-tuple of the form: (transform. ticks and gridlines.0 1.0 0. matplotlib axes .5 1.0 0.0 1.0 0. Returns a 3-tuple of the form: (transform.0 x 1.0 0. get_yaxis_text2_transform(pad_points) Get the transformation used for drawing the secondary y-axis labels. Note: This transformation is primarily used by the Axis class. which will add the given amount of padding (in points) between the axes and the label.1 between y1 andbetween y1 and 1 y2 between y1 and 0 1.0 0.5 1. and is meant to be overridden by new kinds of projections that may need to place axis elements in diﬀerent locations.5 2.5 0.0 1. halign) where valign and halign are requested alignments for the text.0 Get the transformation used for drawing y-axis labels.0 0. which will add the given amount of padding (in points) between the axes and the label. Release 1.

0 1.5 0.5 0.0 0. 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. 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. matplotlib.0 1.5 2. Release 1.0.1.5 masked 2.5 1.5 0.0 1.axes 457 . and is meant to be overridden by new kinds of projections that may need to place axis elements in diﬀerent locations.0 axis coordinates and the y-direction is in data coordinates.Matplotlib.5 0.0 0.1 1. get_ylim() Get the y-axis range [bottom. Note: This transformation is primarily used by the Axis class.0 0.5 1.5 1.5 1.0 0.0 0.0 fill between where 0.0 Now regions with y2>1 are1.5 1.0 1.

grid(color=’r’. which=’major’.5 0. **kwargs) call signature: grid(self. linewidth=2) Valid Line2D kwargs are 458 Chapter 36. matplotlib axes . If kwargs are supplied. b is a boolean. ‘on’ or ‘oﬀ’. or both are aﬀected. (For MATLAB compatibility. which can be ‘major’ (default).) If b is None and len(kwargs)==0.1 1. linestyle=’-’.0 0.Matplotlib.0 0. eg: ax. it is assumed that you want a grid and b is thus set to True. Release 1.0 0.0. ‘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.5 1. **kwargs) Set the axes grids on or oﬀ.0 0. b may also be a string. b=None. toggle the grid state. or ‘both’ to control whether major tick grids.0 1. minor tick grids. kawrgs are used to set the grid line properties.5 2. which=’major’.5 1.

1 between y1 andbetween y1 and 1 y2 between y1 and 0 2.0 0. matplotlib.0 0.5 1.Bbox instance [True | False] [ (Path.0 1.1.5 1. Release 1.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string 36.5 1. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x.5 1.0 0.01.0. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Matplotlib.0 1.0 1.0 1.0 1.5 1.01.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.5 1.0 x 0.axes 459 .5 1.0 0.5 2.0 0.5 0.0 transparent through 1.5 0.5 1.0 0.5 0.01.5 0.figure.5 1.0 0.0 1.5 2.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 ﬂoat (0.5 0.5 0.0 0.transforms.

’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.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. alpha=None. linewidths=None.’ | ’. matplotlib axes . norm=None. where x. yscale=’linear’. stride) ﬂoat distance in points or callable pick function fn(artist. and may not actually be useful for anything. marginals=True **kwargs) Make a hexagonal binning plot of x versus y. this is a histogram of the number of occurences of the observations at (x[i].y[i]). C = None. xscale = ’linear’. mincnt=None. If C is None (the default). gridsize = 100. yscale = ’linear’.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind.0. N. vmax=None. y are 1-D sequences of the same length. bins = None. C=None. edgecolors=’none’. bins=None. vmin=None. **kwargs) call signature: hexbin(x.Matplotlib. cmap=None. linewidths=None. hexbin(x.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 [ ’-’ | ’--’ | ’-. This should not be used to determine whether the dataLim need to be updated. extent=None. y. which defaults to 460 Chapter 36. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. These values are accumulated for each hexagonal bin and then reduced according to reduce_C_function. y. norm=None. reduce_C_function=<function mean at 0x2b55320>. mincnt=None. it speciﬁes values at the coordinate (x[i].transforms. If C is speciﬁed. vmin=None. alpha=None. vmax=None.mean.y[i]). edgecolors=’none’ reduce_C_function = np. xscale=’linear’. gridsize=100. Release 1. marginals=False. cmap=None.

5 2.0 0.0 fill between where 1. log10 (i + 1) is used to determine the hexagon color.0 0.0 > 10.5 0.01. divide the counts in the speciﬁed number of bins. Internally.5 0.) x. The corresponding number of hexagons in the y-direction is chosen such that the hexagons are approximately regular.5 1.5 Now regions with0. and color the hexagons accordingly.0 0. xscale: [ ‘linear’ | ‘log’ ] Use a linear or log10 scale on the horizontal axis. If a sequence of values. use a logarithmic scale for the color map.1.0 0. y and/or C may be masked arrays.5 y2 are 1. (If C is speciﬁed. scale: [ ‘linear’ | ‘log’ ] Use a linear or log10 scale on the vertical axis.5 masked 1.5 numpy’s mean function (np. the color of each hexagon directly corresponds to its count value. Alternatively. matplotlib.0 1.0 0.5 1. If an integer.0.0 1.5 1.5 1.0 1. in which case only unmasked points will be plotted. 36. bins: [ None | ‘log’ | integer | sequence ] If None. Optional keyword arguments: gridsize: [ 100 | integer ] The number of hexagons in the x-direction. Release 1.Matplotlib. gridsize can be a tuple with two elements specifying the number of hexagons in the x-direction and the y-direction. the values of the lower bound of the bins to be used.01.axes 461 . default is 100.5 0.mean). it must also be a 1-D sequence of the same length as x and y. no binning is applied.1 2. If ‘log’.

draws the edges in the same color as the ﬁll color. Other keyword arguments controlling color mapping and normalization arguments: cmap: [ None | Colormap ] a matplotlib. norm: [ None | Normalize ] matplotlib. as required by RegularPolyCollection. y. If either are None.1 mincnt: None | a positive integer If not None. Release 1. only display cells with more than mincnt number of points in the cell marginals: True|False if marginals is True. matplotlib axes 462 .cmap. as it avoids unsightly unpainted pixels between the hexagons. defaults to rc lines. Note that this is a tuple. x.0.linewidth.cm. and if you set the linewidths argument you must set it as a sequence of ﬂoats.Matplotlib.Bbox instance [True | False] [ (Path. the min and max of the color array C is used. or None the alpha value for the patches linewidths: [ None | scalar ] If None.transforms.Colormap instance. right. bottom. defaults to rc image. This is the default. alpha: scalar between 0 and 1. Transform) | Patch | None ] a colormap or registered colormap name matplotlib color arg or sequence of rgba tuples Continued on next page Chapter 36.colors. draws the outlines in the speciﬁed color. xscale and yscale. If None. The default assigns the limits based on gridsize. If None. your settings for vmin and vmax will be ignored. Note if you pass a norm instance. top) ] The limits of the bins. plot the marginal density as colormapped rectagles along the bottom of the x-axis and left of the y-axis extent: [ None | scalars (left. Other keyword arguments controlling the Collection properties: edgecolors: [ None | mpl color | color sequence ] If ‘none’.1. 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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib. If a matplotlib color arg or sequence of rgba tuples.Normalize instance is used to scale luminance data to 0. draws the outlines in the default color. vmin/vmax: scalar vmin and vmax are used in conjunction with norm to normalize luminance data.

use get_array() on this PolyCollection to get the counts in each hexagon. bins=10.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. range=None. rwidth=None. The return value is a tuple (n. orientation=’vertical’.1. x1. cumulative=False.. histtype=’bar’.. or as a 2-D ndarray in which each column is a dataset. [patches0. range=None. cumulative=False. bottom=None. patches1. align=’mid’. align=’mid’. ‘dotted’ | (oﬀset.. Release 1. matplotlib.Matplotlib. bins. weights=None..Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. .0. bins. horizontal bar and vertical bar (both PolyCollections) will be attached to the return collection as attributes hbar and vbar Example: hist(x. log=False.. patches) or ([n0. log=False.. bins=10. **kwargs) Compute and draw the histogram of x. ‘dashdot’. histtype=’bar’.. Note that the ndarray form is transposed relative to the list form.]. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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. . rwidth=None. normed=False.]). If marginals is True. Keyword arguments: 36. label=None. Multiple data can be provided via x as a list of datasets of potentially diﬀerent length ([x0. Masked arrays are not supported at present. bottom=None. normed=False. **kwargs) call signature: hist(x.figure.axes 463 . n1. color=None.. orientation=’vertical’.]) if the input contains multiple data.1 Table 36.

25 4 3 2 10 1 2 3 4 0.1 Hexagon binning 20 10 0 10 20 With a log color scale 20 140 120 10 100 80 60 counts 0 2.Matplotlib. Release 1.sum(pdf * np.0. Range has no eﬀect if bins is a sequence. Lower and upper outliers are ignored. bins. i.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.75 0. patches = ax. n/(len(x)*dbin). If bins is an integer. autoscaling is based on the speciﬁed bin range instead of the range of x.min().75 1.5. bins + 1 bin edges will be returned.50 1. range: The lower and upper range of the bins. In a probability density.50 0.00 1.. If bins is a sequence or range is speciﬁed. the integral of the histogram should be 1. of the same shape as x. the underlying numpy histogram function was incorrect with normed*=*True if bin sizes were unequal. the ﬁrst element of the return tuple will be the counts normalized to form a probability density. matplotlib axes . If not provided.hist(. MPL inherited that error. x..e. It is now corrected within MPL when using earlier numpy versions weights An array of weights. consistent with numpy.3.diff(bins)) Note: Until numpy release 1.histogram() for numpy version >= 1. range is (x.) print np.max()). and with the new = True argument in earlier versions..00 log10(N) 1. normed: If True.00 0. Unequally spaced bins are supported if bins is a sequence. you can verify that with a trapezoidal integration of the probability density function: pdf. Each value in x only contributes 464 Chapter 36.

Ignored if histtype = ‘step’ or ‘stepﬁlled’. then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. cumulative: If True. label=’men’) ax. • ‘bar’ is a traditional bar-type histogram. • ‘stepﬁlled’ generates a lineplot that is by default ﬁlled. or sequence of strings to match multiple datasets. • ‘mid’: bars are centered between the bin edges. If None. so that the integral of the density over the range remains 1. rwidth: The relative width of the bars as a fraction of the bin width. matplotlib.1.g. • ‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.0. In this case. alpha=0.hist(10+2*np. the histogram axis will be set to a log scale.randn(1000).5) ax. • ‘right’: bars are centered on the right bin edges. barh() will be used for bartype histograms and the bottom kwarg will be the left edges. -1). If multiple data are given the bars are aranged side by side. then the histogram is normalized such that the ﬁrst bin equals 1. • ‘left’: bars are centered on the left bin edges.randn(1000). Release 1.Matplotlib.1 its associated weight towards the bin count (instead of 1). if normed is also True. color: Color spec or sequence of color specs. empty bins will be ﬁltered out and only the non-empty (n. The last bin gives the total number of datapoints. label=’women’. • ‘step’ generates a lineplot that is by default unﬁlled. If normed is also True then the histogram is normalized such that the last bin equals 1. the weights are normalized. log: If True.hist(12+3*np. label: String. but only the ﬁrst gets the label. histtype: [ ‘bar’ | ‘barstacked’ | ‘step’ | ‘stepﬁlled’ ] The type of histogram to draw. the direction of accumulation is reversed. align: [’left’ | ‘mid’ | ‘right’ ] Controls how the histogram is plotted. one per dataset. so that the legend command will work as expected: ax. Default (None) uses the standard line color sequence.legend() kwargs are used to update the properties of the Patch instances returned by hist: 36. automatically compute the width. patches) will be returned.random. If cumulative evaluates to less than 0 (e. bins.axes 465 . Bar charts yield multiple patches per dataset.random. If normed is True. orientation: [ ‘horizontal’ | ‘vertical’ ] If ‘horizontal’. If log is True and x is a 1D array.

else the widths of the lines are determined by xmin and xmax.transforms. xmax. Returns the LineCollection that was added. xmin. label=’‘. **kwargs) Plot horizontal lines at each y from xmin to xmax. colors=’k’. xmin. either a single color or a len(y) list of colors 466 Chapter 36. Optional keyword arguments: colors: a line collections color argument. If they are scalars.0.Bbox instance [True | False] [ (Path. Required arguments: y: a 1-D numpy array or iterable. matplotlib axes .Matplotlib. or ‘none’ for no color a matplotlib. colors=’k’.figure.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number hlines(y. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. linestyles=’solid’. **kwargs) call signature: hlines(y. or None for default. linestyles=’solid’.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 ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib. xmin and xmax: can be scalars or len(x) numpy arrays. or None for default. or ‘none’ for no color mpl color spec. xmax. Release 1. then the respective values are constant.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.

the current axes and ﬁgure will be cleared on the next plot command imshow(X. vmin=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. imlim=None.axes 467 . interpolation=None.0. origin=None. aspect=None.0. resample=None. norm=None. **kwargs) call signature: 36. ﬁlterrad=4.010 0. ﬁlternorm=1.1. matplotlib. Release 1.020 Probability 0. When hold is False.Matplotlib. url=None. If hold is None (default). subsequent plot commands will be added to the current axes. shape=None.000 40 Histogram of IQ : µ =100. alpha=None.025 0.030 0. cmap=None.015 0. Examples: •toggle hold: >>> hold() •turn hold on: >>> hold(True) •turn hold oﬀ >>> hold(False) When hold is True. vmax=None. Else set the hold state to boolean value b. extent=None.005 0.1 0. toggle the hold state.

0 to 1.3 0.AxesImage instance is returned.4 0. changes the image aspect ratio to match that of the axes 468 Chapter 36. cm.cm.9 0. a uint8 array or a PIL image.2 0.jet.image. **kwargs) Display the image in X to current axes. matplotlib axes . Release 1. ﬂoat array only) •MxNx3 – RGB (ﬂoat or uint8 array) •MxNx4 – RGBA (ﬂoat or uint8 array) The value for each component of MxNx3 and MxNx4 ﬂoat arrays should be in the range 0. eg. An matplotlib. aspect=None. default to rc image. interpolation=None. X may be a ﬂoat array. If None.cmap value. vmin=None.Matplotlib.5 0. cmap is ignored when X has RGB(A) information aspect: [ None | ‘auto’ | ‘equal’ | scalar ] If ‘auto’. alpha=None. X can have the following shapes: •MxN – luminance (grayscale. extent=None.6 0.8 0. cmap=None. MxN ﬂoat arrays may be normalised. origin=None.Colormap instance. vmax=None.0.1 0. Keyword arguments: cmap: [ None | Colormap ] A matplotlib.0. If X is an array.1 5 4 3 2 1 Comparison of model with data 0 0.0 time (s) imshow(X. norm=None.7 0.

‘hermite’. If None.0. ‘hanning’. ‘nearest’. changes the axes aspect ratio to match that of the image. matplotlib. default is normalization(). ‘spline16’. Release 1.0 which means that any sum of pixel weights must be equal to 1. right. ‘sinc’. ‘catrom’. ‘kaiser’.interpolation.Matplotlib. This scales luminance -> 0-1 norm is only used for an MxN ﬂoat array. i. alpha: scalar The alpha blending value. between 0 (transparent) and 1 (opaque) or None origin: [ None | ‘upper’ | ‘lower’ ] Place the [0.origin. ‘lanczos’ If interpolation is None. If either is None. So. ‘quadric’. ‘mitchell’. From the antigrain documentation. If extent is not None. extent: [ None | scalars (left. the min and max of the luminance values will be used. ﬁlterrad: The ﬁlter radius for ﬁlters that have a radius parameter. ‘gaussian’. the ﬁlter normalizes integer values and corrects the rounding errors.0] index of the array in the upper left or lower left corner of the axes. ‘bessel’. ‘lanczos’ or ‘blackman’ Additional kwargs are Artist properties: if 36. Note if norm is not None.e.aspect value. column indices to the x. ‘hamming’.0. the ﬁlter function must produce a graph of the proper shape. default to rc image. If None. shape: [ None | scalars (columns. default to rc image. ‘spline36’. the settings for vmin and vmax will be ignored. when interpolation is one of: ‘sinc’. interpolation: Acceptable values are None. top) ] Data limits for the axes. vmin/vmax: [ None | scalar ] Used to scale a luminance image to 0-1. ‘bilinear’. See also the ﬁlternorm and ﬁlterrad parameters norm: [ None | Normalize ] An matplotlib. the axes aspect ratio is changed to match that of the extent. ‘bicubic’. rows) ] For raw buﬀer images ﬁlternorm: A parameter for the antigrain image resize ﬁlter. if ﬁlternorm = 1.colors.axes 469 . bottom. y centers of the pixels. It doesn’t do anything with the source ﬂoating point values.1 If ‘equal’.1. default to rc image.Normalize instance. and extent is None. None. it corrects only integers according to the rule of 1. The default assigns zero-based row.

figure.Bbox instance [True | False] [ (Path.Matplotlib. matplotlib axes . Release 1.0.Figure instance an id string any string [True | False] [None|ﬂoat|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.transforms.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 ﬂoat (0.0 opaque) [True | False] an Axes instance a matplotlib.0 transparent through 1. Transform) | Patch | None ] a callable function a matplotlib.

1 in_axes(mouseevent) return True if the given mouseevent (in display coords) is in the Axes invert_xaxis() Invert the x-axis. y. 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. You can set the label of a line by doing: plot(x. **kwargs) call signature: legend(*args. loc=’upper left’) or: legend( (line1. ’label3’) ) To make a legend at a given location.axes 471 . ’label2’. (’label1’. line2.0. the item will not be shown in legend. line3). If label is set to ‘_nolegend_’. ’label2’. loc=2) The location codes are 36. To automatically generate the legend from labels: legend( (’label1’.Matplotlib. ’label3’). Labels are a sequence of strings and loc can be a string or an integer specifying the legend location. **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. matplotlib. ’label2’. line2. ’label2’. (’label1’. label=’my data’) or: line. ishold() return the HOLD status of the axes legend(*args.1. ’label3’). Release 1. invert_yaxis() Invert the y-axis. using a location argument: legend( (’label1’.set_label(’my data’). line3).

use rc settings. If None. The loc itslef can be a 2-tuple giving x. the legend will be horizontally expanded to ﬁll the axes area (or bbox_to_anchor) bbox_to_anchor [an instance of BboxBase or a tuple of 2 or 4 ﬂoats] the bbox that the legend will be anchored.0. If None. default is 1 mode [[ “expand” | None ]] if mode is “expand”. original. If None. The legend location can be speciﬁed in other coordinate. 0. Keyword arguments: prop: [ None | FontProperties | dict ] A matplotlib. by using the bbox_transform keyword.5. For example. use rc shadow: [ None | False | True ] If True. bbox_to_anchor = (0. If prop is a dictionary. draw a shadow behind legend. matplotlib axes . ncol [integer] number of columns. bbox_to_anchor can be an instance of BboxBase(or its derivatives) or a tuple of 2 or 4 ﬂoats.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. loc = ‘upper right’.5) will place the legend so that the upper right corner of the legend at the center of the axes. draw a frame. numpoints: integer The number of points in the legend for line scatterpoints: integer The number of points in the legend for scatter plot scatteroﬀsets: list of ﬂoats a list of yoﬀsets for scatter symbols in legend markerscale: [ None | scalar ] The relative size of legend markers vs. use rc settings. draw a frame with a round fancybox. frameon: [ True | False ] if True. Release 1. If None.Matplotlib.FontProperties instance.y of the lower-left corner of the legend in axes coords (bbox_to_anchor is ignored). a new instance will be created with prop.font_manager. Default is True fancybox: [ None | False | True ] if True. 472 Chapter 36. use rc settings.

Matplotlib. a fontsize of 10 points and a handlelength=5 implies a handlelength of 50 points. locator_params(axis=’both’. Values from rcParams will be used if None.1 bbox_transform [[ an instance of Transform | None ]] the transform for the bbox. **kwargs) Convenience method for controlling tick locators. tight=None.1.axes 473 . transAxes if None.. Keyword arguments: 36.0. These values are measure in font-size units. title [string] the legend title Padding and spacing between various elements use following keywords parameters. 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. matplotlib. E.g. Release 1.

This presently works only for the MaxNLocator used by default on linear axes.locator_params(tight=True. default is ‘both’. but it may be generalized. loglog(*args. Typically one might want to reduce the maximum number of ticks and use tight bounds when plotting small subplots.Axes.Bbox instance [True | False] [ (Path.Axes. for example: ax. Default is None. **kwargs) Make a plot with log scaling on the x and y axis. which depend on the number of decades in the plot.axes. for no change. autoscale_view() is called automatically after the parameters are changed. Release 1. matplotlib axes . 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 ﬂoat (0. **kwargs) call signature: loglog(*args.0.Axes.Matplotlib.set_yscale() for details nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid.0 transparent through 1. Remaining keyword arguments are passed to directly to the set_params() method.axes.set_yscale(). Transform) | Patch | None ] any matplotlib color a callable function and 474 Chapter 36.set_xscale() / matplotlib. None defaults to autosubs.1 axis [’x’ | ‘y’ | ‘both’] Axis on which to operate.axes. loglog() supports all the keyword arguments of plot() matplotlib.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. see matplotlib.transforms. 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.set_xscale() / matplotlib.axes. nbins=4) Because the locator is involved in autoscaling.Axes. tight [True | False | None] Parameter passed to autoscale_view().

signatures: margins() returns xmargin.0.Transform instance a url string [True | False] 1D array 1D array any number Example: margins(*args. stride) ﬂoat distance in points or callable pick function fn(artist.axes 475 . **kw) Convenience method to set or retrieve autoscaling margins. Release 1.Matplotlib. 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 [ ’-’ | ’--’ | ’-. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. ymargin margins(margin) margins(xmargin.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind.1.transforms.’ | ’.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.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/oﬀ ink in points 2D array (rows are x. matplotlib. ymargin) 36.figure.

because they interact. if xmargin is not None.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. the default here is True. for example. Argument: Z anything that can be interpreted as a 2-D array kwargs all are passed to imshow(). y=ymargin) margins(. you probably should be using imshow directly in your own version of 476 Chapter 36. no additional padding to match tick marks is usually desired. matshow(Z.0 0.5 15 201.0 -2 10-1 100 101 102 10 All three forms above set the xmargin and ymargin parameters. Release 1. All keyword parameters are optional. Row and column numbering is zero-based. matshow() sets defaults for extent. use care in overriding the extent and origin kwargs. The tight parameter is passed to autoscale_view(). tight=False) loglog base 4 on x 105Errorbars go negative 5 10 semilogx 1.5 0. The matrix will be shown the way it would be printed. and aspect. on the assumption that when margins are speciﬁed.. **kwargs) Plot a matrix or array as an image.0. with the ﬁrst row at the top. origin. A single argument speciﬁes both xmargin and ymargin. (Also. which is executed after a margin is changed. if you want to change them.0 0..Matplotlib. interpolation.. Setting tight to None will preserve the previous setting. Specifying any margin changes only the autoscaling. matplotlib axes . then xmargin times the X data interval will be added to each end of that interval before it is used in autoscaling.

j]. for details. j+1]). if ‘ﬂat’.) Returns: an matplotlib. use rc settings.1. Y[i+1.j] (X or Y at [i. j+1]) is masked. nothing is plotted. (X[i.cm. or one of the vertices surrounding C[i. they will be expanded as needed into the appropriate 2-D arrays. a black grid is drawn around each rectangle. Y[i. vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data. if the dimensions are the same. If either or both of X and Y are 1-D arrays or column vectors. j+1]. see the Grid Orientation section below. This kwarg is deprecated. **kwargs) Create a pseudocolor plot of a 2-D array. j]). then the last row and column of C will be ignored. j+1]. contrary to MATLAB. Y[i+1.colors.axes 477 .Normalize instance is used to scale luminance data to 0. shading: [ ‘ﬂat’ | ‘faceted’ ] If ‘faceted’. Keyword arguments: cmap: [ None | Colormap ] A matplotlib. minorticks_off() Remove minor ticks from the axes. making a rectangular grid. Y[i. Ideally the dimensions of X and Y should be one greater than those of C. specify the (x. If you pass a norm instance. defaults to normalize(). j+1].j] has corners at: (X[i. j]). pcolor(*args. Y and C may be masked arrays. Release 1.Matplotlib. and the row index corresponds to y. Default is ‘ﬂat’. j+1]). If None.image.[i+1. norm: [ None | Normalize ] An matplotlib. the min and max of the color array C is used.1. **kwargs) call signatures: pcolor(C. the quadrilateral for C[i. [i+1. Y.1 matshow. X. if given. matplotlib. j]. j]. (X[i+1. If either are None. If None. C is the array of color values. minorticks_on() Add autoscaling minor ticks to the axes. edges are not drawn.AxesImage instance.0. y) coordinates of the colored quadrilaterals. X and Y.Colormap instance. (X[i+1. **kwargs) pcolor(X. j]. C. If either C[i. Note that the the column index corresponds to the x-coordinate. please use ‘edgecolors’ instead: 36. [i. vmin and vmax will be ignored. j].

len(y)) then you need: pcolor(X.collection. 3.T) MATLAB pcolor() always discards the last row and column of C.0. 0. increasing up. 2. C is taken as C*(*y. If ‘none’. except that the Y axis is reversed. The grid orientation follows the MATLAB convention: an array C with shape (nrows. ncolumns) is plotted with the column number as X and the row number as Y. 0. 2. 1. 4]. edges will not be visible. 2. Y = meshgrid(x. 3.arange(5) y = np. [1. 4]]) Y = array([[0. 1]. [2.T) or: pcolor(C. Y. 2.y) is equivalent to: X = array([[0.arange(3) X. That is. 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. 1. but matplotlib displays the last row and column if X and Y are not speciﬁed. Similarly for meshgrid(): x = np. or if X and Y have one more row and column than C. hence it is plotted the way the array would be printed. matplotlib axes . Release 1. x). kwargs can be used to control the PolyCollection properties: Property agg_filter alpha animated antialiased or antialiaseds array axes Description unknown ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance Continued on next page 478 Chapter 36. 0. 0]. 2]]) so if you have: C = rand( len(x). 1. [0. 2. 3. 1.1 • shading=’ﬂat’ – edgecolors=’none’ • shading=’faceted – edgecolors=’k’ edgecolors: [ None | ‘none’ | color | color sequence] If None. the rc setting is used by default.Matplotlib. C. 4].Collection instance. 1. [0. 2.

transforms. yr. Call signatures: pcolor(C. In some cases. Release 1. ‘dotted’ | (oﬀset. Y. particularly if alpha is 1. this is a version of pcolor that does not draw lines. which defaults to True. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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. you may be able to reduce rendering artifacts (light or dark patch boundaries) by setting it to False. **kwargs) pcolor(X. pcolorfast(*args. that provides the fastest possible rendering with the Agg backend.14 – continued from previous page clim a length 2 sequence of ﬂoats clip_box a matplotlib.1. C.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. **kwargs) pcolor(xr.axes 479 .0. **kwargs) 36. 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.antialiased’]. y. C.Matplotlib. ‘dashdot’.1 Table 36. there seems to be no single combination of parameters that eliminates artifacts under all conditions. C.figure. and that can handle any quadrilateral grid. Unfortunately. **kwargs) pcolor(x.Bbox instance clip_on [True | False] clip_path [ (Path. An alternative it to set edgecolors to ‘face’. **kwargs) pseudocolor plot of a 2-D array Experimental. matplotlib.

defaults to normalize() vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data.j+1]. pcolor(C. If: xr = [x0. and if found to be uniform the fast version is used. and a QuadMesh collection in the general quadrilateral case. (X[i.j].j]. This is the fastest version. **kwargs) xr.Y[i. nc +1) that specify the (x. Y. Note that the the column index corresponds to the x-coordinate.j]). C) pcolormesh(C.Y[i+1.j] has corners at (X[i. (X[i+1. alpha: 0 <= scalar <= 1 or None the alpha blending value Return value is an image if a regular or rectangular grid is speciﬁed. It may produce faster and more compact output using ps. y0) is the outermost corner of cell (0. and the row index corresponds to y. and (x1.j]). see the “Grid Orientation” section below. x. Optional keyword arguments: cmap: [ None | Colormap ] A cm Colormap instance from cm.Normalize instance is used to scale luminance data to 0. **kwargs) call signatures: pcolormesh(C) pcolormesh(X. pdf.j+1]). [0. the min and max of the color array C is used. matplotlib axes . All cells are rectangles of the same size. C. use rc settings. but the slowest to render. Release 1.nc]. etc. The cells need not be rectangular. **kwargs) is equivalent to pcolor([0.0). C may be a masked array.j+1]. nc) be its shape. (x0.Y[i. If None. the quadrilateral for C[i. **kwargs) 480 Chapter 36.Matplotlib. however. y1) is the outermost corner of cell (nr-1. Hence the cells are rectangular but the grid may be nonuniform. x1] and: yr = [y0. (X[i+1. If None.1 C is the 2D array of color values corresponding to quadrilateral cells. yr specify the ranges of x and y corresponding to the rectangular region bounding C.nr]. respectively. If you pass a norm instance. If either are None. y are 1D arrays of length nc +1 and nr +1. norm: [ None | Normalize ] An mcolors. pcolormesh(*args.y1] then x goes from x0 to x1 as the second index of C goes from 0 to nc. for details. This is the most general.) X and Y are 2D arrays with shape (nr +1. nc-1).y) coordinates of the corners of the colored quadrilaterals. The speed is intermediate.Y[i+1. vmin and vmax will be None. giving the x and y boundaries of the cells. Let (nr.j+1]). (The grid is checked. and svg backends.0.1.

QuadMesh object. If None.Normalize instance is used to scale luminance data to 0. in contrast.collections. defaults to normalize().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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib. edges will not be visible. if ‘ﬂat’. This kwarg is deprecated. 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. contrary to MATLAB.transforms. kwargs can be used to control the matplotlib. but X and Y may not. If either are None. Release 1. a black grid is drawn around each rectangle. Masked array support is implemented via cmap and norm. the rc setting is used by default. matplotlib. vmin and vmax will be ignored. If you pass a norm instance. pcolor() simply does not draw quadrilaterals with masked colors or vertices.Colormap instance. If None.colors. edges are not drawn. 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. the min and max of the color array C is used.axes . Keyword arguments: cmap: [ None | Colormap ] A matplotlib. norm: [ None | Normalize ] A matplotlib.1.1 C may be a masked array.collection. Default is ‘ﬂat’. If ‘None’.0. vmin/vmax: [ None | scalar ] vmin and vmax are used in conjunction with norm to normalize luminance data.1.Bbox instance [True | False] [ (Path.Matplotlib.cm. use rc settings. please use ‘edgecolors’ instead: • shading=’ﬂat’ – edgecolors=’None’ • shading=’faceted – edgecolors=’k’ edgecolors: [ None | ‘None’ | color | color sequence] If None. shading: [ ‘ﬂat’ | ‘faceted’ | ‘gouraud’ ] If ‘faceted’.

pick(*args) call signature: pick(mouseevent) each child artist will ﬁre a pick event if mouseevent is over the artist and the artist has picker set pie(x. 482 Chapter 36.0. pctdistance=0.1000000000000001) call signature: pie(x. labeldistance=1. colors=(’b’. ’k’.59999999999999998. matplotlib axes .Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. autopct=None. If sum(x) <= 1. ’w’). autopct=None. is a len(x) array which speciﬁes the fraction of the radius with which to oﬀset each wedge. Keyword arguments: explode: [ None | len(x) sequence ] If not None. ’g’. ’c’. The fractional area of each wedge is given by x/sum(x). explode=None.1 Table 36. ’m’. ‘dashdot’. labeldistance=1.1. ‘dotted’ | (oﬀset. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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.figure. pctdistance=0.6. ’r’.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. ’y’. labels=None. colors=None. then the values of x give the fractional area directly and the array will not be normalized. shadow=False) Make a pie chart of array x. Release 1. shadow=False. explode=None.Matplotlib. labels=None.

x2.Matplotlib.Text instances. For example.0. Ignored if autopct is None. Eg. matplotlib. y2. ’g^’. fmt groups can be speciﬁed.1. The label will be placed inside the wedge. allowing for multiple x. args is a variable length argument. If it is a function.6.1. ’r+’) # # # # plot x plot x plot y ditto.8)) ax = axes([0..1. autotexts). 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. is a string or function used to label the wedges with their numeric value. **kwargs) Plot lines and/or markers to the Axes.text.1 colors: [ None | color sequence ] A sequence of matplotlib color args through which the pie chart will cycle.patches. y. 0. texts.: figure(figsize=(8. it will be called.plot(x1. The following format string characters are accepted to control the line style or marker: 36. return the tuple (patches.axes 483 . y. 0. y1. y pairs with an optional format string. plot(*args. the label will be fmt%pct.8. and autotexts is a list of Text instances for the numeric labels. If it is a format string. 0. and y using default line style and color and y using blue circle markers using x as index array 0. y) plot(x. ’g-’) Return value is a list of lines that were added. Release 1. texts): • patches is a sequence of matplotlib. The pie chart will probably look best if the ﬁgure and axes are square. An arbitrary number of x. pctdistance: scalar The ratio between the center of each pie slice and the start of the text generated by autopct. default is 0. return the tuple (patches. ’bo’) plot(y) plot(y. as in: a. 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.N-1 but with red plusses If x and/or y is 2-dimensional. where patches and texts are as above.8]) Return value: If autopct is None. If autopct is not None. then the corresponding columns will be plotted.Wedge instances • texts is a list of the label matplotlib.

matplotlib axes . as in ’bo’ for blue circles. anitialising.’ ’:’ ’. hex strings (’#008000’). RGB or RGBA tuples ((0. The kwargs can be used to set line properties (any property that has a set_* method). Of these.’ ’. Line styles and colors are combined in a single format string.1 character ’-’ ’--’ ’-. the string speciﬁcations can be used in place of a fmt group.1)) or grayscale intensities as a string (’0. Here is an example: 484 Chapter 36. but the tuple forms can be used only as kwargs. marker face color. including full names (’green’). You can use this to set a line label (for auto legends). linewidth.0. you can specify colors in many weird and wonderful ways.8’).0.1.Matplotlib.’ ’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. etc. Release 1.

All of the line properties can be controlled by keyword arguments.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.2.3].Bbox instance [True | False] [ (Path.axes 485 . label=’line 2’) axis([0.1 plot([1. [1. you can set the color.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.9]. the kwargs apply to all those lines. For example. matplotlib.2.figure. linestyle=’dashed’.’ | ’. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.3]. and markercolor with: plot(x.transforms. 10]) legend() If you make multiple lines with one plot command.1.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. 4. marker=’o’. label=’line 1’. You do not need to use format strings.Line2D‘ for details. linewidth=2) plot([1. See :class:‘~matplotlib. which are just abbreviations. y1. e. color=’green’.0 transparent through 1.3].2. 0. y. x2. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x. antialised=False) Neither line will be antialiased.0. y2.: plot(x1. Release 1. ’go-’. [1.g. markerfacecolor=’blue’.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color 36.Matplotlib. ’rs’. linestyle. markersize=12). marker.lines.4. 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 ﬂoat (0.

AutoDateLocator (if the tick locator is not already set to a matplotlib. tz=None. the y-axis will be labeled with dates. fmt=’bo’. plot_date(x. tz=None.dates.1 markersize or ms markevery picker pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder ﬂoat None | integer | (startind. xdate=True. ydate=False. If None. matplotlib axes . ydate: [ False | True ] If True. 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. **kwargs) call signature: plot_date(x. the default is True. ydate=False. y. x and/or y can be a sequence of dates represented as ﬂoat days since 0001-01-01 UTC.Transform instance a url string [True | False] 1D array 1D array any number kwargs scalex and scaley. **kwargs) Similar to the plot() command.0. Keyword arguments: fmt: string The plot format string. Valid kwargs are Line2D properties: Property Description 486 Chapter 36.DateLocator instance) and the default tick formatter to matplotlib. y.dates. the x-axis will be labeled with dates. if deﬁned.transforms. Release 1.DateFormatter instance).dates. and the axis is labeled accordingly. stride) ﬂoat distance in points or callable pick function fn(artist. tz: [ None | timezone string ] The time zone to use in labeling dates. xdate=True.dates. defaults to rc value. except the x or y (or both) data is considered to be dates. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.AutoDateFormatter (if the tick formatter is not already set to a matplotlib. fmt=’bo’. Note if you are using custom date tickers and formatters.Matplotlib. are passed on to autoscale_view() to determine whether the x and y axes are autoscaled. xdate: [ True | False ] If True.

0.Transform instance a url string [True | False] 1D array 1D array any number See Also: dates for helper functions 36.Matplotlib. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. matplotlib.0 transparent through 1.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.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 ﬂoat (0.figure. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x.1.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.0 opaque) [True | False] [True | False] an Axes instance a matplotlib.transforms.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.axes 487 .’ | ’. Release 1. stride) ﬂoat distance in points or callable pick function fn(artist.transforms.Bbox instance [True | False] [ (Path.

which speciﬁes the number of data points used.Matplotlib. psd(x. num2date() and drange() for help on creating the required ﬂoating point dates. Release 1. which returns one-sided for real data and both for complex data. detrend: callable The function applied to each segment before ﬀt-ing. noverlap=0. Fc=0. detrend=mlab. window=<function window_hanning at 0x3a178c0>. pad_to: integer The number of points to which the data segment is padded when performing the FFT. noverlap: integer The number of points of overlap between blocks. Unlike in MATLAB. Fs: scalar The sampling frequency (samples per time unit). noverlap=0.detrend_none. This corresponds to the n parameter in the call to ﬀt().1 date2num(). 488 Chapter 36. Default gives the default behavior.blackman(). this can give more points in the plot. numpy. numpy. scale_by_freq=None. If a function is passed as the argument. matplotlib axes . sides=’default’. etc. The |ﬀt(i)|2 of each segment i are averaged to compute Pxx. scale_by_freq=None.get_window().window_hanning. freqs. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. The default value is 0 (no overlap). pad_to=None. Fs=2. window: callable or ndarray A function or a vector of length NFFT. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes which sides of the PSD to return. ‘onesided’ forces the return of a one-sided PSD. detrend=<function detrend_none at 0x3a1c668>. while ‘twosided’ forces two-sided. Each segment is detrended by function detrend and windowed by function window.signal. detrend_mean(). window_none(). To create window vectors see window_hanning(). with a scaling to correct for power loss due to windowing. The default value is 256. NFFT=256. The default is window_hanning(). in cycles per time unit. in matplotlib is it a function. This can be diﬀerent from NFFT. The vector x is divided into NFFT length segments. sides=’default’. where the detrend parameter is a vector.0. The default value is 2. **kwargs) call signature: psd(x.bartlett(). Must be even. NFFT=256. The pylab module deﬁnes detrend_none().hamming(). allowing for more detail. It is used to calculate the Fourier frequencies. Fc=0. noverlap gives the length of the overlap between segments. **kwargs) The power spectral density by Welch’s average periodogram method. The default is None.signal(). window=mlab. and detrend_linear(). Fs=2. scipy. designed to remove the mean or linear trend. scipy. pad_to=None. Fs is the sampling frequency. it must take a data segment as an argument and return the windowed version of the segment. but you can use a custom function as well. numpy. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). a power 2 is most eﬃcient.

0. though Pxx itself is returned.1 scale_by_freq: boolean Speciﬁes whether the resulting density values should be scaled by the scaling frequency. Returns the tuple (Pxx.0 transparent through 1. 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 ﬂoat (0. Fc: integer The center frequency of x (defaults to 0).figure. The default is True for MATLAB compatibility.axes 489 . matplotlib.transforms. Release 1. stride) ﬂoat distance in points or callable pick function fn(artist. event) 36.1. References: Bendat & Piersol – Random Data: Analysis and Measurement Procedures.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. This allows for integration over the returned frequency values. freqs). y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.Bbox instance [True | False] [ (Path.’ | ’.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-. For plotting.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’. which oﬀsets the x extents of the plot to reﬂect the frequency range used when a signal is acquired and then ﬁltered and downsampled to baseband. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x. the power is plotted as 10 log10 (P xx ) for decibels.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind. which gives density in units of Hz^-1.Matplotlib.

15 0. **kw) Plot a 2-D ﬁeld of arrows.00 0.0. Release 1. call signatures: 490 Chapter 36.Transform instance a url string [True | False] 1D array 1D array any number Example: Power Spectral Density (dB/Hz) 0.transforms.05 0.Matplotlib.10 0.10 0.1 pickradius rasterized snap solid_capstyle solid_joinstyle transform url visible xdata ydata zorder ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.150 10 20 30 40 50 60 70 80 900 2 4 6 8 10 10 20 30 Frequency 40 50 quiver(*args.05 0. matplotlib axes .

the arrow points from (x. for ‘dots’ or ‘inches’. **kw) C.axes 491 . when the the window is resized. matplotlib. Y are not supported at present. Y: The x and y coordinates of the arrow locations (default is tail of arrow. • ‘width’ or ‘height’: the width or height of the axes • ‘dots’ or ‘inches’: pixels or inches. CCW from the x-axis.0. for other units. V. With ‘xy’. For ‘x’ or ‘y’. angles: [’uv’ | ‘xy’ | array] With the default ‘uv’. but masked X. based on the ﬁgure dpi • ‘x’. respectively.g. 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. y+v). If None. Keyword arguments: units: [’width’ | ‘height’ | ‘dots’ | ‘inches’ | ‘x’ | ‘y’ | ‘xy’] arrow units. quiver(X. arbitrary angles may be speciﬁed as an array of values in degrees. If X and Y are absent.meshgrid().Matplotlib. **kw) U. For ‘width or ‘height’. m/s per plot width. a smaller scale parameter makes the arrow longer. the arrow size is independent of the zoom state. ‘y’. the arrow dimensions except for length are in multiples of this unit. scale: [ None | ﬂoat ] data units per arrow length unit. **kw) Arguments: X. Y. a simple autoscaling algorithm 36. so that if U*==*V the angle of the arrow on the plot is 45 degrees CCW from the x-axis. and if len(X) and len(Y) match the column and row dimensions of U.1. Y. e. the arrow size increases with the width and height of the axes. C. the arrow aspect ratio is 1. **kw) U. quiver(X. see pivot kwarg) U. V. they will be generated as a uniform grid. the arrows get larger as one zooms in. C may be masked arrays. V. V. U.y) to (x+u. quiver(U. Y. Alternatively.1 quiver(U. V. Release 1. or sqrt(X^2+Y^2) data units The arrows scale diﬀerently depending on the units. If U and V are 2-D arrays but X and Y are 1-D. or ‘xy’: X. then X and Y will be expanded with numpy. resizing does not change the arrows.

For example.0. based on the average vector length and the number of vectors. then the vector will be half the width of the axes. To plot vectors in the x-y plane. Default is 1. if an arrow length is less than this. Release 1. scale=1”. default depends on choice of units. make headaxislength the same as headlength. with u and v having the same units as x and y. scale is 2. PolyCollection keyword arguments: Property agg_filter alpha animated antialiased or antialiaseds array axes clim clip_box clip_on clip_path cmap Additional Description unknown ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib.5 inches long. width: shaft width in arrow units. scale down all the head parameters. color: [ color | color sequence ] This is a synonym for the PolyCollection facecolor kwarg. plot a dot (hexagon) of this diameter instead. To make the arrow more pointed. and number of vectors. You will probably do best to leave minshaft alone. pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point. and (u. linewidths and edgecolors can be used to customize the arrow outlines. To make the head smaller relative to the shaft. reduce headwidth or increase headlength and headaxislength. If C has been set. If scale_units is ‘x’ then the vector will be 0. The arrow length unit is given by the scale_units parameter scale_units: None. a typical starting value is about 0.5 x-axis units. The defaults give a slightly swept-back arrow.005 times the width of the plot. above.Bbox instance [True | False] [ (Path. hence the name pivot. use “angles=’xy’. or any of the units options. or small arrows will look terrible! Default is 1 minlength: scalar minimum length as a multiple of shaft width. then the vector will be 0.0. matplotlib axes 492 .v) = (1. Transform) | Patch | None ] a colormap or registered colormap name Continued on next page Chapter 36. in units of head length. default is 5 headaxislength: scalar head length at shaft intersection.transforms.1 is used. the arrow rotates about this point. scale_units=’xy’. to make the head a triangle. If scale_units is ‘width’. Do not set this to less than 1. color has no eﬀect.5 minshaft: scalar length below which arrow scales. headwidth: scalar head width as multiple of shaft width. if scale_units is ‘inches’. default is 4. default is 3 headlength: scalar head length as multiple of shaft width.Matplotlib.0).

matplotlib.Figure instance gid an id string label any string linestyle or linestyles or dashes [’solid’ | ‘dashed’. U. ‘dotted’ | (oﬀset.0.1. **kw) Arguments: Q: The Quiver instance returned by a call to quiver. Release 1.0 at the lower left corner. ‘inches’ is position in the ﬁgure in inches. label.figure. ‘data’ are the axes data coordinates (used for the locations of the vectors in the quiver plot itself). X.axes 493 .0 in the lower left and 1. ‘dashdot’. with 0. Y.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.Matplotlib. Y: The location of the key. X. 36.1 in the upper right. call signature: quiverkey(Q. U: The length of the key label: a string with the length and units of the key Keyword arguments: coordinates = [ ‘axes’ | ‘ﬁgure’ | ‘data’ | ‘inches’ ] Coordinate system and units for X.1 Table 36. Y: ‘axes’ and ‘ﬁgure’ are normalized coordinate systems with 0. on-oﬀ-dash-seq) ] linewidth or lw or linewidths ﬂoat or sequence of ﬂoats lod [True | False] norm unknown offsets ﬂoat or sequence of ﬂoats paths unknown picker [None|ﬂoat|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. additional explanation follows. **kw) Add a key to a quiver plot.

norm=None. etc are not updated) relim() Recompute the data limits based on current artists. marker=’o’. Collection instances are not supported. cmap=None. vmax=None. Keyword arguments: s: size in points^2. Y. matplotlib axes . X. Y is somewhere in the middle of the arrow+label key object. The positioning of the key depends on X.1 labelcolor: defaults to default Text color. N. Y positions the head.1 color: overrides face and edge colors from Q. marker: can be one of: 494 Chapter 36. labelsep: Distance in inches between the arrow and the label. Y give the position of the middle of the key arrow. faceted=True. labels. X. to the right. where x. linewidths=None. Release 1. If labelpos is ‘E’. and if labelpos is ‘W’. and labelpos. labelpos = [ ‘N’ | ‘S’ | ‘E’ | ‘W’ ] Position the label above. **kwargs) call signatures: scatter(x. weight by the Any additional keyword arguments are used to override vector properties taken from Q. variant. vmax=None. c can be a single color format string. reset_position() Make the original position the active position scatter(x. y are converted to 1-D sequences which must be of the same length. c: a color. 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. vmin=None. style. c can be a 2-D array in which the rows are RGB or RGBA. redraw_in_frame() This method can only be used after an initial draw which caches the renderer. If labelpos is ‘N’ or ‘S’. Y positions the tail. It is a scalar or an array of the same length as x and y. c=’b’. size. verts=None. **kwargs) Make a scatter plot of x versus y. y. X. respectively. alpha=None. however. c=’b’. or a sequence of N numbers to be mapped to colors using the cmap and norm speciﬁed via kwargs (see below).Matplotlib. below. cmap=None. or a sequence of color speciﬁcations of length N. norm=None. fontproperties: A dictionary with keyword arguments accepted FontProperties initializer: family. alpha=None. y. coordinates. At present. s=20. vmin=None. marker=’o’. It is used to eﬃciently update Axes data (axis ticks. to the left of the arrow. X. s=20. linewidths=None. Default is 0. verts=None.0. in either of these two cases.

0): verts is a sequence of (x. matplotlib. style.1. regular symbol. 1.0. alpha: 0 <= scalar <= 1 or None The alpha value for the patches 36.axes 495 . Note if you pass a norm instance. defaults to rc image. Alternatively. cmap is only used if c is an array of ﬂoats.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. If None. cmap: [ None | Colormap ] A matplotlib. Other keyword arguments: the color mapping and normalization arguments will be used only if c is an array of ﬂoats. s. y) vertices for a custom scatter symbol. Release 1. y.cmap. angle). use the kwarg combination marker = None. your settings for vmin and vmax will be ignored. use the default normalize(). norm is only used if c is an array of ﬂoats. Any or all of x. in which case all masks will be combined and only unmasked points will be plotted. 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. If None.Normalize instance is used to scale luminance data to 0. marker can be (verts.Colormap instance or registered name. verts = verts. and c may be masked arrays. which will create a custom. vmin/vmax: vmin and vmax are used in conjunction with norm to normalize luminance data. norm: [ None | Normalize ] A matplotlib. the min and max of the color array C is used.colors. If either are None.colors.Matplotlib.

matplotlib axes . on-oﬀ-dash-seq) ] ﬂoat or sequence of ﬂoats [True | False] unknown ﬂoat or sequence of ﬂoats unknown [None|ﬂoat|boolean|callable] unknown [True | False | None] unknown Transform instance a url string unknown [True | False] any number 496 Chapter 36.).figure. ‘dotted’ | (oﬀset. 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.Bbox instance [True | False] [ (Path. as required by RegularPolyCollection. Release 1. Note that this is a tuple.linewidth.0. in particular: edgecolors: The string ‘none’ to plot faces with no outlines facecolors: The string ‘none’ to plot unﬁlled 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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib. Optional kwargs control the Collection properties. ‘dashdot’.Figure instance an id string any string [’solid’ | ‘dashed’.1 linewidths: [ None | scalar | sequence ] If None.Matplotlib.transforms. and if you set the linewidths argument you must set it as a sequence of ﬂoats. defaults to (lines.

which depend on the number of decades in the plot.1.’ | ’.Figure instance [’full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’] an id string any string [ ’-’ | ’--’ | ’-.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’. None defaults to autosubs. **kwargs) call signature: semilogx(*args. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x.0 transparent through 1. Notable keyword arguments: basex: scalar > 1 base of the x logarithm subsx: [ None | sequence ] The location of the minor xticks.axes.set_xscale(). Release 1. see set_xscale() for details. y) or two 1D arrays [ ‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’ ] a matplotlib.axes 497 .Matplotlib.transforms. matplotlib. semilogx(*args. 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 ﬂoat (0. **kwargs) Make a plot with log scaling on the x axis.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points 36.1 A Collection instance is returned.Axes.0 opaque) [True | False] [True | False] an Axes instance a matplotlib. nonposx: [’mask’ | ‘clip’ ] non-positive values in x can be masked as invalid. semilogx() supports all the keyword matplotlib.0.figure.Bbox instance [True | False] [ (Path.

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 ﬂoat None | integer | (startind. which depend on the number of decades in the plot.Axes. nonposy: [’mask’ | ‘clip’ ] non-positive values in y can be masked as invalid. matplotlib axes .Matplotlib. stride) ﬂoat distance in points or callable pick function fn(artist.0 transparent through 1. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib. Release 1.Transform instance a url string [True | False] 1D array 1D array any number See Also: loglog() For example code and ﬁgure semilogy(*args.axes.0 opaque) arguments of plot() and 498 Chapter 36.set_yscale(). **kwargs) Make a plot with log scaling on the y axis. Notable keyword arguments: basey: scalar > 1 Base of the y logarithm subsy: [ None | sequence ] The location of the minor yticks. **kwargs) call signature: semilogy(*args. see set_yscale() for details. None defaults to autosubs. semilogy() supports all the keyword matplotlib.0.transforms. or clipped to a very small positive number The remaining valid kwargs are Line2D properties: Property agg_filter alpha Description unknown ﬂoat (0.

Transform instance a url string [True | False] 1D array 1D array any number See Also: loglog() For example code and ﬁgure 36.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.axes 499 . matplotlib.0.’ | ’. 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 [ ’-’ | ’--’ | ’-. stride) ﬂoat distance in points or callable pick function fn(artist.Matplotlib. Release 1. event) ﬂoat distance in points [True | False | None] unknown [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] a matplotlib.figure.’ | ’1’ | ’2’ | ’3’ | ’4’ | ’<’ | ’>’ | ’D’ | ’H’ | ’^’ | ’_’ | ’d’ | any matplotlib color ﬂoat value in points any matplotlib color any matplotlib color ﬂoat None | integer | (startind.transforms. Transform) | Patch | None ] any matplotlib color a callable function [’butt’ | ‘round’ | ‘projecting’] [’miter’ | ‘round’ | ‘bevel’] sequence of on/oﬀ ink in points 2D array (rows are x.’ | ’:’ | ’None’ | ’ ’ | ” ] and any drawstyle in combination with a ﬂoat value in points [True | False] [ ’+’ | ’*’ | ’.transforms.1.Bbox instance [True | False] [ (Path.

aspect=1 is the same as aspect=’equal’. anchor value ‘C’ ‘SW’ ‘S’ ‘SE’ etc.0. 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. Release 1. ﬁll position rectangle with data same as ‘auto’. For cases when sharing axes is ﬁne. 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’. use ‘box-forced’. as this can cause unintended side eﬀect. matplotlib axes .Matplotlib. 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. but axes can be shared description automatic.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. adjustable=None. ‘box’ does not allow axes sharing.

color) or: ax.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.see colors() set_axis_off() turn oﬀ 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.set_cursor_props((linewidth.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(linewidth. Release 1.ﬁgure. clist is a list of mpl color speciﬁers.Matplotlib. color)) ACCEPTS: a (ﬂoat. color) tuple set_figure(ﬁg) Set the class:~matplotlib.Axes ﬁgure accepts a class:~matplotlib.1. set_cursor_props(*args) Set the cursor property as: ax. matplotlib.axes 501 .0. set_axis_bgcolor(color) set the axes background color ACCEPTS: any matplotlib color .axes.

**kwargs): Set the title for the axes. which=’both’) Set the axes position with: pos = [left.1 set_navigate_mode(b) Set the navigation toolbar button status. width. and a second which is the starting point for apply_aspect().0. 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 ﬂoat (0. height] in relative 0. Optional keyword arguments: which value ‘active’ ‘original’ ‘both’ description to change the ﬁrst to change the second to change both set_rasterization_zorder(z) Set zorder value below which artists will be rasterized set_title(label. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.0 transparent through 1.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] 502 Chapter 36.Matplotlib. set_position(pos. Warning: this is not a user-API function.transforms. fontdict=None. or pos can be a Bbox There are two position variables: one which is ultimately used. matplotlib axes .font_manager. bottom. but which may be modiﬁed by apply_aspect().Bbox instance [True | False] [ (Path. **kwargs) call signature: set_title(label.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.1 coords.Figure instance a matplotlib. Release 1. fontdict=None.figure.

1 Table 36. matplotlib. This method will honor axes inversion regardless of parameter order. **kwargs) Set the label for the xaxis. fontdict=None. It will not change the _autoscaleXon attribute. 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’ | ﬂoat ﬂoat any number ACCEPTS: str See Also: text() for information on how override and the optional args work set_xbound(lower=None. labelpad=None. fontdict=None. labelpad=None. Release 1.axes 503 .0.Matplotlib. **kwargs) call signature: set_xlabel(xlabel. set_xlabel(xlabel. labelpad is the spacing in points between the label and the x-axis Valid kwargs are Text properties: 36.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 ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.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. upper=None) Set the lower and upper numerical bounds of the x-axis.

Figure instance a matplotlib.font_manager. Release 1. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.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 ﬂoat (0.figure. matplotlib axes .0.transforms.Bbox instance [True | False] [ (Path.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a 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.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’ | ﬂoat ﬂoat any number ACCEPTS: str See Also: 504 Chapter 36.Matplotlib.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.

**kwargs): Set the data limits for the xaxis Examples: set_xlim((left. For example. right=None. may still be used emit: [ True | False ] notify observers of lim change auto: [ True | False | None ] turn x autoscaling on (True). emit=True. **kwargs) call signature: set_xscale(value) Set the scaling of the x-axis: ‘linear’ | ‘log’ | ‘symlog’ ACCEPTS: [’linear’ | ‘log’ | ‘symlog’] Diﬀerent kwargs are accepted. the previous name. right) set_xlim(left=1) # right unchanged set_xlim(right=1) # left unchanged Keyword arguments: left: scalar the left xlim. may still be used right: scalar the right xlim. depending on the scale: ‘linear’ ‘log’ 36. **kw) call signature: set_xlim(self. or leave unchanged (None) Note: the left (formerly xmin) value may be greater than the right (formerly xmax). matplotlib. *args. m times the data interval will be added to each end of that interval before it is used in autoscaling. auto=False. xmax. right)) set_xlim(left. xmin. the previous name. suppose x is years before present.1. Release 1. oﬀ (False. Then one might use: set_ylim(5000.1 text() for information on how override and the optional args work set_xlim(left=None.axes 505 .Matplotlib. accepts: ﬂoat in range 0 to 1 set_xscale(value.0. 0) so 5000 years ago is on the left of the plot and the present is on the right. default). Returns the current xlimits as a length 2 tuple ACCEPTS: len(2) sequence of ﬂoats set_xmargin(m) Set padding of X data limits prior to autoscaling.

4. Release 1. For example.1 basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. 1. 2.Figure instance a matplotlib. 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 ﬂoat (0. 7.transforms. in a log10 scale: [0. 6. 8.font_manager. fontdict=None. 3. kwargs set the Text properties. 6. **kwargs) Set the xtick labels with list of strings labels. 1.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.Matplotlib. 7. 9] will place 10 logarithmically spaced minor ticks between each major tick. For example. Should be a sequence of integers. minor=False. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. set_xticklabels(labels. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. **kwargs) call signature: set_xticklabels(labels. 3.Bbox instance [True | False] [ (Path.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) 506 Chapter 36. x) within which the plot is linear (to avoid having the plot go to inﬁnity around zero). 5. 2. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick.0. matplotlib axes .0 transparent through 1. 9] will place 10 logarithmically spaced minor ticks between each major tick. 4. in a log10 scale: [0. Should be a sequence of integers. fontdict=None.figure. 8. minor=False. 5. Return a list of axis text instances. subsx/subsy: Where to place the subticks between each major tick.

1 Table 36. **kwargs) call signature: set_ylabel(ylabel.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|ﬂoat|boolean|callable] (x. minor=False) Set the x ticks with list of ticks ACCEPTS: sequence of ﬂoats set_ybound(lower=None. upper=None) Set the lower and upper numerical bounds of the y-axis. Release 1.Matplotlib. set_ylabel(ylabel.axes 507 . It will not change the _autoscaleYon attribute. fontdict=None. matplotlib.0. labelpad=None. 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’ | ﬂoat ﬂoat any number ACCEPTS: sequence of strings set_xticks(ticks.1. This method will honor axes inversion regardless of parameter order. fontdict=None. **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.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.

1 Table 36.Matplotlib.0.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.Bbox instance [True | False] [ (Path.font_manager.Figure instance a matplotlib. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. matplotlib axes . 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’ | ﬂoat ﬂoat any number ACCEPTS: str See Also: 508 Chapter 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 ﬂoat (0.transforms.0 transparent through 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.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.figure. Release 1.

Release 1. top) set_ylim(bottom=1) # top unchanged set_ylim(top=1) # bottom unchanged Keyword arguments: bottom: scalar the bottom ylim. **kw) call signature: set_ylim(self. **kwargs): Set the data limits for the yaxis Examples: set_ylim((bottom. matplotlib. is at the top. may still be used top: scalar the top ylim. oﬀ (False. depending on the scale: ‘linear’ ‘log’ 36. emit=True. top)) set_ylim(bottom. the previous name. m times the data interval will be added to each end of that interval before it is used in autoscaling. the previous name. may still be used emit: [ True | False ] notify observers of lim change auto: [ True | False | None ] turn y autoscaling on (True). **kwargs) call signature: set_yscale(value) Set the scaling of the y-axis: ‘linear’ | ‘log’ | ‘symlog’ ACCEPTS: [’linear’ | ‘log’ | ‘symlog’] Diﬀerent kwargs are accepted. auto=False. 0 m. ymin. ymax. Then one might use: set_ylim(5000. top=None.1 text() for information on how override and the optional args work set_ylim(bottom=None. or leave unchanged (None) Note: the bottom (formerly ymin) value may be greater than the top (formerly ymax).Matplotlib. default).axes 509 .0. accepts: ﬂoat in range 0 to 1 set_yscale(value. 0) so 5000 m depth is at the bottom of the plot and the surface. suppose y is depth in the ocean.1. *args. For example. Returns the current ylimits as a length 2 tuple ACCEPTS: len(2) sequence of ﬂoats set_ymargin(m) Set padding of Y data limits prior to autoscaling.

9] will place 10 logarithmically spaced minor ticks between each major tick.Matplotlib. 3. 2. For example. minor=False.1 basex/basey: The base of the logarithm nonposx/nonposy: [’mask’ | ‘clip’ ] non-positive values in x or y can be masked as invalid. 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 ﬂoat (0.Figure instance a matplotlib.Bbox instance [True | False] [ (Path. 8.figure. in a log10 scale: [0. Should be a sequence of integers. 9] will place 10 logarithmically spaced minor ticks between each major tick. in a log10 scale: [0. set_yticklabels(labels. minor=False. fontdict=None.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.0. 1. ‘symlog’ basex/basey: The base of the logarithm linthreshx/linthreshy: The range (-x. 5. 6. For example. Should be a sequence of integers. kwargs set Text properties for the labels.font_manager. Return a list of Text instances. 7.0 transparent through 1. fontdict=None. 5. 7. **kwargs) call signature: set_yticklabels(labels. 1. 2. 4. matplotlib axes . 3. **kwargs) Set the ytick labels with list of strings labels. 4. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. Release 1. subsx/subsy: Where to place the subticks between each major tick. 6. x) within which the plot is linear (to avoid having the plot go to inﬁnity around zero).FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) 510 Chapter 36. 8. or clipped to a very small positive number subsx/subsy: Where to place the subticks between each major tick.transforms.

scale_by_freq=None. cmap=None. noverlap=128.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|ﬂoat|boolean|callable] (x. detrend=<function detrend_none at 0x3a1c668>. pad_to=None. Data are split into NFFT length segments and the PSD of each section is computed. The windowing function window is applied to each segment. sides=’default’.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. Fc=0. xextent=None.1 Table 36. **kwargs) call signature: specgram(x.window_hanning. NFFT=256. Fs=2. minor=False) Set the y ticks with list of ticks ACCEPTS: sequence of ﬂoats Keyword arguments: minor: [ False | True ] Sets the minor ticks if True specgram(x. Fc=0. scale_by_freq=None. detrend=mlab. window=mlab.axes 511 . **kwargs) Compute a spectrogram of data in x. cmap=None. sides=’default’.detrend_none. NFFT=256. and the amount of overlap of each segment is speciﬁed with noverlap. window=<function window_hanning at 0x3a178c0>.1. Fs=2.0. 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’ | ﬂoat ﬂoat any number ACCEPTS: sequence of strings set_yticks(ticks. xextent=None. matplotlib. Keyword arguments: 36. pad_to=None. Release 1. noverlap=128.Matplotlib.

‘onesided’ forces the return of a one-sided PSD. pad_to: integer The number of points to which the data segment is padded when performing the FFT.Colormap instance. which returns one-sided for real data and both for complex data. If a function is passed as the argument. This corresponds to the n parameter in the call to ﬀt(). a power 2 is most eﬃcient. while ‘twosided’ forces two-sided.cm. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). scipy. where the detrend parameter is a vector. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes which sides of the PSD to return. The default is None. which speciﬁes the number of data points used. designed to remove the mean or linear trend. Fc: integer The center frequency of x (defaults to 0). numpy. scale_by_freq: boolean Speciﬁes whether the resulting density values should be scaled by the scaling frequency. This allows for integration over the returned frequency values. window_none(). numpy.signal. Must be even. The pylab module deﬁnes detrend_none(). matplotlib axes . The default value is 0 (no overlap). which oﬀsets the y extents of the plot to reﬂect the frequency range used when a signal is acquired and then ﬁltered and downsampled to baseband.bartlett(). in matplotlib is it a function. it must take a data segment as an argument and return the windowed version of the segment. bins. It is used to calculate the Fourier frequencies. freqs. scipy. Release 1. which gives density in units of Hz^-1.get_window().max(bins)). if None use default determined by rc xextent: The image extent along the x-axis. allowing for more detail. numpy. detrend_mean(). etc. To create window vectors see window_hanning().signal(). The default value is 256. window: callable or ndarray A function or a vector of length NFFT. cmap: A matplotlib.0. where bins is the return value from mlab. xextent = (xmin. im): •bins are the time points the spectrogram is calculated over 512 Chapter 36. The default value is 2. detrend: callable The function applied to each segment before ﬀt-ing. This can be diﬀerent from NFFT. The default is True for MATLAB compatibility. in cycles per time unit.Matplotlib.1 NFFT: integer The number of data points used in each block for the FFT. Fs: scalar The sampling frequency (samples per time unit). noverlap: integer The number of points of overlap between blocks. The default is window_hanning().xmax) The default is (0. and detrend_linear(). Default gives the default behavior.blackman().specgram() kwargs: Additional kwargs are passed on to imshow which makes the specgram image Return value is (Pxx. freqs. but you can use a custom function as well. this can give more points in the plot.hamming(). Unlike in MATLAB.

there is a special case: if precision is ‘present’. any value present in the array will be plotted. markersize=None. only the positive spectrum is shown.sparse.axes 513 . For scipy. If x is complex. matplotlib. If precision is 0.image.1.Matplotlib. Release 1. 36. aspect=’equal’.0. non-complex). This can be overridden using the sides keyword argument.e. both positive and negative parts of the spectrum are shown. Example: 3 2 1 0 1 2 30 1000 800 600 400 200 00 5 10 15 20 5 10 15 20 spy(Z. marker=None. **kwargs) call signature: spy(Z.spmatrix instances. any non-zero value will be plotted. else.AxesImage instance Note: If x is real (i. **kwargs) spy(Z) plots the sparsity pattern of the 2-D array Z. marker=None. aspect=’equal’. precision=0.1 •freqs is an array of frequencies •Pxx is a len(times) x len(freqs) array of power •im is a matplotlib. markersize=None. even if it is identically zero. values of |Z| > precision will be plotted. precision=0.

ListedColormap([’c’. x.g. button is the mouse button number: •1: LEFT •2: MIDDLE 514 Chapter 36.sparse. By default aspect is ‘equal’. or to any scalar number to specify the aspect ratio of an array element directly. useful kwargs include: •cmap •alpha See Also: imshow() For image options. If marker and markersize are None.spmatrix instances. use: cmap = mcolors.’ point •‘. set the aspect kwarg to ‘auto’ to allow the plot to ﬁll the plot box. and any remaining kwargs passed to the plot() method. so that each array element occupies a square space.0. with the ﬁrst index (row) increasing down and the second index (column) increasing to the right. Two plotting styles are available: image or marker. For controlling colors. Both are available for full arrays. e. an image will be returned and any remaining kwargs are passed to imshow().1 The array will be plotted as it would be printed. y are the mouse coordinates in display coords.Matplotlib. Release 1. cyan background and red marks. If marker and markersize are None. matplotlib axes . else. useful kwargs include: •marker •markersize •color Useful values for marker include: •‘s’ square (default) •‘o’ circle •‘. y.’r’]) If marker or markersize is not None. button) Called when a pan operation has started. a Line2D object will be returned with the value of marker determining the marker type. but only the marker style works for scipy.’ pixel See Also: plot() For plotting options start_pan(x.

linefmt=’b-‘. table(**kwargs) call signature: table(cellText=None. y. kwargs control the Table properties: 36. cellColours=None. rowColours=None.axes 515 . See Also: this document for details examples/pylab_examples/stem_plot.table. colLoc=’center’. bbox=None): Add a table to the current axes. cellLoc=’right’. **kwargs) Make a step plot. Additional keyword args to step() are the same as those for plot(). Returns a matplotlib. baseline). Release 1. rowLabels=None. stemlines. *args. y. basefmt=’r-‘) call signature: stem(x.0. use the Table class and add it to the axes with add_table(). For ﬁner grained control over tables.Matplotlib. linefmt=’b-’. markerfmt=’bo’. but not checked. basefmt=’r-’) A stem plot plots vertical lines (using linefmt) at each x location from the baseline to y. colColours=None. A horizontal line at 0 is is plotted using basefmt. *args. that x is uniformly increasing. the interval from x[i] to x[i+1] has level y[i+1] If ‘post’. rowLoc=’left’. Keyword arguments: where: [ ‘pre’ | ‘post’ | ‘mid’ ] If ‘pre’. that interval has level y[i] If ‘mid’. markerfmt=’bo’.Table instance. and it is assumed. Thanks to John Gill for providing the class and table. stem(x. y. the jumps in y occur half-way between the x-values. colLabels=None.1.1 •3: RIGHT Note: Intended to be overridden by new projection types. Return value is a tuple (markerline. x and y must be 1-D sequences. colWidths=None. matplotlib. loc=’bottom’. y. **kwargs) call signature: step(x. and places a marker there using markerfmt.py for a demo step(x.

withdash=False.5. matplotlib axes . **kwargs) call signature: text(x.Bbox instance [True | False] [ (Path. bbox is a dictionary of matplotlib.Matplotlib. 0. you can specify text in axis coords (0. y.Rectangle properties. fontdict=None.figure. fontsize=12) The default transform speciﬁes that text is in data coords. transform = ax. Transform) | Patch | None ] a callable function a matplotlib. fontdict=None. s. Release 1. The example below places text in the center of the axes: text(0. If fontdict is None.0 is lower-left and 1.Figure instance a ﬂoat in points an id string any string [True | False] [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number text(x. s. to set a background color) by using the keyword bbox. the defaults are determined by your rc parameters.patches.’matplotlib’. s. y. **kwargs) Add text in string s to axis at location x.0. withdash: [ False | True ] Creates a TextWithDash instance instead of a Text instance. data coordinates.transforms. For example: 516 Chapter 36.1 is upper-right).5. y. horizontalalignment=’center’. Keyword arguments: fontdict: A dictionary to override the default text properties.0 transparent through 1.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 ﬂoat (0.transAxes) You can put a rectangular box around the text instance (eg.0 opaque) [True | False] an Axes instance a matplotlib. alternatively. verticalalignment=’center’. y. Individual keyword arguments can be used to override any given parameter: text(x.

5)) Valid kwargs are 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.text. Release 1. matplotlib.0.transforms.figure. alpha=0. bbox=dict(facecolor=’red’. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib.1 text(x.0 transparent through 1. s. y.font_manager.Bbox instance [True | False] [ (Path.Matplotlib.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib.Figure instance a matplotlib.axes 517 .FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.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 ﬂoat (0. 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’ | ﬂoat ﬂoat any number 36.1.

bottom. top. pair of integers. colors Changes the tick color and the label color to the same value: mpl color spec. color Tick color. which [’major’ | ‘minor’ | ‘both’] Default is ‘major’: apply arguments to major ticks only. Tick labels will also be red. Optional keyword arguments: Keyword style scilimits useOﬀset axis Description [ ‘sci’ (or ‘scientiﬁc’) | ‘plain’ ] plain turns oﬀ scientiﬁc notation (m. [ ‘x’ | ‘y’ | ‘both’ ] 518 Chapter 36. ‘large’). set all parameters to defaults before processing other keyword arguments. labelsize Tick label font size in points or as a string (e. labelleft.Matplotlib. default is ‘both’. length=6.1 tick_params(axis=’both’. mpl color spec. colors=’r’) This will make all major ticks be red. [True | False | oﬀset]. the oﬀset will be calculated as needed. if style is ‘sci’. ticklabel_format(**kwargs) Convenience method for manipulating the ScalarFormatter used by default for linear axes. right Boolean or [’on’ | ‘oﬀ’]. labeltop. if False. Default is False. if True.tick_params(direction=’out’.g. n). scientiﬁc notation will be used for numbers outside the range 10‘-m‘:sup: to 10‘n‘:sup:. accepts any mpl color spec. if a numeric oﬀset is speciﬁed. length Tick length in points. zorder Tick and label zorder. **kwargs) Convenience method for changing the appearance of ticks and tick labels. Keyword arguments: axis [’x’ | ‘y’ | ‘both’] Axis on which to operate. width Tick width in points. reset [True | False] If True. controls whether to draw the respective ticks. no oﬀset will be used. direction [’in’ | ‘out’] Puts ticks inside or outside the axes. controls whether to draw the respective tick labels.0) to include all numbers. it will be used. width=2. labelcolor Tick label color. labelright Boolean or [’on’ | ‘oﬀ’]. and with dimensions 6 points by 2 points. left. matplotlib axes . Release 1. pointing out of the box. Use (0.0. labelbottom. pad Distance in points between tick and label. Example: ax.

. The remaining arguments may be: tricontour(. . Z.. Release 1. see below for more details. either: tricontour(triangulation. See Triangulation for a explanation of these possibilities. Except as noted.. Z..) mask=mask... tricontour(x. ..... all levels will be plotted in this color. like ‘r’ or ‘red’. y.. N) contour N automatically-chosen levels.... If the method is called when the ScalarFormatter is not the Formatter being used.) where triangulation is a Triangulation object. Z. the colormap speciﬁed by cmap will be used. mask.. If a string. tricontour(x.) in which case a Triangulation object will be created...axes 519 .. an AttributeError will be raised... **kwargs) Use keyword args to control colors. 36. **kwargs) tricontour() and tricontourf() draw contour lines and ﬁlled contours... origin.) triangles. Optional keyword arguments: colors: [ None | string | (mpl_colors) ] If None. tricontour(x..0.. tricontour(*args. . cmap . y.) triangles. mask=mask. V) draw contour lines at the values speciﬁed in sequence V tricontourf(. one per point in the triangulation. tricontour(x. matplotlib... . function signatures and return values are the same for both versions. y.. V) ﬁll the (len(V)-1) regions between the values in V tricontour(Z. y. .) triangles=triangles.Matplotlib. .1 Only the major ticks are aﬀected.. tricontour(x. The level values are chosen automatically. or tricontour(x. y. The triangulation can be speciﬁed in one of two ways.1. y. C = tricontour(. . y. respectively. tricontour(.) returns a TriContourSet object. tricontour(x. tricontour(. linewidth.) triangles...) mask.. Z) where Z is the array of values to contour.. . on an unstructured triangular grid.

colors. In this case. . This keyword is not active if X and Y are speciﬁed in the call to contour.. y0) is the position of Z[0. If origin is None. matplotlib axes . If cmap is None and colors is None. levels [level0.origin will be used. the rc value for image. a default Colormap is used. not a corner. the position of Z[0. all levels will be plotted with this linewidth.pyplot. etc).y1) ] If origin is not None. xunits.colors.y0.0] is the center of the pixel. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’. tricontour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None.Locator subclass ] If locator is None. diﬀerent levels will be plotted in diﬀerent colors in the order speciﬁed.colors.. then (x0. locator: [ None | ticker.0).. If a number. Release 1. leveln] A list of ﬂoating point numbers indicating the level curves to draw.0]. ﬂoat. but can be set via matplotlib. the default linear scaling is used.imshow(): it gives the outer pixel boundaries. location (0.x1. the ﬁrst value of Z will correspond to the lower left corner. alpha: ﬂoat The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None.linewidth in matplotlibrc is used.Matplotlib. rgb. y1) is the position of Z[-1.set_over() methods. then extent is interpreted as in matplotlib.ConversionInterface.Colormap.Normalize instance for scaling data values to colors. the default width in lines. norm: [ None | Normalize ] A matplotlib.0. This keyword is not active if X and Y are speciﬁed in the call to contour. diﬀerent levels will be plotted with diﬀerent linewidths in the order speciﬁed 520 Chapter 36. The locator is used to determine the contour levels if they are not given explicitly via the V argument. contour levels are automatically added to one or both ends of the range so that all data are included. If a tuple. eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None. and (x1.Colormap. If ‘image’. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib. extent: [ None | (x0.-1].1 If a tuple of matplotlib color args (string.units. the default MaxNLocator is used. If norm is None and colors is None. level1.set_under() and matplotlib.

negative_linestyle in matplotlibrc will be used. no subdivision of the domain.. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points. tricontourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0. . Release 1. y.. The triangulation can be speciﬁed in one of two ways. . y. Examples: tricontourf(*args.. y.. See Triangulation for a explanation of these possibilities. for boundaries z1 and z2. so this option may be removed..1 linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. tricontour(x. that is. Note: tricontourf ﬁlls intervals that are closed at the top. . **kwargs) tricontour() and tricontourf() draw contour lines and ﬁlled contours. . .. on an unstructured triangular grid.) triangles. the ﬁlled region is: z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array.) in which case a Triangulation object will be created.. then the linestyle speciﬁed in contour. y. If contour is using a monochrome colormap and the contour level is less than 0... function signatures and return values are the same for both versions. matplotlib. tricontour(x. or tricontour(x.) mask=mask. tricontour(x. ...) triangles... . mask=mask.) triangles. The remaining arguments may be: 36.1. . This may never actually be advantageous.) where triangulation is a Triangulation object.axes 521 . tricontour(x.. tricontour(x. tricontour(x. y. y. Chunking introduces artifacts at the chunk boundaries unless antialiased is False. y. then that minimum value will be included in the lowest interval... 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. Except as noted. either: tricontour(triangulation. the ‘solid’ is used.0.Matplotlib.) mask. mask. respectively.) triangles=triangles.

. Z.00 0..75 1. cmap .00 tricontour(. N) contour N automatically-chosen levels.5 0...5 0...0 0. one per point in the triangulation. Z..0 0. linewidth. see below for more details..0 0.5 1. C = tricontour(.Matplotlib. tricontour(. tricontour(.0 0. The level values are chosen automatically.25 0.25 0.. V) ﬁll the (len(V)-1) regions between the values in V tricontour(Z. V) draw contour lines at the values speciﬁed in sequence V tricontourf(.00 1.50 0. Release 1. Z.) returns a TriContourSet object.50 0..0..01. origin.. Z) where Z is the array of values to contour... Optional keyword arguments: 522 Chapter 36..5 1.1 Contour plot of Delaunay triangulation 1. **kwargs) Use keyword args to control colors..75 0.0 0. matplotlib axes .

. If ‘image’.75 0. the rc value for image.60 colors: [ None | string | (mpl_colors) ] If None.1 Contour plot of user-specified triangulation 1. the colormap speciﬁed by cmap will be used.Matplotlib. .90 0. levels [level0. etc). eg to draw just the zero contour pass levels=[0] origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None. matplotlib.70 0. Release 1. like ‘r’ or ‘red’. If norm is None and colors is None.y1) ] 36. If a tuple of matplotlib color args (string. This keyword is not active if X and Y are speciﬁed in the call to contour.65 0.axes 523 . a default Colormap is used. location (0. norm: [ None | Normalize ] A matplotlib. If a string.x1. rgb.85 0. the ﬁrst value of Z will correspond to the lower left corner.0). diﬀerent levels will be plotted in diﬀerent colors in the order speciﬁed. ﬂoat.origin will be used.1. the default linear scaling is used. extent: [ None | (x0.0.. alpha: ﬂoat The alpha blending value cmap: [ None | Colormap ] A cm Colormap instance or None..y0. all levels will be plotted in this color.Normalize instance for scaling data values to colors.80 0. level1.95 0.colors. If cmap is None and colors is None.00 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) 0. leveln] A list of ﬂoating point numbers indicating the level curves to draw.

all levels will be plotted with this linewidth. then (x0. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range. Release 1.negative_linestyle in matplotlibrc will be used. yunits: [ None | registered units ] Override axis units by specifying an instance of a matplotlib.0. xunits. diﬀerent levels will be plotted with diﬀerent linewidths in the order speciﬁed linestyles: [None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles is None. the ﬁlled region is: 524 Chapter 36. This may never actually be advantageous. Note: tricontourf ﬁlls intervals that are closed at the top.Matplotlib. contour levels are automatically added to one or both ends of the range so that all data are included.Colormap. so this option may be removed.ConversionInterface. If a tuple. no subdivision of the domain. y1) is the position of Z[-1. not a corner. then extent is interpreted as in matplotlib. the default width in lines. for boundaries z1 and z2. linestyles can also be an iterable of the above strings specifying a set of linestyles to be used. If contour is using a monochrome colormap and the contour level is less than 0.pyplot.units.set_under() and matplotlib.imshow(): it gives the outer pixel boundaries. If a number. If origin is None.1 If origin is not None. extend: [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’. Specify a positive integer to divide the domain into subdomains of roughly nchunk by nchunk points.linewidth in matplotlibrc is used. the position of Z[0. locator: [ None | ticker. 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. but can be set via matplotlib. the default MaxNLocator is used.-1].Colormap.colors.colors. tricontour-only keyword arguments: linewidths: [ None | number | tuple of numbers ] If linewidths is None.Locator subclass ] If locator is None. and (x1. tricontourf-only keyword arguments: antialiased: [ True | False ] enable antialiasing nchunk: [ 0 | integer ] If 0.0] is the center of the pixel. then the linestyle speciﬁed in contour. that is. This keyword is not active if X and Y are speciﬁed in the call to contour. In this case. matplotlib axes .set_over() methods. the ‘solid’ is used. The locator is used to determine the contour levels if they are not given explicitly via the V argument. y0) is the position of Z[0.0].

.. tripcolor(x..Matplotlib.) in which case a Triangulation object will be created. tripcolor(x. .) mask=mask.50 0.5 0. y. .5 1...) where triangulation is a Triangulation object. y.75 0.) triangles=triangles. or tripcolor(x. y. The triangulation can be speciﬁed in one of two ways. 36.50 0. matplotlib..axes 525 . y.0 0. tripcolor(x. either: tripcolor(triangulation..00 0.00 1.0 0.. . ..5 1. Release 1.0 0..01. tripcolor(x.00 tripcolor(*args.25 0. mask.0 0. tripcolor(x. . See Triangulation for a explanation of these possibilities. .1 z1 < z <= z2 There is one exception: if the lowest boundary coincides with the minimum value of the z array. y. . Examples: Contour plot of Delaunay triangulation 1.) mask... **kwargs) Create a pseudocolor plot of an unstructured triangular grid to the Axes.) triangles. .) triangles. tripcolor(x..0 0.75 1. y..25 0. then that minimum value will be included in the lowest interval. y..) triangles. mask=mask.1.0..5 0.

. Example: triplot(*args.. triplot(x. .00 58 Latitude (degrees) 56 54 52 50 7 6 5 4 3 2 1 0 1 2 Longitude (degrees) 0. triplot(x. triplot(x. triplot(x.. y. The colors used for each triangle are from the mean C of the triangle’s three points.. Release 1.) where triangulation is a Triangulation object...70 0.. **kwargs) Draw a unstructured triangular grid as lines and/or markers to the Axes.. .) triangles.65 0.75 0. triplot(x. y. y. . y. mask.. or triplot(x.1 Contour plot of user-specified triangulation 1. . .) mask=mask.80 0. y. y. triplot(x. The triangulation to plot can be speciﬁed in one of two ways. The remaining kwargs are the same as for pcolor().90 0. one per point in the triangulation.. ..60 The next argument must be C. . y.) mask.. .95 0.0.) 526 Chapter 36.) triangles. matplotlib axes . either: triplot(triangulation. the array of color values. mask=mask....Matplotlib..85 0.) triangles.) triangles=triangles.

1 1. 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.0 0.0 0. Release 1.0 0.1.6 0. Example: twinx() call signature: ax = twinx() create a twin of Axes for generating a plot with a sharex x-axis but independent y axis. See Triangulation for a explanation of these possibilities.4 0.8 in which case a Triangulation object will be created.2 0.5 1.Matplotlib.5 0. The remaining args and kwargs are the same as for plot().5 1. updatex=True.2 0.axes 527 .0 0. 2-D array 36.01.0 tripcolor of Delaunay triangulation 0.0. matplotlib.8 0.0 0. 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.6 0. updatey=True) Update the data lim bbox with seq of xy tups or equiv.5 0.

80 0. ymax.92 0. linestyles=’solid’.68 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. color=’k’. else the heights of the lines are determined by ymin and ymax. ymin or ymax can be scalars or len(x) numpy arrays. either a single color or a len(x) list of colors linestyles one of [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] Returns the matplotlib. ymax.64 Plot vertical lines at each x from ymin to ymax.72 0. matplotlib axes . If they are scalars.88 0.96 0.0.collections.LineCollection that was added. linestyles=’solid’) 0.76 0. then the respective values are constant.84 0. colors=’k’. ymin. Release 1. colors a line collections color args.Matplotlib. kwargs are LineCollection properties: Continued on next page 528 Chapter 36. **kwargs) call signature: vlines(x. label=’‘. ymin.

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 ﬂoat or None [True | False] Boolean or sequence of booleans unknown an Axes instance a length 2 sequence of ﬂoats a matplotlib. ‘dotted’ | (oﬀset. on-oﬀ-dash-seq) ] ﬂoat or sequence of ﬂoats [True | False] unknown ﬂoat or sequence of ﬂoats unknown [None|ﬂoat|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. 36. matplotlib.axes 529 .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.1 Table 36.0. ‘dashdot’. Defaults to rc value.Bbox instance [True | False] [ (Path. tz is the time zone to use in labeling dates.Figure instance an id string any string [’solid’ | ‘dashed’. Release 1. xaxis_inverted() Returns True if the x-axis is inverted.transforms.figure.Matplotlib.

correlate() with mode = 2.0 0. usevlines=True. normed=True. **kwargs): Plot the cross correlation between x and y. x and y must be equal length. The cross correlation is performed with numpy. detrend=<function detrend_none at 0x3a1c668>. maxlags=10. normalize the data by the cross correlation at 0-th lag. y. If normed = True. **kwargs) Return value is a tuple (lags.0 0. normed=True. matplotlib axes . detrend=mlab. If usevlines is True: vlines() rather than plot() is used to draw vertical lines from the origin to the xcorr.0 xcorr(x. Data are plotted as plot(lags.0 0.5 1.0. x and y are detrended by the detrend callable (default no normalization). 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().detrend_none.1 1.01.5 triplot of Delaunay triangulation 1. 530 Chapter 36.5 0. c. **kwargs) call signature: def xcorr(self.5 0. though these can be overridden with keyword args. The default linestyle is None and the default marker is ‘o’. c. Release 1. maxlags=10. y.0 0. usevlines=True.Matplotlib. x.

collections.0.SubplotBase(ﬁg.1. which are Axes instances with additional methods to facilitate generating and 36. matplotlib.Matplotlib. The default value of None will return all (2*len(x)-1) lags. Defaults to rc value. and acorr() below. matplotlib. c. **kwargs) Base class for subplots.axes. Release 1.axes. Example: yaxis_date(tz=None) Sets up y-axis ticks and labels that treat the y data as dates. .Subplot alias of AxesSubplot class matplotlib. which are Line2D properties.1 triplot of user-specified triangulation 58 Latitude (degrees) Example: xcorr() above. b) where linecol is the matplotlib. maxlags is a positive integer detailing the number of lags to show. *args.LineCollection instance and b is the x-axis.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. tz is the time zone to use in labeling dates. yaxis_inverted() Returns True if the y-axis is inverted. The return value is a tuple (lags. linecol.

0 0.4 0. plotNum starts at 1 in the upper left corner and increases to the right. num) change subplot geometry.260 40 20 0 20 40 60 40 20 0 20 40 60 manipulating a set of Axes within a ﬁgure. from 1. args can be the decimal integer numRows * 100 + numCols * 10 + plotNum.10 0. change_geometry(numrows.1 0. args is the tuple (numRows.2 0.figure. numcols. numCols.1 to 2. ﬁg is a matplotlib.0 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.2.Figure instance.15 0. numCols. where the array of subplots in the ﬁgure has dimensions numRows. and where plotNum is the number of the subplot being created. eg.0. Release 1. plotNum).15 0. matplotlib axes .2060 1.8 0.3 get_geometry() get the subplot geometry.05 0.6 0. If numRows <= numCols <= plotNum < 10.10 0.05 0. eg 2.00 0.Matplotlib.2.20 0.1.

See also: set_color_cycle().Matplotlib. Release 1.1.subplot_class_factory(axes_class=None) 36. Set rcParams[’axes. matplotlib. clist is a sequence of mpl color speciﬁers. Note: Deprecated 2010/01/03.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 ﬁrst column set_subplotspec(subplotspec) set the SubplotSpec instance associated with the subplot update_params() update the subplot position from ﬁg.set_default_color_cycle(clist) Change the default cycle of colors that will be used by the plot command. it will apply to all future axes.axes.subplotpars matplotlib.axes 533 .0.color_cycle’] directly. This must be called before creating the Axes to which it will apply. matplotlib.axes.

Release 1.0.1 534 Chapter 36. matplotlib axes .Matplotlib.

grid lines.Axis(axes. pickradius=15) Bases: matplotlib.transform axis coords to display coords •labelpad .transData .Artist Public attributes •axes.1 matplotlib.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. renderer.CHAPTER THIRTYSEVEN MATPLOTLIB AXIS 37. 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 . **kwargs) Draw the axis lines.axis. *args.transAxes .artist. cla() clear the current axis convert_units(x) draw(artist.axis Classes for the ticks and x and y axis class matplotlib.transform data coords to display coords •axes.

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.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. 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 oﬀsetText 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. matplotlib axis .Matplotlib. 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.

the x coordinate of the y label is determined by the tick label bounding boxes. but this can lead to poor alignment of multiple ylabels if there are multiple axes.axis 537 . limit_range_for_scale(vmin. If kwargs are supplied. kwargs are used to set the line properties of the grids. 0. Use which = ‘major’ | ‘minor’ | ‘both’ to set the grid for major or minor ticks. b is a boolean. xax. which=’major’. linestyle=’-‘. By default. **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. If b is None and len(kwargs)==0. etc set_label_text(label. it is assumed you want the grid on and b will be set to True. linewidth=2) have_units() iter_ticks() Iterate through all of the major and minor ticks. eg.Matplotlib. You can also specify the coordinate system of the label with the transform. transform=None) Set the coordinates of the label.5. vmax) pan(numsteps) Pan numsteps (can be positive or negative) reset_ticks() set_clip_path(clippath.0. 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. toggle the grid state.grid(color=’r’. y.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. the default coordinate system will be the axes coordinate system (0.bottom). fontdict=None. If None. Release 1. (0.5) is middle. matplotlib.0) is (left.1. **kwargs) Set the axis grid on or oﬀ. Ditto for the y coodinate of the x label.

axes.Matplotlib. For documentation of keyword arguments. As for get_ticklabels. regardless of the state of label1On and label2On. **kwargs) Set the text values of the tick labels. The list of returned label text objects consists of all such label1 objects followed by all such label2 objects. vmax. ACCEPTS: sequence of strings set_ticks(ticks. label1 (left or bottom) is aﬀected for a given tick only if its label1On attribute is True. The input ticklabels is assumed to match the set of tick locations. matplotlib axis . set_ticklabels(ticklabels.tick_params(). **kwargs) set_smart_bounds(value) set the axis to have smart bounds set_tick_params(which=’major’. Return a list of Text instances. reset=False. All other kwargs are used to update the text object properties. **kw) Set appearance parameters for ticks and ticklabels. Use kwarg minor=True to select minor ticks.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.0.Axes. and similarly for label2. see matplotlib. minor=False) Set the locations of the tick marks from sequence ticks ACCEPTS: sequence of ﬂoats set_units(u) set the units for axis ACCEPTS: a units tag set_view_interval(vmin. *args. ignore=False) 538 Chapter 37. Release 1.

size=None.1. draw(artist.Matplotlib. Release 1.0. **kwargs) get_children() get_loc() Return the tick location (data coords) as a scalar 37. matplotlib. Return True is data is registered for unit conversion zoom(direction) Zoom in/out on axis. zorder=None.converter instance if necessary.axis. loc. pad=None. label2On=False. tickdir=None. label1On=True. color=None. 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. tick1On=True. major=True) Bases: matplotlib. width=None. tick2On=True. *args. This function always returns false.axis 539 . else zoom out class matplotlib.artist. renderer.Artist Abstract base class for the axis ticks. if direction is >0 zoom in.1 update_units(data) introspect data for units converter and update the axis.Tick(axes. gridOn=None. labelsize=None. labelcolor=None. label._pad and self. 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.

0. vmax. to remove the clipping path For eﬃciency. which may be: •a Patch (or subclass) instance •a Path instance.Ticker class matplotlib. this method will set the clipping box to the corresponding rectangle and set the clipping path to None.axis. transform=None) Set the artist’s clip path. if the path happens to be an axis-aligned rectangle.XAxis(axes.axis.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. Release 1.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.Matplotlib. pickradius=15) Bases: matplotlib. which will be applied to the path before using it for clipping. ignore=False) class matplotlib. matplotlib axis .axis. 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: ﬂoat set_view_interval(vmin. •None. ACCEPTS: [ (Path. in which case an optional Transform instance may be provided.

default or none) both sets the ticks to appear on both positions. 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. the order of vmin. ignore=False) If ignore is False. labelcolor=None. ‘none’ can be used if you don’t want any ticks. ‘none’ and ‘both’ aﬀect only the ticks.Tick Contains all the Artists needed to make an x tick . tick_bottom() use ticks only on bottom tick_top() use ticks only on top class matplotlib. vmax. size=None.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. below) get_ticks_position() Return the ticks position (top. loc.0. pad=None. width=None. zorder=None. the original axis orientation will be preserved. tickdir=None. 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. label. tick1On=True. labelsize=None. vmax. color=None.the tick line. label1On=True. but does not change the tick labels. gridOn=None. bottom. ‘default’ resets the tick positions to the default: ticks on both positions. Release 1.1. Returns a tuple (above. both. ACCEPTS: [ ‘top’ | ‘bottom’ | ‘both’ | ‘default’ | ‘none’ ] set_view_interval(vmin. not the labels.axis 541 . major=True) Bases: matplotlib.XTick(axes.axis. labels at bottom. default or unknown) get_view_interval() return the Interval instance for this axis view limits set_data_interval(vmin. bottom. vmax does not matter. label2On=False. matplotlib.axis.Matplotlib. tick2On=True.

Axis Init the axis with the parent Axes instance contains(mouseevent) Test whether the mouse event occurred in the y axis. vmax. vmax. both or unknown) get_view_interval() return the Interval instance for this axis view limits set_data_interval(vmin.axis. 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. not the labels. pickradius=15) Bases: matplotlib.Matplotlib. labels at left. 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. but does not change the tick labels.YAxis(axes. ‘default’ resets the tick positions to the default: ticks on both positions. right. both. ‘none’ and ‘both’ aﬀect only the ticks. ignore=False) update_position(loc) Set the location of tick in data coords with scalar loc class matplotlib. matplotlib axis . Release 1.0. ‘none’ can be used if you don’t want any ticks.axis. right.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. 542 Chapter 37. default or none) ‘both’ sets the ticks to appear on both positions.

axis 543 . gridOn=None.axis. Release 1. labelsize=None. the order of vmin.Tick Contains all the Artists needed to make a Y tick .0.Matplotlib.axis.the tick line. tick_left() use ticks only on left tick_right() use ticks only on right class matplotlib. pad=None. width=None. ignore=False) If ignore is False.1 ACCEPTS: [ ‘left’ | ‘right’ | ‘both’ | ‘default’ | ‘none’ ] set_view_interval(vmin. 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. size=None. zorder=None. tick1On=True. ignore=False) update_position(loc) Set the location of tick in data coords with scalar loc 37. the original axis orientation will be preserved. tick2On=True. labelcolor=None.1. label. vmax does not matter. loc. label2On=False. tickdir=None.YTick(axes. vmax. major=True) Bases: matplotlib. label1On=True. color=None. vmax. matplotlib.

Matplotlib.1 544 Chapter 37. Release 1.0. matplotlib axis .

cbook. Whenever you want to group a few variables: >>> point = Bunch(datum=2. x def ondrink(x): print ’drink’.process(’drink’. ondrink) # this will raise a ValueError callbacks. a dictionary’s OK for that. squared=4.CHAPTER THIRTYEIGHT MATPLOTLIB CBOOK 38. 456) callbacks.Bunch(**kwds) Often we want to just collect a bunch of stuﬀ together. naming each item of the bunch.com/ASPN/Cookbook/Python/Recipe/52308 class matplotlib.activestate.connect(’drink’. ’drink’.connect(’eat’. 456) callbacks.process(’eat’.cbook.1 matplotlib.process(’eat’.nothing class is even handier.datum By: Alex Martelli From: http://aspn.CallbackRegistry(signals) Handle registering and disconnecting for a set of signals and callbacks: signals = ’eat’. 456) # # # # # will call oneat will call ondrink nothing will be called disconnect oneat nothing will be called 545 .connect(’drunk’. and prettier to use. coord=12) >>> point. x callbacks = CallbackRegistry(signals) ideat = callbacks. ondrink) #tmp = callbacks.process(’be merry’.cbook A collection of utility functions and classes. but a small do. ’be merry’ def oneat(x): print ’eat’. oneat) iddrink = callbacks.disconnect(ideat) callbacks. 123) callbacks. Many (but not all) from the Python Cookbook – hence the name cbook class matplotlib.

This technique was shared by Peter Parente on his “Mindtrove” blog. it is rather diﬃcult to place this kind of code. we instead store weak references to bound methods only. s): .... e.cbook. d.cbook. def __repr__(self): . def __init__(self. The objects being joined must be hashable and weak-referenceable.s = s . one should always disconnect all callbacks when they are no longer needed to avoid dangling references (and thus memory leaks). 2006 IBM Corporation @license: The BSD License Minor bugﬁxes by Michael Droettboom CallbackRegistry.Matplotlib. so when the destination object needs to die. c.process(s. 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. Stores a weak reference to the instance to support garbage collection. tested for connectedness using joined().GetRealpathAndStat class matplotlib.. func) register func to be called when a signal s is generated func will be called CallbackRegistry. and prevent this class of memory leaks. self..connect(s. Objects can be joined using join(). the CallbackRegistry won’t keep it alive. @organization: IBM Corporation @copyright: Copyright (c) 2005... so we need to create a proxy object to handle weak references to bound methods (or regular free functions).0.disconnect(cid) disconnect the callback registered with callback id cid CallbackRegistry. matplotlib cbook . real code in matplotlib rarely does so. class. For example: >>> class Foo: . **kwargs) process signal s. The Python stdlib weakref module can not create weak references to bound methods directly.. and due to its design.s . and instance out of a bound method. However. >>> a. and all disjoint sets can be retreived by using the object as an iterator... To get around this.1 In practice. return self. Release 1. 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.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. Pulls information about the function. *args. b.

including itself.cbook 547 .cbook.joined(a. class matplotlib. d) False clean() Clean dead weak references from the dictionary get_siblings(a) Returns all of the items joined with a. joined(a.join(b. e].join(d.Null(*args. isub=1. b) Returns True if a and b are members of the same set. c]] >>> g.Scheduler Schedule callbacks when scheduler is idle run() class matplotlib. isub=1) class matplotlib.cbook. matplotlib.0.Scheduler Bases: threading. **kwargs) Null objects always and reliably “do nothing. [a.1 >>> g.cbook.joined(a. b.RingBuffer(size_max) class that implements a not-yet-full buﬀer append(x) append an element at the end of the buﬀer get() Return a list of elements from the oldest to the newest.joined(a. join(a.cbook.Idle(func) Bases: matplotlib.Matplotlib. class matplotlib.MemoryMonitor(nmax=20000) clear() plot(i0=0. c) >>> g. b) True >>> g.” class matplotlib. b) >>> g.1. *args) Join given arguments into the same set.cbook.join(a. c) True >>> g.Thread 38. Release 1. Accepts one or more arguments. ﬁg=None) report(segments=4) xy(i0=0.cbook. e) >>> list(g) [[d.

3)] dict = [{’a’: 3. ’a’) # default sort # sort by index 1 # sort a list of dicts by key ’a’ byAttribute(data.all elements occurring later than the current position are discarded remove(o) remove element o from the stack 548 Chapter 38. 8).cbook. itemindex=None. inplace=1) class matplotlib. ’b’: 2}. 1) sort(dict. {’a’: 0.Matplotlib. itemindex=None.cbook. {’a’: 5.1 Base class for timeout and idle scheduling stop() class matplotlib. ’b’: 4}.Stack(default=None) Bases: object Implement a stack where elements can be pushed on and you can move back and forth. inplace=1) byItem(data. (0. ’b’: 0}. o must be in the stack clear() empty the stack empty() forward() move the position forward and return the current element home() push the ﬁrst element onto the top of the stack push(o) push object onto stack at current position . 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.0. ’b’: 9}] sort(list) sort(list. inplace=1) sort(data.Sorter Sort by attribute or item Example usage: sort = Sorter() list = [(1. {’a’: 9. (4. But no pop. matplotlib cbook . Release 1. attributename. 2).

cbook.Scheduler Schedule recurring events with a wait time in seconds run() class matplotlib.0. matplotlib. "Perl" : "Python". remove_stale_files() Remove ﬁles from the cache directory that are not listed in cache. The ﬁle cache. headers) Store a received ﬁle in the cache directory.Matplotlib. cache_file(url. data.1 class matplotlib.1.pck holds the directory of ﬁles that have been cached. If it does not exist. msg. http_response(req. fetch it with urllib from the svn repo and store it in the cachedir. Else the path to the ﬁle as a string will be returned.cbook 549 . If asﬁleobj is True. get_sample_data(fname.Timeout(wait. } 38.cbook.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". code. "creator" : "Benevolent Dictator for Life".BaseHandler Urllib2 handler that takes care of caching ﬁles. asﬁleobj=True) Check the cachedirectory for a sample_data ﬁle.pck. class matplotlib. http_request(req) Make the request conditional if we have a cached ﬁle. a ﬁle object will be returned. in_cache_dir(fn) read_cache() Read the cache ﬁle from the cache directory. fp. Release 1.cbook. write_cache() Write the cache data structure into the cache directory.ViewVCCachedServer(cache_dir. func) Bases: matplotlib. response) Update the cache with the returned ﬁle. baseurl) Bases: urllib2. http_error_304(req.cbook. hdrs) Read the ﬁle from the cache since the server has no newer version.

xlat(text) xlat(text) Translate text.delete_masked_points(*args) Find all masked and/or non-ﬁnite points in a set of arguments.cbook.anything else The ﬁrst argument must be in one of the ﬁrst four categories. If seq is empty. then removes up to n whitespace characters from each line.cbook.cbook. matplotlib.cbook.align_iterators(func. *iterables) This generator takes a bunch of iterables that are ordered by func It sends out ordered tuples: (func(row).cbook.converter(missing=’Null’. text) xlat = Xlator(adict) print xlat.cbook. matplotlib cbook .cbook. and return the arguments with only the unmasked points remaining.allpairs(x) return all possible pairs in sequence x Condensed by Alex Martelli from this thread on c. return True matplotlib. Release 1. Discards any leading blank lines.1-D masked arrays 2.1 print multiple_replace(adict. where n is the number of leading whitespace characters in the ﬁrst line.l. It is also faster in most cases. 550 Chapter 38. return False.python matplotlib. Arguments can be in any of 5 categories: 1.alltrue(seq) Return True if all elements of seq evaluate to True. If seq is 0 or 1 length. matplotlib.0.mlab.dedent in its deletion of leading blank lines and its use of the ﬁrst non-blank line to determine the indentation. returns the modiﬁed text.recs_join() to join record arrays matplotlib.ndarrays with more than one dimension 4. It diﬀers from textwrap.allequal(seq) Return True if all elements of seq compare equal. any argument with a length diﬀering from that of the ﬁrst argument (and hence anything in category 5) then will be passed through unchanged. missingval=None) Base class for handling string -> python type with support for missing values is_missing(s) matplotlib.dedent(s) Remove excess indentation from docstring s. class matplotlib.other non-string iterables 5.Matplotlib. [rows from all iterators matching func(row)]) It is used by matplotlib.1-D ndarrays 3.

matplotlib.activestate.12 in cookbook matplotlib.sourceforge. case=False) return all attributes of o which match string in match. if case is True require an exact case match.finddir(o. and 4.cbook.matplotlib/sample_data for a sample_data ﬁle.get_sample_data(fname. you need to check out sample_data from matplotlib svn: svn co https://matplotlib.flatten(seq. scalarp=<function is_scalar_or_string at 0x2f19410>) this generator ﬂattens nested containers such as >>> l=( (’John’.cbook. To bypass all downloading.dict_delall(d. John Hunter 1 23 42 5 23 By: Composite of Holger Krekel and Luther Blissett From: http://aspn. match.distances_along_curve(X) This function has been moved to matplotlib.sourceforge. matplotlib. If asﬁleobj is True. matplotlib. asﬁleobj=True) Check the cachedirectory ~/. keys) delete all of the keys from the dict d matplotlib.Matplotlib.net/svnroot/matplotlib/trunk/sample_data and svn add the data ﬁle you want to support. fetch it with urllib from the mpl svn repo http://matplotlib.cbook.cbook 551 . This is primarily intended for use in mpl examples that need custom data. Else the path to the ﬁle as a string will be returned To add a dataﬁle to this directory.net/svnroot/matplotlib/trunk/sample_data/ and store it in the cachedir.cbook. 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. a ﬁle object will be returned. (1. [[[[42.get_recursive_filelist(args) Recurse all the ﬁles and dirs in args ignoring symbolic links and return the ﬁles as a list of strings matplotlib.svn. A vastly simpler version of this function was originally written as a helper for Axes.23). ’Hunter’).scatter().mlab – please import it from there matplotlib. 38. 3.com/ASPN/Cookbook/Python/Recipe/121294 and Recipe 1.cbook. No attempt is made to extract a mask from categories 2. Release 1.23)]]]]) so that >>> for i in flatten(l): print i.0.(5.cbook.directory to the directory where we should look.exception_to_str(s=None) matplotlib.1 Masks are obtained from all arguments of the correct length in categories 1.svn. and 4 if np.download to False and examples.isfinite() does not yield a Boolean array. set the rc parameter examples.1. If it does not exist.cbook. 2. a point is bad if masked in a masked array or if it is a nan or inf.

just setitem.is_writable_file_like(obj) return true if obj looks like a ﬁle object with a write method matplotlib.is_closed_polygon(X) This function has been moved to matplotlib.mlab – please import it from there matplotlib.mlab – please import it from there matplotlib.cbook. Release 1.isvector(X) This function has been moved to matplotlib.get_split_ind(seq. extrap=False) This function has been moved to matplotlib.is_sequence_of_strings(obj) Returns true if obj is iterable and contains strings matplotlib.cbook.mlab – please import it from there matplotlib.cbook.1 matplotlib.iterable(obj) return true if obj is iterable matplotlib. y.is_math_text(s) matplotlib.cbook.less_simple_linear_interpolation(x.cbook.issubclass_safe(x. klass) return issubclass(x. return_folders=0) Recursively list ﬁles from Parmar and Martelli in the Python Cookbook class matplotlib.0.cbook. klass) and return False on a TypeError matplotlib.Matplotlib.cbook.cbook. xi. and set mode.mkdirs(newdir.is_scalar_or_string(val) matplotlib.is_string_like(obj) Return True if obj looks like a string matplotlib.cbook. this doesn’t override all the relevant methods to contrain size. matplotlib cbook .is_scalar(obj) return true if obj is not string like and is not iterable matplotlib.cbook. Return the index into seq such that: len(’ ’.cbook.join(seq[:ind])<=N matplotlib. patterns=’*’.cbook.is_numlike(obj) return true if obj looks like a number matplotlib. so use with caution matplotlib. recurse=1.cbook.cbook. Equivalent to > mkdir -p NEWDIR > chmod MODE NEWDIR 552 Chapter 38.cbook.maxdict(maxsize) Bases: dict A dictionary with a maximum size. N) seq is a list of words. mode=511) make directory newdir recursively.cbook.listFiles(root.

Matplotlib. matplotlib.onetrue(seq) Return True if one element of seq is True. num=2) Break up the seq into num tuples matplotlib.path_length(X) This function has been moved to matplotlib. q1y.cbook.converter 38. meaningless output.safezip(*args) make sure args are equal len before zipping class matplotlib.silent_list(type. outstream=<open ﬁle ‘<stdout>’. steps) matplotlib.cbook. len=4) soundex module conforming to Odell-Russell algorithm matplotlib.cbook. return_opened=False) fname can be a ﬁlename or a ﬁle handle. Support for gzipped ﬁles is automatic.report_memory(i=0) return the memory consumed by process matplotlib.cbook. q0y. It seq is empty.print_cycles(objects.mlab – please import it from there matplotlib.cbook.pieces(seq. if the ﬁlename ends in .cbook.mlab – please import it from there matplotlib. Release 1. This is meant to be used for a homogeneous list of a give type matplotlib.cbook.cbook. q2x.cbook 553 .quad2cubic(q0x.cbook. show_progress=False) objects A list of objects to ﬁnd cycles in.cbook.1.recursive_remove(path) matplotlib.cbook. missingval=None) Bases: matplotlib.cbook. outstream The stream for output.cbook. It is often useful to pass in gc.cbook. return False. ﬂag is a read/write ﬂag for file() class matplotlib.strip_math(s) remove latex formatting from mathtext matplotlib.0.gz.cbook. ﬂag=’rU’.to_filehandle(fname. q1x. q2y) This function has been moved to matplotlib.simple_linear_interpolation(a.popall(seq) empty a list matplotlib. show_progress If True.cbook.soundex(name.cbook.1 matplotlib. missing=’Null’.todate(fmt=’%Y-%m-%d’. print the number of objects reached as they are found. mode ‘w’ at 0x7fe77cfc0150>.safe_masked_invalid(x) matplotlib. matplotlib. matplotlib.garbage to ﬁnd the cycles that are preventing some objects from being garbage collected.cbook.reverse_dict(d) reverse the dictionary – may lose data if values are not unique! matplotlib. seq=None) Bases: list override repr when returning a list of matplotlib artists to prevent long.

1]] # returns array [3.tofloat(missing=’Null’.cbook. 5]] y. compressed=False) # returns array [[0. 2].cbook.cbook.compressed()[ii[1.] ii = unmasked_index_ranges(ma.cbook.0.cbook.ndarray corresponding to each of N uninterrupted runs of unmasked values.2.] [2. mask will be ﬂattened if it is not already 1-D. Returns None if there are no unmasked values.cbook.unmasked_index_ranges(mask.arange(5).cbook.4.tostr(missing=’Null’. Release 1.0]:ii[1.]] y. compressed=True) Find index ranges where mask is False.4.cbook. this was used to support masked arrays in Line2D. missingval=None) Bases: matplotlib.ndarray with each row the start and stop indices for slices of the compressed numpy.converter convert to string or None matplotlib.unique(x) Return a list of unique elements of x matplotlib.strptime() format string for conversion class matplotlib.cbook. it returns the start and stop indices into the original numpy.converter convert to an int or None class matplotlib.todatetime(fmt=’%Y-%m-%d’. missingval=None) Bases: matplotlib.0]:ii[1. Example: y = ma.getmaskarray(y).1 convert to a date or None use a time. missingval=None) Bases: matplotlib.1.Matplotlib.array(np.0.] Prior to the transforms refactoring. If optional argument compressed is False. 554 Chapter 38.converter convert to a datetime or None use a time.1]] # returns array [3.4.ndarray.getmaskarray(y)) # returns array [[0. mask = [0. Returns Nx2 numpy. missingval=’‘) Bases: matplotlib.0]) ii = unmasked_index_ranges(ma.filled()[ii[1.unicode_safe(s) matplotlib.cbook.strptime() format string for conversion class matplotlib.toint(missing=’Null’. [3.cbook. missing=’Null’.0. matplotlib cbook .ndarray.converter convert to a ﬂoat or None class matplotlib. not the compressed numpy.

text.0.Matplotlib. matplotlib.wrap(preﬁx. P=2.mlab – please import it from there matplotlib.cbook.1. cols) wrap text with preﬁx at length cols 38. Release 1.cbook 555 .vector_lengths(X. axis=None) This function has been moved to matplotlib.0.cbook.1 matplotlib.

Matplotlib. matplotlib cbook .1 556 Chapter 38.0. Release 1.

ScalarMappable(norm=None.cm.Normalize or one of its subclasses. 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 . class matplotlib. used to map luminance to 0-1. functions for registering new colormaps and for getting a colormap by name.1 matplotlib.CHAPTER THIRTYNINE MATPLOTLIB CM 39. Handles normalization and colormapping norm is an instance of colors. and a mixin class for adding color mapping functionality. cmap=None) This is a mixin class to support scalar -> RGBA mapping. 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 ﬂags that are set to True when the mappable is changed.cm This module provides a large set of colormaps. 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. else return False get_array() Return the array get_clim() return the min. cmap is a cm colormap instance. for example cm. return True.

It can be used in two ways: register_cmap(name=’swirly’. If bytes is True. ax) set the colorbar image and axes associated with mappable set_norm(norm) set the normalization instance to_rgba(x. and the resulting colormap is registered. cmap must be a colors. return rgba as 4 uint8s instead of 4 ﬂoats. matplotlib.LinearSegmentedColormap initializer. matplotlib.0. vmax) which is used to support setp ACCEPTS: a length 2 sequence of ﬂoats set_cmap(cmap) set the colormap for luminance data ACCEPTS: a colormap or registered colormap name set_colorbar(im. cmap=None.cm. interpret it as (vmin. data=choppydata. return it unchanged.revcmap(data) 558 Chapter 39. the three arguments are passed to the colors.cm. data=None.cm. it will be returned. matplotlib cm . lut=None) Add a colormap to the set recognized by get_cmap().1 set_clim(vmin=None. lut=128) In the ﬁrst case. In the second case. If x is already an rgb array. lut=None) Get a colormap instance.Matplotlib. The name is optional. if absent. Colormaps added with register_cmap() take precedence over builtin colormaps. bytes=False) Return a normalized rgba array corresponding to x. defaulting to rc values if name is None. If lut is not None it must be an integer giving the number of entries desired in the lookup table.Colormap instance.register_cmap(name=None.Colormap instance. if vmin is a length2 sequence. Release 1. cmap=swirly_cmap) register_cmap(name=’choppy’.get_cmap(name=None. and name must be a standard mpl colormap name with a corresponding data dictionary in datad. matplotlib. insert alpha. the name will be the name attribute of the cmap. If name is a colors. alpha=None. if it is already rgba. vmax=None) set the norm limits for image scaling.

PatchCollection 40.g. rotation=0.CHAPTER FORTY MATPLOTLIB COLLECTIONS collections.AsteriskPolygonCollection(numsides.1 matplotlib. a large set of solid line segemnts) class matplotlib. e. sizes=(1.ScalarMappable collections.LineCollection collections.collections.BrokenBarHCollection collections. ).CircleCollection collections.Artist collections.EllipseCollection collections.RegularPolyCollection Draw a collection of regular asterisks with numsides points.collections Classes for the eﬃcient drawing of large collections of objects that share most properties. a large number of line segments or polygons. The classes are not meant to be as ﬂexible as their single element counterparts (e.AsteriskPolygonCollection collections.RegularPolyCollection collections.Collection cm.g.QuadMesh artist.collections. **kwargs) Bases: matplotlib. 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 .g.PolyCollection collections.StarPolygonCollection collections. you may not be able to select all line styles) but they are meant to be fast for common use cases (e.PathCollection collections.

Matplotlib. sizes=(50.1) collection = RegularPolyCollection( numsides=5. facecolors = facecolors. transOffset = ax. offsets = offsets.2) facecolors = [cm. linewidths. Release 1.). they default to their matplotlib.py for complete example: offsets = np. # a pentagon rotation=0.jet(x) for x in np.).1 Valid Collection keyword arguments: • edgecolors: None • facecolors: None • linewidths: None • antialiaseds: None • oﬀsets: None • transOﬀset: transforms.PolyCollection A collection of horizontal bars spanning yrange with a sequence of xranges.IdentityTransform() • norm: None (optional for matplotlib.rand(20. ) class matplotlib.cm.0.collections. matplotlib collections .cm.rand(20)] black = (0. xranges sequence of (xmin.collections. facecolors. **kwargs) Bases: matplotlib. linewidths = (1. Example: see examples/dynamic_collection.BrokenBarHCollection(xranges. ywidth Valid Collection keyword arguments: • edgecolors: None • facecolors: None • linewidths: None • antialiaseds: None • oﬀsets: None 560 Chapter 40.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors.random. yrange. xwidth) yrange ymin. in sequence form.0. edgecolors = (black.ScalarMappable) • cmap: None (optional for matplotlib.random.rcParams patch setting.0.transData. antialiaseds are None.).

cm.collections. drawn using splines. in sequence form.cm. Release 1. they default to their matplotlib.CircleCollection(sizes.1.cm.artist. Must be subclassed to be usable.IdentityTransform() • norm: None (optional for matplotlib.0. linewidths. in sequence form. linestyles=’solid’.Artist.Matplotlib. class matplotlib. sizes Gives the area of the circle in points^2 Valid Collection keyword arguments: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •oﬀsets: None •transOﬀset: transforms. 40. cmap=None.IdentityTransform() •norm: None (optional for matplotlib. facecolors.ScalarMappable Base class for Collections.0. antialiaseds=None. kwargs are passed on to the collection.ScalarMappable) •cmap: None (optional for matplotlib. The bars range on the y-axis from ymin to ymax A BrokenBarHCollection is returned.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors.Collection(edgecolors=None. *args. urls=None. **kwargs) Bases: matplotlib. matplotlib. **kwargs) Bases: matplotlib. facecolors=None. renderer. antialiaseds are None. linewidths=None. static span_where(x. draw(artist. facecolors.Collection A collection of circles.collections 561 . ymin. pickradius=5.collections. oﬀsets=None. linewidths. ymax.cm. **kwargs) get_sizes() return sizes of circles class matplotlib.cm. **kwargs) Create a BrokenBarHCollection to plot horizontal bars from over the regions in x where where is True.rcParams patch setting. matplotlib. they default to their matplotlib. antialiaseds are None. where. norm=None.ScalarMappable) • cmap: None (optional for matplotlib.1 • transOﬀset: transforms.rcParams patch setting.collections.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors. transOﬀset=None.

ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets).1 All properties in a collection must be sequences or scalars. they default to their matplotlib. where every item in itemlist contains the event.0.cm. linewidths. dict(ind=itemlist). Release 1. they will be converted to sequences.IdentityTransform() •norm: None (optional for matplotlib. renderer. Returns True | False. 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 •oﬀsets: None •transOﬀset: transforms. If any of edgecolors. at draw time a call to scalar mappable will be made to set the face colors. if scalars. antialiaseds are None. If the ScalarMappable matrix _A is not None (ie a call to set_array has been made). in sequence form. matplotlib collections .ScalarMappable) •cmap: None (optional for matplotlib. draw(artist.rcParams patch setting. facecolors. *args.cm. Create a Collection %(Collection)s contains(mouseevent) Test whether the mouse event occurred in the collection.Matplotlib. The use of ScalarMappable is optional. **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.

or a sequence of rgba tuples. 40. the edge color will always be the same as the face color. If c is ‘none’. if it is a sequence the patches will cycle through the sequence. c can be a matplotlib color arg (all patches have same color). If c is ‘face’.1 get_offsets() Return the oﬀsets for the collection. matplotlib. If it is ‘none’. the patch will not be ﬁlled. set_dashes(ls) alias for set_linestyle set_edgecolor(c) Set the edgecolor(s) of the collection. or a sequence of rgba tuples.collections 563 . ACCEPTS: matplotlib color arg or sequence of rgba tuples See Also: set_facecolor(). 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.1. get_paths() get_pickradius() get_transforms() get_urls() get_window_extent(renderer) set_alpha(alpha) Set the alpha tranparencies of the collection. alpha must be a ﬂoat or None.0. the patch boundary will not be drawn. c can be a matplotlib color arg (all patches have same color). Release 1. set_edgecolor() For setting the edge or face color individually. if it is a sequence the patches will cycle through the sequence.Matplotlib. ACCEPTS: ﬂoat or None set_antialiased(aa) Set the antialiasing state for rendering. ACCEPTS: Boolean or sequence of booleans set_antialiaseds(aa) alias for set_antialiased set_color(c) Set both the edgecolor and the facecolor.

ACCEPTS: [’solid’ | ‘dashed’. angles.collections. ‘dotted’ | (oﬀset. update colors from scalar data class matplotlib. oﬀsets can be a scalar or a sequence. drawn using splines. degrees CCW from the X-axis units: [’points’ | ‘inches’ | ‘dots’ | ‘width’ | ‘height’ ‘x’ | ’y’ | ’xy’] 564 Chapter 40. lw can be a scalar or a sequence.Collection A collection of ellipses.EllipseCollection(widths. **kwargs) Bases: matplotlib. ‘dashdot’. Release 1. on-oﬀ-dash-seq) ] set_linestyles(ls) alias for set_linestyle set_linewidth(lw) Set the linewidth(s) for the collection. matplotlib collections .g.. major axis lengths) heights: sequence lengths of second axes angles: sequence angles of ﬁrst axes. widths: sequence lengths of ﬁrst axes (e. units=’points’.collections. heights.0. ACCEPTS: ﬂoat or sequence of ﬂoats 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.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. if it is a sequence the patches will cycle through the sequence ACCEPTS: ﬂoat or sequence of ﬂoats set_linewidths(lw) alias for set_linewidth set_lw(lw) alias for set_linewidth set_offsets(oﬀsets) Set the oﬀsets for the collection.Matplotlib.

ym) or the equivalent numpy array with two columns. y0). antialiaseds=None. and equals the speciﬁed angle only when the aspect ratio is unity. norm=None.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors. Hence it behaves the same as the Ellipse with axes. the properties cycle if the len of props is less than the number of segments. line2). (xm. they will be converted to sequences. matplotlib. *args. pickradius=5. Each line can be a diﬀerent length.collections. antialiaseds are None. linewidths=None..e. **kwargs) class matplotlib. ‘xy’ diﬀers from all others in that the angle as plotted varies with the aspect ratio. y1). ‘width’ and ‘height’ refer to the dimensions of the axes.collections 565 . linewidths..1.LineCollection(segments. Release 1. where: linen = (x0. **kwargs) Bases: matplotlib. oﬀsets=None.ScalarMappable) •cmap: None (optional for matplotlib. antialiaseds must be a sequence of ones or zeros linestyles [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] a string or dash tuple.Collection All parameters must be sequences or scalars. facecolors.1 units in which majors and minors are given. they default to their matplotlib. if scalars. renderer. in sequence form. (x1. The property of the ith line segment is: prop[i % len(props)] i. cmap=None.0. Additional kwargs inherited from the base Collection: Valid Collection keyword arguments: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •oﬀsets: None •transOﬀset: transforms. not allowed). etc. transOﬀset=None. The dash tuple is: (offset.cm.. linestyles=’solid’.IdentityTransform() •norm: None (optional for matplotlib. onoffseq). colors must be a sequence of RGBA tuples (eg arbitrary color strings. segments a sequence of (line0.Matplotlib.cm. 40.transData as its transform. line1.rcParams patch setting.collections. while ‘x’ and ‘y’ refer to the oﬀsets data units. draw(artist. . colors=None.

The use of ScalarMappable is optional. then oﬀsets are transformed by transOﬀset and applied after the segments have been transformed to display coordinates. so as to produce a set of successively oﬀset curves. match_original=False. This also may improve plotting speed. This list may include a heterogeneous assortment of diﬀerent patch types. color(c) Set the color(s) of the line collection. they default to their rcParams setting.ScalarMappable) cmap None (optional for matplotlib. in sequence form. colors. If oﬀsets is not None but transOﬀset is None. if it is a sequence the patches will cycle through the sequence.1 where onoﬀseq is an even length tuple of on and oﬀ ink in points.Collection A generic collection of patches. a single oﬀset can be speciﬁed as: offsets=(xo. 566 Chapter 40.Matplotlib. If oﬀsets and transOﬀset are not None. or a sequence or rgba tuples.collections.cm. c can be a matplotlib color arg (all patches have same color).0. If the ScalarMappable matrix _A is not None (ie a call to set_array() has been made).collections. or a sequence or rgba tuples. matplotlib collections .PatchCollection(patches. 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. **kwargs) Bases: matplotlib. Release 1. If linewidths.ScalarMappable) pickradius is the tolerance for mouse clicks picking a line.cm. or antialiaseds is None. This makes it easier to assign a color map to a heterogeneous collection of patches. The default is 5 pt. since PatchCollection will draw faster than a large number of patches. at draw time a call to scalar mappable will be made to set the colors. c can be a matplotlib color arg (all patches have same color). patches a sequence of Patch objects. then the oﬀsets are added to the segments before any transformation. In this case. norm None (optional for matplotlib. ACCEPTS: matplotlib color arg or sequence of rgba tuples set_paths(segments) set_segments(segments) set_verts(segments) class matplotlib.yo) and this value will be added cumulatively to each successive segment.

antialiaseds are None. then the overall scaling is such that if verts_i specify a unit square.cm. The scaling is applied before the Artist master transform. when True.Matplotlib. set_paths(patches) class matplotlib.) where verts_i is a sequence of xy tuples of vertices. Release 1.PolyCollection(verts. in sequence form. paths is a sequence of matplotlib. facecolors. verts1.IdentityTransform() •norm: None (optional for matplotlib.Collection This is the most basic Collection subclass. the additional values will be taken cyclically from the array. Valid Collection keyword arguments: •edgecolors: None •facecolors: None •linewidths: None •antialiaseds: None •oﬀsets: None •transOﬀset: transforms.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors.rcParams patch setting..collections. matplotlib. if the latter is an identity transform.. linewidths. or an equivalent numpy array of shape (nv.collections. The use of ScalarMappable is optional. closed=True.PathCollection(paths. If len(sizes) < nv. then sizes_i is the area of that square in points^2. facecolor. set_paths(paths) class matplotlib. linewidths.collections. closed.Collection verts is a sequence of ( verts0.Path instances.rcParams patch setting.collections. If the ScalarMappable matrix _A is not None (ie a call to set_array has been made).1.1 match_original If True. sizes=None. 2).path. **kwargs) Bases: matplotlib. at draw time a call to scalar mappable will be made to set the face colors. linewidths. norm or cmap. in sequence form. . **kwargs) Bases: matplotlib. Valid Collection keyword arguments: •edgecolors: None 40. use the colors and linewidths of the original patches. will explicitly close the polygon.ScalarMappable) •cmap: None (optional for matplotlib. antialiaseds are None.0. facecolors. If False.cm. edgecolor. If any of edgecolors. they default to their matplotlib. new colors may be assigned by providing the standard collection arguments.collections 567 . they default to their matplotlib. sizes is None (default) or a sequence of ﬂoats that scale the corresponding verts_i.

in the case of the colors). 1). use the set_cmap() method.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors. closed=True) This allows one to delay initialization of the vertices. coordinates) Converts a given mesh into a sequence of matplotlib. draw(artist. shading may be ‘ﬂat’. A quadrilateral mesh is represented by a (2 x ((meshWidth + 1) * (meshHeight + 1))) numpy array coordinates. There are thus (meshWidth * meshHeight) quadrilaterals in the mesh. 0). (m. n + 1). meshWidth). 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. then at (0.path. matplotlib collections . n + 1). (1. meshHeight + 1). The mesh need not be regular and the polygons need not be convex.Collection Class for the eﬃcient drawing of a quadrilateral mesh. meshHeight.Path objects for easier rendering by backends that do not directly support quadmeshes. linewidths. renderer. 2) . closed=True) This allows one to delay initialization of the vertices. 568 Chapter 40.cm.collections. Each vertex in the mesh has a diﬀerent set of “mesh coordinates” representing its position in the topology of the mesh. The dimensions of this array are (meshWidth + 1. and (m + 1. n) form one of the quadrilaterals in the mesh. A quadrilateral mesh consists of a grid of vertices.ScalarMappable) •cmap: None (optional for matplotlib.QuadMesh(meshWidth. **kwargs) Bases: matplotlib. To deﬁne the function that maps from a data point to its corresponding color. where each row is the x and y coordinates of one of the vertices. shading=’ﬂat’. 0).1 •facecolors: None •linewidths: None •antialiaseds: None •oﬀsets: None •transOﬀset: transforms. then the one at (0.. meshHeight.0. This function is primarily of use to backend implementers. facecolors. in sequence form. and so on. (0.Matplotlib. **kwargs) set_paths(verts. n) such that 0 <= m <= meshWidth and 0 <= n <= meshHeight. (m + 1. 1). showedges. ‘faceted’ or ‘gouraud’ static convert_mesh_to_paths(meshWidth. coordinates. set_verts(verts. Release 1. they default to their matplotlib. the vertices at mesh coordinates (m. *args. For example. antialiaseds are None.IdentityTransform() •norm: None (optional for matplotlib. For any values (m. antialiased=True.collections. (1. n).rcParams patch setting. the ﬁrst entry in coordinates is the coordinates of the vertex at mesh coordinates (0. class matplotlib.cm.

sizes=(50. Release 1. facecolors.random.rand(20.1) collection = RegularPolyCollection( numsides=5.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors. they default to their matplotlib.ScalarMappable) • cmap: None (optional for matplotlib.). linewidths. edgecolors = (black. sizes=(1.IdentityTransform() • norm: None (optional for matplotlib. renderer. 40. each point with its own color. ).rand(20)] black = (0.cm.0.RegularPolyCollection(numsides.collections.cm. **kwargs) Bases: matplotlib.1 convert_mesh_to_triangles(meshWidth. facecolors = facecolors. *args.Matplotlib. coordinates) Converts a given mesh into a sequence of triangles. rotation=0.Collection Draw a collection of regular polygons with numsides. antialiaseds are None.0. **kwargs) get_datalim(transData) get_paths() set_paths() class matplotlib.1. Example: see examples/dynamic_collection.). in sequence form.collections 569 . matplotlib. meshHeight. draw(artist. offsets = offsets.). 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 • oﬀsets: None • transOﬀset: transforms. # a pentagon rotation=0.2) facecolors = [cm.random.py for complete example: offsets = np.collections.0.jet(x) for x in np. This is useful for experiments using draw_qouraud_triangle.rcParams patch setting. linewidths = (1.

IdentityTransform() • norm: None (optional for matplotlib. edgecolors = (black. rotation=0.).0.ScalarMappable) • cmap: None (optional for matplotlib.cm. in sequence form. facecolors = facecolors.2) facecolors = [cm. 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 • oﬀsets: None • transOﬀset: transforms. linewidths = (1.RegularPolyCollection Draw a collection of regular stars with numsides points.py for complete example: offsets = np.collections.1 transOffset = ax. ) draw(artist.). renderer.jet(x) for x in np.rand(20. linewidths.random.StarPolygonCollection(numsides.Matplotlib. sizes=(50. 570 Chapter 40.ScalarMappable) oﬀsets and transOﬀset are used to translate the patch after rendering (default no oﬀsets) If any of edgecolors.transData.0. sizes=(1.rand(20)] black = (0. # a pentagon rotation=0. matplotlib collections .rcParams patch setting. Release 1. antialiaseds are None.). Example: see examples/dynamic_collection. ). **kwargs) Bases: matplotlib. facecolors.0. **kwargs) get_numsides() get_rotation() get_sizes() class matplotlib.collections.cm.random. *args.1) collection = RegularPolyCollection( numsides=5. offsets = offsets. they default to their matplotlib.

1 transOffset = ax. ) 40.Matplotlib. matplotlib. Release 1.collections 571 .1.0.transData.

Release 1. matplotlib collections .1 572 Chapter 40.Matplotlib.0.

It is not called when the pyplot.colorbar method are used to create the colorbar..colorbar function or the Figure.colorbar Colorbar toolkit with two classes and a function: ColorbarBase the base class with full colorbar drawing functionality. it does not clear the axes. alpha=None. values=None. class matplotlib.ColorbarBase(ax. **kw) Bases: matplotlib.colorbar.colorbar. instead.Colorbar(ax. and will probably be deprecated and then removed. 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. This is meant to be called when the image or contour plot to which this colorbar belongs is changed. etc. norm=None. use colorbar() or colorbar() to make your colorbar. boundaries=None. update_normal(mappable) update solid. orientation=’vertical’. format=None. spacing=’uniform’. Unlike update_bruteforce. update_bruteforce(mappable) Destroy and rebuild the colorbar.CHAPTER FORTYONE MATPLOTLIB COLORBAR 41.colorbar. image) is not needed. cmap=None. a mappable object (e. add_lines(CS) Add the lines from a non-ﬁlled ContourSet to the colorbar. extend=’neither’.1 matplotlib. This is intended to become obsolete. mappable. class matplotlib. ticks=None. the colorbar() function is a thin wrapper over colorbar(). It is not intended to be instantiated directly.g. It can be used as-is to make a colorbar for a given colormap. lines. drawedges=False. Colorbar the derived class for use with images or contour plots.ColorbarBase This class connects a ColorbarBase to a ScalarMappable such as a AxesImage generated via imshow(). ﬁlled=True) 573 .

Release 1.colorbar. colors.0. kw = make_axes(parent. If the cmap kwarg is given but boundaries and values are left as None. This is a base class for the Colorbar class.Normalize(clip=False) To show the colors versus index instead of on the 0-1 scale. To manually update the ticks. call update_ticks method explicitly.1 Bases: matplotlib. This must be called whenever the tick locator and/or tick formatter changes.cm. To manually update the ticks. otherwise None Useful public methods are set_label() and add_lines(). **kw) Resize and reposition a parent axes.make_axes(parent. set_ticks(ticks. update_ticks=True) set tick labels. call update_ticks method explicitly. update_ticks() Force the update of the ticks and ticklabels. specify the norm as: colors.NoNorm. use: norm=colors. which are the usual ways of creating a colorbar. Tick locations are updated immediately unless update_ticks is False. Useful attributes: ax the Axes instance in which the colorbar is drawn lines a LineCollection if lines were drawn. It is also useful by itself for showing a colormap.and over-value colors. otherwise None dividers a LineCollection if drawedges is True. update_ticks=True) set tick locations. 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.Matplotlib. To show the under. Tick labels are updated immediately unless update_ticks is False. **kw) Label the long axis of the colorbar set_ticklabels(ticklabels.ScalarMappable Draw a colorbar in an existing axes. and do all the drawing. linewidths) Draw lines on the colorbar. **kw) Keyword arguments may include the following (with defaults): 574 Chapter 41. add_lines(levels. set_alpha(alpha) set_label(label. which is the basis for the colorbar() function and the colorbar() method. matplotlib colorbar . and return a child axes suitable for a colorbar: cax.

41.15. kw).0. fraction by which to shrink the colorbar 20.1. fraction of original axes to use for colorbar 0. fraction of original axes between colorbar and new image axes 1. matplotlib. Release 1. ratio of long to short dimensions All but the ﬁrst of these are stripped from the input kw set.05 if vertical.15 if horizontal.Matplotlib. 0.0. the child axes and the reduced kw dictionary.colorbar 575 . Returns (cax.1 orientation ‘vertical’ or ‘horizontal’ Property orientation fraction pad shrink aspect Description vertical or horizontal 0.

0. Release 1.1 576 Chapter 41. matplotlib colorbar .Matplotlib.

3 or 4 ﬂoats in the range 0-1. e. and for mapping numbers to colors in a 1-D array of colors called a colormap. Two are provided here: LinearSegmentedColormap.colors A module for converting numbers or color arguments to RGB or RGBA RGB and RGBA are sequences of. which is used for generating a custom colormap from a list of color speciﬁcations. respectively.g. colorConverter. For the basic builtin colors. This module includes functions and classes for color speciﬁcation conversions.75’ 577 . then this number in the 0-1 range is mapped to a color using an instance of a subclass of Colormap. but is also useful for making custom colormaps.CHAPTER FORTYTWO MATPLOTLIB COLORS 42. 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 ﬂoat in the 0-1 range. and ListedColormap. Colormapping typically involves two steps: a data array is ﬁrst mapped onto the range 0-1 using an instance of Normalize or of a subclass. Commands which take color arguments can use several formats to specify the colors.1 matplotlib.: color = ’0. of the ColorConverter class providing methods for converting single color speciﬁcations or sequences of them to RGB or RGBA. The module also provides a single instance. which is used to generate all the built-in colormap instances.

the A will simply be discarded.a ﬂoat. and reduces the number of conversions back and forth between integer and ﬂoating point. where each of R . like ‘0.colors.0. to_rgba(arg. 578 Chapter 42. Release 1.a letter from the set ‘rgbcmykw’ 2. BoundaryNorm maps values to integers instead of to the interval 0-1. 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. ncolors. class matplotlib. you have two options. clip=False) Bases: matplotlib. but using integers seems simpler. ‘burlywood’ and ‘chartreuse’ are supported. G . like ‘aqua’ 4.1 For a greater range of colors. these are converted to valid indices by Colormap. as i varies from 0 to len(boundaries)-2.Matplotlib. B tuple.a hex color string.colors. B are in the range [0.a standard name. legal html names for colors. arg can be an RGB or RGBA sequence or a string in any of several forms: 1.ColorConverter Provides methods for converting color speciﬁcations to RGB or RGBA Caching is used for more eﬃcient conversion upon repeated calls with the same argument.1]. to_rgb(arg) Returns an RGB tuple of three ﬂoats from 0-1. Ordinarily only the single instance instantiated in this module. j goes from 0 to ncolors-1.BoundaryNorm(boundaries. like ‘red’. as in: color = ’#eeefff’ or you can pass an R . Unlike Normalize or LogNorm. You can specify the color using an html hex string. Out-of-range values are mapped to -1 if low and ncolors if high. G . inverse(value) class matplotlib. is needed. alpha=None) Returns an RGBA tuple of four ﬂoats from 0-1. colorConverter.Normalize Generate a colormap index based on discrete intervals. like ‘#00FFFF’ 3.4’. matplotlib colors . indicating gray on a 0-1 scale if arg is RGBA. Finally.colors. Mapping to the 0-1 interval could have been done via piece-wise linear interpolation.__call__() .

LightSource(azdeg=315. In addition. Requires norm.Colormap(name. cmap) Take the input data array. alpha=None) Set color to be used for masked values. class matplotlib. Same for an empty list. then (0.1 For acceptable values of arg. alpha=None) Set color to be used for low out-of-range values.0. v = 1). set_over(color=’k’. or lightened by sliding (s. hsv_min_sat=1. The shade() is used to produce rgb values for a shaded relief image given a data array. Angles are in degrees. Release 1. matplotlib. shade(data. Special case to handle “no color”: if c is “none” (case-insensitive). to_rgba_array(c.0) will be returned. if arg is “none” (case-insensitive). altdeg=45. Accepts a single mpl color spec or a sequence of specs. alpha will replace the original A. then adjust those color 42. The color of the resulting image will be darkened by moving the (s. hsv_min_val=0.colors. v = 0) and completely illuminated points are nearly white (s = 0.v) toward (hsv_max_sat hsv_max_val) in regions that are illuminated.Matplotlib. If arg is an RGBA sequence and alpha is not None.v) values (in hsv colorspace) toward (hsv_min_sat. then an empty array will be returned.0. see to_rgb(). hsv_min_val) in the shaded regions. hsv_max_sat=0) Bases: object Create a light source coming from the speciﬁed azimuth and elevation. with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. 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’. Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees.colors 579 .colors.clip = False class matplotlib.1. Requires norm. alpha=None) Returns a numpy array of RGBA tuples.clip = False set_under(color=’k’. alpha=None) Set color to be used for high out-of-range values. The default extremes are chose so that completely shaded points are nearly black (s = 1. convert to HSV values in the given colormap. hsv_max_val=1.0.

For any input value z falling between x[i] and x[i+1]. (1. ’blue’: [(0.0. and blue over the top half.1 values to given the impression of a shaded relief map with a speciﬁed light source. 1.0).0) Bases: 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 speciﬁed light source using the elevation (ny*nx). Each entry should be a list of x.colors. (0. 0. factory function for generating a smoothly-varying LinearSegmentedColormap.0. y1 tuples. with the 0-1 domain divided into any number of segments. 0.0.colors. 1.0)]} Each row in the table for a given color is a sequence of x. 1. (0. (1.0). 0. In each sequence.0. (0.0. 1. segmentdata.Matplotlib.0. ’green’: [(0. The lookup table is generated using linear interpolation for each primary color. y0.0. 0. matplotlib colors . Create color map from linear mapping segments segmentdata argument is a dictionary with a red. x must increase monotonically from 0 to 1.0. 0. 1. which can then be used to plot the shaded image with imshow.0. 0. green to do the same over the middle half.0)]. A new RGB array ((ny*nx*3)) is returned. y0. class matplotlib. 1. 0.25. Then you would use: cdict = {’red’: [(0.0)]. 1.0). green and blue entries. 0. See Also: LinearSegmentedColormap.0. elevation.0. 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 ﬁrst row and y1 in the last row are never used.from_list() Static method. gamma=1. fraction=1. shade_rgb(rgb. N=256.LinearSegmentedColormap(name. 0. 1. makeMappingArray() For information about making a mapping array.5.0. Release 1.0.0.0). 1.75. RGBA values are returned. y1 tuples.0). forming rows in a table.Colormap Colormap objects based on lookup tables using linear segments.0). 580 Chapter 42. Example: suppose you want red to increase from 0 to 1 over the bottom half.5.0).0.0. (1. 1. (0. 0.0.

matplotlib.LogNorm(vmin=None.colors.colors. autoscale_None(A) autoscale only None-valued vmin or vmax inverse(value) 42. including masked arrays. If clip is True.Normalize Normalize a given value to the 0-1 range on a log scale If vmin or vmax is not given.colors 581 . therefore the default is clip = False. under. the returned value will be 0 or 1.Matplotlib. name=’from_list’. clip=False) Bases: matplotlib. Alternatively. in which case there is one colormap entry for each element in the list of colors. gamma=1. If: N > len(colors) the list will be extended by repetition. Make a colormap from a list of colors. class matplotlib. autoscale(A) Set vmin. This may be most useful when indexing directly into a colormap. and masked colors in the colormap. whichever is closer.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. Release 1. colors. class matplotlib. vmax to min. they are taken from the input’s minimum and maximum value respectively. N is the number of rgb quantization levels.1. N=256.colors.Colormap Colormap object generated from a list of colors. If clip is True and the given value falls outside the range. or an equivalent Nx3 ﬂoating point array (N rgb values) name a string to identify the colormap N the number of entries in the map.1 static from_list(name. otherwise they remain masked. max of A.0. so it is likely to lead to surprises. The default is None. N=None) Bases: matplotlib. set_gamma(gamma) Set a new gamma value and regenerate color map. Clipping silently defeats the purpose of setting the over. color) tuples can be given to divide the range unevenly. If: N < len(colors) the list will be truncated at N. vmax=None. but it can also be used to generate special colormaps for ordinary mapping.ListedColormap(colors. a list of (value. Returns 0 if: vmin==vmax Works with scalars or arrays.colors. colors a list of matplotlib color speciﬁcations. masked values are set to 1.

Returns 0 if: vmin==vmax Works with scalars or arrays. therefore the default is clip = False. 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. vmax to min. clip=False) Normalize a given value to the 0-1 range If vmin or vmax is not given.93725. otherwise they remain masked. whichever is closer. so it is likely to lead to surprises. autoscale(A) Set vmin. If clip is True and the given value falls outside the range. under. inverse(value) class matplotlib. they are taken from the input’s minimum and maximum value respectively. clip=False) Bases: matplotlib.0.colors.Normalize(vmin=None. for the case where we want to use indices directly in a ScalarMappable .1 class matplotlib. Release 1. 0. so it is likely to lead to surprises. masked values are set to 1. under.colors.Matplotlib.93725) matplotlib. masked values are set to 1.colors. the returned value will be 0 or 1. the returned value will be 0 or 1.0) Create an N -element 1-d lookup table 582 Chapter 42. Clipping silently defeats the purpose of setting the over. including masked arrays. and masked colors in the colormap. gamma=1. 0.colors. If clip is True and the given value falls outside the range.colors.NoNorm(vmin=None. Returns 0 if: vmin==vmax Works with scalars or arrays. matplotlib colors . they are taken from the input’s minimum and maximum value respectively. If clip is True.Normalize Dummy replacement for Normalize. max of A.colors. and masked colors in the colormap.93725. therefore the default is clip = False. vmax=None. whichever is closer. including masked arrays.hsv_to_rgb(hsv) convert hsv values in a numpy array to rgb values both input and output arrays have shape (M.hex2color(s) Take a hex string s and return the corresponding rgb 3-tuple Example: #efefef -> (0. If clip is True. data.makeMappingArray(N. vmax=None.colors.is_color_like(c) Return True if c can be converted to RGB matplotlib.3) matplotlib.N. Clipping silently defeats the purpose of setting the over. If vmin or vmax is not given.

1 data represented by a list of x.colors. 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.normalize alias of Normalize matplotlib. Alternatively.colors. and all values of x must be in increasing order. The function returns an array “result” where result[x*(N-1)] gives the closest value for values of x between 0 and 1. matplotlib.colors. data can be a function mapping values between 0 .1.y0. matplotlib.Matplotlib.0. end with x=1. 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).1 to 0 .no_norm alias of NoNorm matplotlib. and y1 is the value to be used for x > than that given).1.colors. The list must start with x=0.rgb_to_hsv(arr) convert rgb values in a numpy array to hsv values input and output arrays should have shape (M.y1 mapping correspondences.rgb2hex(rgb) Given an rgb or rgba sequence of 0-1 ﬂoats.colors 583 . Release 1. return the hex string matplotlib.3) 42.N. Values between the given mapping points are determined by simple linear interpolation.

1 584 Chapter 42. matplotlib colors .0.Matplotlib. Release 1.

not 0.1 matplotlib. This practice is not universal. 1582. the number of days between 0001-01-01 and 2006-04-01 is 732403. For example. mpl uses the Gregorian calendar for all conversions between dates and ﬂoating point numbers. Hence.date(1. using their calculator.25. whereas using the Gregorian calendar via the datetime module we ﬁnd: In [31]:date(2006.1). and calendar diﬀerences can cause confusing diﬀerences between what Python and mpl give as the number of days since 0001-01-01 and what other software and databases yield.25.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. datetime objects are converted to ﬂoating point numbers which represent time in days since 0001-01-01 UTC. For example.1.dates Matplotlib provides sophisticated date plotting capabilities.toordinal() Out[31]:732401 585 .toordinal() . plus 1. 06:00 is 1. the add-on modules pytz and dateutils. standing on the shoulders of python datetime.1). 0001-01-01. The helper functions date2num(). Note: Like Python’s datetime. num2date() and drange() are used to facilitate easy conversion to and from datetime and numeric ranges.4. the US Naval Observatory uses a calendar that switches from Julian to Gregorian in October.

TU • MonthLocator: locate months. the default from your rc ﬁle will be assumed. The dateutil module provides additional code to handle date ticking. 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. 43. The rrulewrapper is a simple wrapper around a dateutils. • AutoDateLocator: On autoscale. byeaster=1. interval=2) The rrule locator allows completely general date ticking: # tick every 5th easter rule = rrulewrapper(YEARLY.0. See pytz for information on pytz and timezone handling.rrulewrapper. If you leave out a tz timezone instance. All the matplotlib date converters. and any custom date tickers or locators you create. making it easy to place ticks on any kinds of dates. 586 Chapter 43. most of the constructors take an interval argument: # tick on mondays every second week loc = WeekdayLocator(byweekday=MO.ticker for general information on tick locators and formatters.1 Date tickers Most of the date tickers can locate single or multiple values. See examples below. These are described below. If you want to use a custom time zone. tz=tz) # tick on mondays and saturdays loc = WeekdayLocator(byweekday=(MO.Matplotlib.1 A wide range of speciﬁc and general purpose date tick locators and formatters are provided in this module. Release 1.dates. eg 7 for july • YearLocator: locate years that are multiples of base • RRuleLocator: locate using a matplotlib. plot_date(). eg MO. SA)) In addition. See matplotlib.timezone instance with the tz keyword argument to num2date(). See rrule example. pass a pytz. tickers and formatters are timezone aware. matplotlib dates . and the default timezone is given by the timezone parameter in your matplotlibrc ﬁle. this class picks the best MultipleDateLocator to set the view limits and the tick locations.1. For example: # tick on mondays every week loc = WeekdayLocator(byweekday=MO.rrule (dateutil) which allow almost arbitrary date tick speciﬁcations.

tz=None) x is a ﬂoat value which gives the number of days (fraction part represents hours. delta) Return a date range as ﬂoat Gregorian ordinals. tz is the tzinfo instance. Use a strftime() format string. minutes.dates. Python only supports datetime strftime() formatting for years greater than 1900. Also. If x is a sequence. The addition of one here is a historical artifact.num2date(x. matplotlib. fmt) 43. see the module docstring.1.dates.date2num(d) d is either a datetime instance or a sequence of datetimes. tz=None) Bases: matplotlib. Return value is a datetime instance in timezone tz (default to rcparams TZ value). delta is a datetime.0. minutes.dates. matplotlib. plus one.1. The addition of one here is a historical artifact. dstart and dend are datetime instances.DateFormatter(fmt.num2epoch(d) Convert days since 0001 to epoch. class matplotlib. Dalke Scientiﬁc Software who contributed the strftime() code below to include dates earlier than this year. matplotlib. matplotlib.dates.Formatter Tick location is seconds since the epoch.2 Date formatters Here all all the date formatters: • AutoDateFormatter: attempts to ﬁgure out the best format to use. For details.mx2num(mxdates) Convert mx datetime instance (or sequence of mx instances) to the new date format. Return value is a ﬂoating point number (or sequence of ﬂoats) which gives the number of days (fraction part represents hours.Matplotlib. this is not universal practice.drange(dstart.dates 587 .ticker.1 43.dates. For details. seconds) since 0001-01-01 00:00:00 UTC plus one.timedelta instance.epoch2num(e) Convert an epoch or sequence of epochs to the new date format. seconds) since 0001-01-01 00:00:00 UTC. note that the Gregorian calendar is assumed. • DateFormatter: use strftime() format strings • IndexDateFormatter: date plots with implicit x indexing. This is most useful when used with the AutoDateLocator. Release 1. dend. matplotlib. a sequence of datetime objects will be returned.dates. d can be a number or sequence. note that the Gregorian calendar is assumed. matplotlib. fmt is an strftime() format string. set_tzinfo(tz) strftime(dt. that is days since 0001. this is not universal practice.dates. Also. matplotlib. see the module docstring. Thanks to Andrew Dalke.

AutoDateLocator(tz=None. The default format is the one to use if none of the times in scaled match class matplotlib. ’%H:%M:%D’.dates. class matplotlib. defaultfmt=’%Y-%m-%d’) Bases: matplotlib.)] = ’%M:%S’ # only show min and sec Autofmt the date labels.0 : 30. fmt is a strftime() format string.ticker. 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.DateLocator maxticks=None. datalim_to_dt() nonsingular(vmin.DateLocator autoscale() Set the view limits to include the data range.AutoDateFormatter(locator.ticker. : } = { ’%Y’. This is most useful when used with the AutoDateLocator.dates. : 1. matplotlib dates .dates. Release 1. inter- On autoscale.dates. The default looks like this: self.DateLocator(tz=None) Bases: matplotlib. ’%b %d %Y’.0. ’%b %Y’.1 class matplotlib. vmax) set_tzinfo(tz) viewlim_to_dt() class matplotlib. minticks=5. this class picks the best MultipleDateLocator to set the view limits and the tick locations.Matplotlib.0 : 1.ticker.dates.Formatter Use with IndexLocator to cycle format strings by index.Formatter This class attempts to ﬁgure out the best format to use. t is a sequence of dates (ﬂoating point days). 588 Chapter 43. fmt. tz=None. val_multiples=False) Bases: matplotlib. You can customize this dictionary by doing: formatter = AutoDateFormatter() formatter./24.Locator tz is a tzinfo instance. tz=None) Bases: matplotlib.dates. tz=None) Bases: matplotlib.*60.scaled 365.scaled[1/(24.RRuleLocator(o. static get_unit_generic(freq) class matplotlib.dates. The algorithm picks the key in the dictionary that is >= the current scale and uses that format string.IndexDateFormatter(t.

get_locator(dmin. MINUTELY: [1. 15. which controls any interval between ticks (ticking every other. 6. etc. tz is a tzinfo instance. 10. etc. Examples: # Tick every year on Jan 1st locator = YearLocator() 43. The AutoDateLocator has an interval dictionary that maps the frequency of the tick (a constant from dateutil.Matplotlib. 2.intervald[HOURLY] = [3] # only show every 3 hours autoscale() Try to choose the view limits intelligently. 2.YearLocator(base=1. maxticks is the maximum number of ticks desired.) to their own maximum number of ticks. 14]. 15. dmax) Pick the best locator based on a distance. MONTHLY. 10].dates. DAILY : [1.6.18 when hourly ticking is done at 6 hour intervals.rrule) and a multiple allowed for that ticking. 7. Any frequency not speciﬁed in this dictionary is given a default value. 15 or 30 make sense. 2. month=1.). matplotlib. 5.dates 589 . 30] The interval is used to specify multiples that are appropriate for the frequency of ticking. tz=None) Bases: matplotlib.12. For instance. You can customize this dictionary by doing: locator = AutoDateLocator() locator. SECONDLY: [1.). etc.DateLocator Make ticks on a given day of each year that is a multiple of base. 6]. set_axis(axis) class matplotlib. For example.0. 3.intervald = { YEARLY : [1. The default looks like this: self. HOURLY : [1. but for minutes/seconds. interval_multiples is a boolean that indicates whether ticks should be chosen to be multiple of the interval. which is used to select the type of ticking (yearly. 12]. This can be used to keep the number of ticks appropriate to the format chosen in class:AutoDateFormatter. 3. 4. This will lock ticks to ‘nicer’ locations. monthly. every 7 days is sensible for daily ticks. this will force the ticks to be at hours 0. 2.1. 4. 30]. every 3.dates. 5. MONTHLY : [1. Release 1. 5. } 4. 10. day=1.1 minticks is the minimum number of ticks desired. this can be a dictionary mapping individual rrule frequency constants (YEARLY. refresh() Refresh internal information based on current limits. 3. For really ﬁne-grained control.

interval speciﬁes the number of weeks to skip.e. TH. interval is the interval between each iteration.32) class matplotlib.dates. byweekday can be a number or sequence. class matplotlib. class matplotlib. if interval=2. mark every second occurrence. Default is range(1.MonthLocator(bymonth=None. eg 1. i.rrule. interval=1.MinuteLocator(byminute=None. For example.DayLocator(bymonthday=None. autoscale() Set the view limits to include the data range. every month. matplotlib dates . tz=None) Bases: matplotlib. 12. TU.HourLocator(byhour=None. Default is to tick every day of the month: bymonthday=range(1. interval=1. For example. For example. SU.Matplotlib. mark every second occurance.dates. FR. 1. Mark every weekday in byweekday. Default is to tick every hour: byhour=range(24) interval is the interval between each iteration. bymonthday=1.WeekdayLocator(byweekday=1.RRuleLocator Make ticks on occurances of each month month. 15. class matplotlib. byhour can be an int or sequence.dates.1 # Tick every 5 years on July 4th locator = YearLocator(5.dates.0. Mark every minute in byminute. byminute can be an int or sequence. bymonth can be an int or sequence.dates.dates. class matplotlib. 3.dates. interval=1. bymonthday can be an int or sequence.RRuleLocator Make ticks on occurances of each day of the month.dates. tz=None) Bases: matplotlib. For example. interval=1.dates. tz=None) Bases: matplotlib.RRuleLocator Make ticks on occurances of each minute. Mark every day in bymonthday. tz=None) Bases: matplotlib. Mark every month in bymonth. Elements of byweekday must be one of MO.dates. interval=1. 30. tz=None) Bases: matplotlib.RRuleLocator Make ticks on occurances of each hour. month=7.RRuleLocator Make ticks on occurances of each weekday. interval=2 plots every second week. SA. Default is to tick every minute: byminute=range(60) 590 Chapter 43. Mark every hour in byhour. the constants from dateutils. Release 1. if interval=2. day=4) Mark years that are multiple of base on a given month and day (default jan 1).13). WE.

minutes=0.dates 591 . minute. second=None. Not specifying it is the same as specifying +1. nlyearday=None. byeaster=None. and the date found is post 28 of february.dates. seconds. Release 1. class matplotlib. wkst=None. bymonthday=None.dates. hour. microsecond: Absolute information. datetime2) And the other way is to use the following keyword arguments: year.relativedelta(dt1=None. hour=None. byweekno=None. class matplotlib. cache=False) Bases: dateutil.DateTime extension. For example. TU. There’s two diﬀerent ways to build a relativedelta instance. years. day. These instances may receive a parameter N. mark every second occurrence. interval=1. byhour=None. nlyearday: Set the yearday or the non-leap year day (jump leap days). interval=1.dates.rrule. microseconds: Relative mation. day=None. if year is a leap year. For example. Lemburg in his mx. dtstart=None. dt2=None. weeks. year=None.1 interval is the interval between each iteration.-A. yearday. leapdays: Will add given days to the date found. where 0=MO. hours=0. days=0. hours. yearday=None.1. Mark every second in bysecond. microseconds=0. notice that this type does NOT implement the same algorithm as his work. specifying the Nth weekday. Default is to tick every second: bysecond = range(60) interval is the interval between each iteration. if interval=2. weeks=0.rrulebase class matplotlib. These are converted to day/month/leapdays information.dates. mark every second occurrence. if interval=2.Matplotlib. leapdays=0. month=None. second. which could be positive or negative (like MO(+1) or MO(-2). bymonth=None. weekday=None. minutes. Here is the behavior of operations with relativedelta: 43. However. infor- weekday: One of the weekday instances (MO. months=0. may be negative. seconds=0. bysecond=None. matplotlib.0. until=None.RRuleLocator Make ticks on occurances of each second. byminute=None. days.DateTime’s counterpart. You can also use an integer.SecondLocator(bysecond=None. months. month. bysetpos=None. The ﬁrst one is passing it two date/datetime classes: relativedelta(datetime1. etc). minute=None. tz=None) Bases: matplotlib. byweekday=None.rrule(freq. byyearday=None. bysecond can be an int or sequence. microsecond=None) The relativedelta type is based on the speciﬁcation of the excelent work done by M. years=0. count=None. Do NOT expect it to behave like mx.

and nth is the number of weeks to add forward or backward. or the original datetime year. 1) or (0.dates. matplotlib. -1) won’t change the day.dates. 3. Notice that if the calculated date is already Monday. matplotlib. with the given (wday.Add the relative ‘days’ argument to the absolute day.1 1. or the original datetime day.Add the relative ‘years’ argument to the absolute year. wday is the index of the weekday (0-6.Do steps 1 and 2 for hour/hours. Release 1.dates. 0=Mon). using (0.seconds(s) Return seconds as days. using the ‘year’ argument. if the argument is not present.Do steps 1 and 2 for month/months. 7. 4. Notice that the ‘weeks’ argument is multiplied by 7 and added to ‘days’.dates.minutes(m) Return minutes as days. nth) tuple. minute/minutes. 5.If the ‘weekday’ argument is present. matplotlib dates . if the argument is not present. matplotlib. 6. Then. subtract from the day until it ﬁts in the year and month found after their operations. depending on its signal. 592 Chapter 43. calculate the weekday.weeks(w) Return weeks as days. matplotlib.0.hours(h) Return hours as days. for example.Calculate the absolute day. using the ‘day’ argument. 2. microsecond/microseconds.Calculate the absolute year.Matplotlib. second/seconds.

figure.figure The ﬁgure module provides the top-level Artist. defaults to rc figure.cbook. The events you can connect to are ‘dpi_changed’.Artist The Figure instance supports callbacks through a callbacks attribute which is a matplotlib. frameon=True.artist. defaults to rc add_axes(*args.CallbackRegistry instance. height] where all quantities are in fractions of 593 . dpi=None.edgecolor linewidth the ﬁgure patch edge linewidth. The ﬁgure patch is drawn by a the attribute patch a matplotlib. the Figure. linewidth=1. bottom. the ﬁgure will make composite images depending on the renderer option_image_nocomposite function. width. the default linewidth of the frame frameon if False.1 matplotlib. edgecolor=None.facecolor edgecolor the ﬁgure patch edge color.CHAPTER FORTYFOUR MATPLOTLIB FIGURE 44.h tuple in inches dpi dots per inch facecolor the ﬁgure patch facecolor.Figure(ﬁgsize=None. **kwargs) Add an a axes with axes rect [left.0.Rectangle instance suppressComposite for multiple ﬁgure images. and the callback will be called with func(fig) where ﬁg is the Figure instance. If suppressComposite is True|False. facecolor=None. which contains all the plot elements.patches. subplotpars=None) Bases: matplotlib. this will override the renderer ﬁgsize w. suppress drawing the ﬁgure frame subplotpars a SubplotParams instance. The following classes are deﬁned SubplotParams control the default spacing of the subplots Figure top level container for all plot elements class matplotlib. defaults to rc figure.

Bbox instance [True | False] [ (Path. The axes label attribute has been exposed for this purpose. ‘rectilinear’].add_axes(rect) fig. If you do not want this behavior. which is equivalent to projection=’polar’). fig. color) tuple unknown Continued on next page Chapter 44.add_axes(rect.see colors() unknown unknown [ True | False ] a matplotlib. eg. you want to force the creation of a new axes.0 opaque) unknown [True | False] unknown unknown unknown unknown an Axes instance unknown any matplotlib color . you must use a unique set of args and kwargs. axisbg=’g’) polar=True) projection=’polar’) # add an Axes instance If the ﬁgure already has an axes with the same parameters.h fig. fig.1 ﬁgure width and height. which may be provided to add_axes(): rect = l. Some of these projections support additional kwargs.add_axes(rect. ‘hammer’. ‘lambert’. ‘mollweide’. if you want two axes that are otherwise identical to be added to the ﬁgure. matplotlib ﬁgure 594 .add_axes(ax) frameon=False. Valid values for projection are: [’aitoﬀ’. ‘polar’. label=’axes2’) The Axes instance will be returned. 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 ﬂoat (0.Matplotlib. Eg. kwargs are legal Axes kwargs plus projection which sets the projection type of the axes.transforms.w. (For backward compatibility. polar=True may also be provided.add_axes(rect. make sure you give them unique labels: fig.b..add_axes(rect. label=’axes1’) fig. Transform) | Patch | None ] unknown a callable function a (ﬂoat. then it will simply make that axes current and return it. Release 1. fig.0 transparent through 1.add_axes(rect.0.

(For backward compatibility. polar=True) # add a polar subplot ﬁg. ‘rectilinear’]. ‘lambert’.add_subplot(111) ﬁg. matplotlib. which chooses a projection type for the axes. func(self) will be called add_subplot(*args. which is equivalent to projection=’polar’).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|ﬂoat|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 ﬂoats xmargin unknown xscale [’linear’ | ‘log’ | ‘symlog’] xticklabels sequence of strings xticks sequence of ﬂoats ybound unknown ylabel str ylim len(2) sequence of ﬂoats ymargin unknown yscale [’linear’ | ‘log’ | ‘symlog’] yticklabels sequence of strings yticks sequence of ﬂoats zorder any number add_axobserver(func) whenever the axes state change.figure 595 . axisbg=’r’) # add subplot with red background ﬁg.1 Table 44. ‘polar’. ‘hammer’. which 44.add_subplot(sub) # add Subplot instance sub kwargs are legal matplotlib.axes.add_subplot(212. ‘mollweide’.Matplotlib. Some of these projections support additional kwargs. Release 1.1) # equivalent but more general ﬁg.add_subplot(111.0. Valid values for projection are: [’aitoﬀ’.1. **kwargs) Add a subplot.add_subplot(1. Examples: ﬁg.1. polar=True may also be provided.Axes kwargs plus projection.

matplotlib ﬁgure 596 .0 opaque) unknown [True | False] unknown unknown unknown unknown an Axes instance unknown any matplotlib color . The Axes instance will be returned. Transform) | Patch | None ] unknown a callable function a (ﬂoat.Bbox instance [True | False] [ (Path.1 may be provided to add_axes().0. Release 1. 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 ﬂoat (0.see colors() unknown unknown [ True | False ] a matplotlib.transforms. color) tuple unknown [ True | False ] an id string any string [True | False] [ True | False ] unknown [None|ﬂoat|boolean|callable] unknown unknown [True | False | None] unknown str Transform instance a url string [True | False] unknown Continued on next page Chapter 44.0 transparent through 1. If the ﬁgure already has a subplot with key (args. kwargs) then it will simply make that subplot current and return it.Matplotlib.

20000000000000001. cax=None.1 Table 44. as well as turn oﬀ xlabels. a gui widget is tracking the axes in the ﬁgure. and it helps to rotate them on the bottom subplot and turn them oﬀ on other subplots. Function signatures for the pyplot interface. **kwargs) colorbar(mappable.2 – continued from previous page xlabel str xlim len(2) sequence of ﬂoats xmargin unknown xscale [’linear’ | ‘log’ | ‘symlog’] xticklabels sequence of strings xticks sequence of ﬂoats ybound unknown ylabel str ylim len(2) sequence of ﬂoats ymargin unknown yscale [’linear’ | ‘log’ | ‘symlog’] yticklabels sequence of strings yticks sequence of ﬂoats zorder any number autofmt_xdate(bottom=0. The ticklabels are often long.clf clf(keep_observers=False) Clear the ﬁgure. ha=’right’) Date ticklabels often overlap. Release 1. rotation=30. cax=cax.1. 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 ﬁgure – synonym for ﬁg. for example. Also. a common use case is a number of subplots with shared xaxes where the x-axis is date data.0. matplotlib.Matplotlib. ax=ax. so it is useful to rotate them and right align them.figure 597 . all but the ﬁrst are also method signatures for the colorbar() method: colorbar(**kwargs) colorbar(mappable. Set keep_observers to True if. **kwargs) colorbar(mappable. **kwargs) arguments: 44. ax=None. colorbar(mappable. Documentation for the pylab thin wrapper: Add a colorbar to a plot. **kw) Create a colorbar for a ScalarMappable instance.

etc. when the mappable has norm=NoNorm()). to which the colorbar applies. ticks are determined automatically from the input. which sets the default to the current image. drawedges [ False | True ] If true. These are set for a given colormap using the colormap set_under and set_over methods.Matplotlib.0. the mat ScalarFormatter is used. draw lines at color boundaries. matplotlib ﬁgure . make pointed tend end(s) for out-of. An alternative Formatter object may be given instead.3f’. for. 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.[ ‘uniform’ | ‘proportional’ ] Uniform spacing gives each discrete ing color the same space. e.Description erty ex[ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] If not ‘neither’. ContourSet.05 if vertical. proportional makes the space proportional to the data interval. 0. this argument is mandatory for the colorbar() method but optional for the colorbar() function. The following will probably be useful only in the context of indexed colors (that is.0.15. ticks [ None | list of ticks | Locator object ] If None.15 if horizontal. ‘%. spac.g. that is used. fraction by which to shrink the colorbar 20. fraction of original axes between colorbar and new image axes 1. or other unusual circumstances. 598 Chapter 44. Release 1.range values.[ None | format string | Formatter object ] If None. fraction of original axes to use for colorbar 0.1 mappable the Image. ratio of long to short dimensions colorbar properties: Prop. If a format string is given.

xo=0. the color mapped to the corresponding value in values will be used. *args. In this case. do not use any of the axes properties kwargs. vmin=None.1. alpha=None. see also its base class.{} delaxes(a) remove a from the ﬁgure and update the current axes dpi draw(artist. matplotlib. Call the set_label() method to label the colorbar. figimage(X. returns: Colorbar instance. cmap=None.artist. yo. For each region delimited by adjacent entries in boundaries. vmax=None. you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn.Matplotlib. **kwargs) call signatures: figimage(X. **kwargs) Render the ﬁgure using matplotlib. **kwargs) adds a non-resampled array X to the ﬁgure.backend_bases. Returns True. renderer. ColorbarBase. its extend kwarg is included automatically.RendererBase instance renderer draw_artist(a) draw matplotlib. Release 1. Note that the shrink kwarg provides a simple way to keep a vertical colorbar. xo. If the colorbar is too tall (or a horizontal colorbar is too wide) use a smaller value of shrink. but it is a manual method requiring some trial and error. X must be a ﬂoat array: •If X is MxN. assume RGB 44. assume luminance (grayscale) •If X is MxNx3.Description erty bound. If mappable is a ContourSet. for example.0. norm=None.None or a sequence which must be of length 1 less than the ues sequence of boundaries. yo=0.figure 599 .Artist instance a only – this is available only after the ﬁgure is drawn figimage(X. For more precise control. origin=None. yo) with pixel oﬀsets xo. contains(mouseevent) Test whether the mouse event occurred on the ﬁgure.None or a sequence aries val. from being taller than the axes of the mappable to which the colorbar is attached.1 Prop.

default to the rc image.image. 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 ﬂoat (0. This scales luminance -> 0-1 vmin|vmax used to scale a luminance image to 0-1. the settings for vmin and vmax will be ignored. Defaults to the rc image. matplotlib ﬁgure . assume RGBA Optional keyword arguments: Keyword xo or yo cmap Description An integer.jet.origin value ﬁgimage complements the axes image (imshow()) which will be resampled to ﬁt the current axes. Note if you pass a norm instance.cmap value norm a matplotlib. If either is None. Release 1. Additional kwargs are Artist kwargs passed on to FigureImage gca(**kwargs) Return the current axes.0] index of the array is in the gin upper left or lower left corner of the axes.colors. If None.1 •If X is MxNx4. the min and are max of the luminance values will be used. default is None pha ori[ ‘upper’ | ‘lower’ ] Indicates where the [0.1.FigureImage instance is returned. If you want a resampled image to ﬁll the entire ﬁgure. the x and y image oﬀset in pixels a matplotlib.Normalize instance.0 opaque) unknown [True | False] unknown unknown unknown unknown an Axes instance unknown any matplotlib color .Matplotlib.1].ColorMap instance. althe alpha blending value.see colors() unknown unknown [ True | False ] Continued on next page 600 Chapter 44.0 transparent through 1.cm. eg cm. you can deﬁne an Axes with size [0. An matplotlib. The default is normalization().0.0.

Bbox instance clip_on [True | False] clip_path [ (Path. 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|ﬂoat|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 ﬂoats xmargin unknown xscale [’linear’ | ‘log’ | ‘symlog’] xticklabels sequence of strings xticks sequence of ﬂoats ybound unknown ylabel str ylim len(2) sequence of ﬂoats ymargin unknown yscale [’linear’ | ‘log’ | ‘symlog’] yticklabels sequence of strings yticks sequence of ﬂoats zorder any number get_axes() get_children() get a list of artists contained in the ﬁgure get_dpi() Return the dpi as a ﬂoat 44. Transform) | Patch | None ] color_cycle unknown contains a callable function cursor_props a (ﬂoat.figure 601 .Matplotlib.transforms.1. matplotlib.0.1 Table 44. Release 1.3 – continued from previous page clip_box a matplotlib.

mouse_add=1. and axis ticklabels. It only accounts axes title. axis labels. Needs improvement. Release 1.0. 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 ﬁgheight as a ﬂoat get_figwidth() Return the ﬁgwidth as a ﬂoat get_frameon() get the boolean indicating frameon get_size_inches() get_tightbbox(renderer) Return a (tight) bounding box of the ﬁgure in inches. get_window_extent(*args. timeout=30. matplotlib ﬁgure . kwargs are void ginput(n=1. **kwargs) get the ﬁgure bounding box in display space. mouse_stop=2) call signature: 602 Chapter 44. show_clicks=True.Matplotlib.

8.1 ginput(self. line2. 3. 2. ’upper right’) The loc location codes are: ’best’ : 0. labels. Release 1. If timeout is zero or negative. ’label2’.Matplotlib. does not timeout. handles is a sequence of Line2D or Patch instances. that give the associated mouse button: 1 for left. Right clicking cancels last input. accumulate clicks until a middle click (or potentially both mouse buttons at once) terminates the input. (’label1’.e. matplotlib. the enter key terminates input and any other key (not already used by the window manager) selects a point. mouse_add=1. *args. Labels are a sequence of strings. show_clicks=True. 4. 7.. n=1. **kwargs) Place a legend in the ﬁgure. mouse_stop=2) Blocking call to interact with the ﬁgure. 3 for right. timeout=30. remove last point). mouse_pop=3. If hold is None (default).0. hold(b=None) Set the hold state. Else set the hold state to boolean value b.1. removing points.figure 603 . Eg: hold() # toggle hold hold(True) # hold is on hold(False) # hold is off legend(handles. and loc can be a string or an integer specifying the legend location USAGE: legend( (line1. 6. The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. terminating the inputs) can be overriden via the arguments mouse_add. 2 for middle. This will wait for n clicks from the user and return a list of the coordinates of each click. line3). ’label3’). toggle the hold state. ’upper right’ ’upper left’ ’lower left’ ’lower right’ ’right’ ’center left’ ’center right’ ’lower center’ (currently not supported for figure legends) : : : : : : : : 1. If n is zero or negative. 44. The buttons used for the various actions (adding points. The delete and backspace keys act like right clicking (i. 5. mouse_pop and mouse_stop.

Values from rcParams will be used if None. If None. Release 1. numpoints: integer The number of points in the legend line. facecolor=’w’.FontProperties instance. a new instance will be created with prop. original. top. **kwargs) call signature: savefig(fname. edgecolor=’w’. transparent=False. ncol [integer] number of columns. draw a frame with a round fancybox. The dimensions of these values are given as a fraction of the fontsize.1 is the right. Keyword borderpad labelspacing handlelength handletextpad borderaxespad columnspacing Example: savefig(*args. orientation=’portrait’.1 ’upper center’ : 9. fancybox: [ None | False | True ] if True. default is 4 scatterpoints: integer The number of points in the legend line.Matplotlib. bbox_inches=None. ﬁgure coords are (0. use rc shadow: [ None | False | True ] If True. which speciﬁes the lower left of the legend box. default is 1 mode [[ “expand” | None ]] if mode is “expand”. use rc settings. the legend will be horizontally expanded to ﬁll the axes area (or bbox_to_anchor) title [string] the legend title Padding and spacing between various elements use following keywords parameters. draw a shadow behind legend. papertype=None. matplotlib ﬁgure . If None. use rc settings. loc can also be an (x. default is 4 scatteroﬀsets: list of ﬂoats a list of yoﬀsets for scatter symbols in legend markerscale: [ None | scalar ] The relative size of legend markers vs.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 ﬁgure. pad_inches=0. use rc settings. If None. bottom of the ﬁgure and 1.0) is the left.y) tuple in ﬁgure coords. If None. Keyword arguments: prop: [ None | FontProperties | dict ] A matplotlib.font_manager. dpi=None. If prop is a dictionary. ’center’ : 10. format=None.0. 604 Chapter 44.

Release 1.0 1.1. Arguments: fname: A string containing a path to a ﬁlename. Keyword arguments: dpi: [ None | scalar > 0 ] The resolution in dots per inch. 44. If fname is not a string.5 1.5 1. currently only on postscript output papertype: One of ‘letter’. ‘b0’ through ‘b10’. or a Python ﬁle-like object. the output format is deduced from the extension of the ﬁlename. ‘executive’. If the ﬁlename has no extension. or possibly some backend-dependent object such as PdfPages. ‘ledger’.0 0. ‘legal’.0 0. If None it will default to the value savefig.dpi in the matplotlibrc ﬁle. If that value is ‘auto’. If format is None and fname is a string.0 Line 3 Line 4 1.0 0.0. facecolor.0 0.extension is used.5 0.5 0. the backend determines the extension.0 0.5 1. ‘a0’ through ‘a10’.figure 605 . the value of the rc parameter savefig.5 1.0 The output formats available depend on the backend being used. Only supported for postscript output.5 1.0 0. remember to specify format to ensure that the correct backend is used.0 0.0 0.0 2.5 2. matplotlib.1 Line 1 Line 2 1.Matplotlib. edgecolor: the colors of the ﬁgure rectangle orientation: [ ‘landscape’ | ‘portrait’ ] not supported on all backends.

Only the given portion of the ﬁgure is saved. ps. transparent: If True. forward=False) 606 Chapter 44. pad_inches: Amount of padding around the ﬁgure when bbox_inches is ‘tight’. sca(a) Set the current axes to be a and return a set_canvas(canvas) Set the canvas the contains the ﬁgure ACCEPTS: a FigureCanvas instance set_dpi(val) Set the dots-per-inch of the ﬁgure ACCEPTS: ﬂoat set_edgecolor(color) Set the edge color of the Figure rectangle ACCEPTS: any matplotlib color . Most backends support png. eps and svg. matplotlib ﬁgure . for example.see help(colors) set_facecolor(color) Set the face color of the Figure rectangle ACCEPTS: any matplotlib color . the axes patches will all be transparent. The transparency of these patches will be restored to their original values upon exit of this function. Release 1.1 format: One of the ﬁle extensions supported by the active backend. the ﬁgure patch will also be transparent unless facecolor and/or edgecolor are speciﬁed via kwargs.Matplotlib. bbox_inches: Bbox in inches. **kwargs) set_size_inches(w. If ‘tight’. for displaying a plot on top of a colored background on a web page. pdf.0.h. bbox_extra_artists: A list of extra artists that will be considered when the tight bbox is calculated. This is useful. try to ﬁgure out the tight bbox of the ﬁgure.see help(colors) set_figheight(val) Set the height of the ﬁgure in inches ACCEPTS: ﬂoat set_figwidth(val) Set the width of the ﬁgure in inches ACCEPTS: ﬂoat set_frameon(b) Set whether the ﬁgure frame (background) is displayed or invisible ACCEPTS: boolean set_size_inches(*args.

kwargs control the Text properties: Property agg_filter alpha animated axes backgroundcolor bbox Description unknown ﬂoat (0.subplots_adjust(left=None.h tuple with w. y. See text() for the meaning of the other arguments. eg you can resize the ﬁgure window from the shell ACCEPTS: a w. fontdict=None. **kwargs) ﬁg. Example: fig.1.Matplotlib.suptitle(’this is the figure title’. y. **kwargs) Add text to ﬁgure at location x. wspace=None.text. Release 1. matplotlib. *args. kwargs are matplotlib. hspace=None) Update the SubplotParams with kwargs (defaulting to rc where None) and update the subplot locations suptitle(t. fontsize=12) text(x. top=None.5 the x location of text in ﬁgure coords •y = 0. s. y (relative 0-1 coords).figure 607 . right=None. **kwargs) Call signature: figtext(x.h) # OR fig. the defaults are: •x = 0.set_size_inches((w.98 the y location of the text in ﬁgure coords •horizontalalignment = ‘center’ the horizontal alignment of the text •verticalalignment = ‘top’ the vertical alignment of the text A matplotlib. **kwargs) Add a centered title to the ﬁgure.1 Set the ﬁgure size in inches Usage: fig.text.Text instance is returned.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict 44. s.Text properties.0. Using ﬁgure coordinates.0 transparent through 1. bottom=None.h in inches subplots_adjust(*args.h) ) optional kwarg forward=True will cause the canvas size to be automatically updated.set_size_inches(w.

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. If timeout is negative.FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.Figure instance a matplotlib. matplotlib ﬁgure .figure.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. 608 Chapter 44.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’ | ﬂoat ﬂoat any number waitforbuttonpress(timeout=-1) call signature: waitforbuttonpress(self. This will return True is a key was pressed.transforms.0. timeout=-1) Blocking call to interact with the ﬁgure.font_manager.Matplotlib. False if a mouse button was pressed and None if timeout was reached without either being pressed.Bbox instance [True | False] [ (Path. Transform) | Patch | None ] any matplotlib color a callable function [ FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] a matplotlib. does not timeout.

0.2 the amount of height reserved for white space between subplots validate make sure the params are in a legal state (left*<*right.9 the top of the subplots of the ﬁgure wspace = 0. etc) update(left=None. right=None. height in inches are returned.figure 609 . hspace=None) A class to hold the parameters for a subplot All dimensions are fraction of the ﬁgure width or height. if set. hspace=None) Update the current values. otherwise to rc matplotlib.figure. top=None. 0. The ﬁgure width. 0. bottom=None.SubplotParams(left=None. 0.2 the amount of width reserved for blank space between subplots hspace = 0.add_axes([0. **kwargs) Thanks to Fernando Perez for this function 44. eg Example usage: # make a figure twice as tall as it is wide w.Matplotlib.1. If arg is an array. wspace=None.8]) ax.figure.figaspect(arg) Create a ﬁgure with speciﬁed aspect ratio.h)) ax = fig.1. All values default to their rc params The following attributes are available left = 0. use that aspect ratio. h = figaspect(A) fig = Figure(figsize=(w.1 the bottom of the subplots of the ﬁgure top = 0. 0.8.add_axes([0.0.1. ﬁgaspect will determine the width and height for a ﬁgure that would ﬁt array preserving aspect ratio.8]) ax.1. If arg is a number.imshow(A.125 the left side of the subplots of the ﬁgure right = 0. wspace=None. Release 1.3) w. right=None.) fig = Figure(figsize=(w.9 the right side of the subplots of the ﬁgure bottom = 0. 0.1 class matplotlib. h = figaspect(2.h)) ax = fig.imshow(A. top=None. bottom=None.1. Be sure to create an axes with equal with and height. If any kwarg is None.8. matplotlib. default to the current value. **kwargs) # make a figure with the proper aspect for an array A = rand(5.

Release 1. matplotlib ﬁgure .Matplotlib.0.1 610 Chapter 44.

variant. the default font (usually Vera Sans) is returned. variant=’normal’. style. To enable it. OS X. class matplotlib.1 matplotlib. weight. It is used when populating the font lookup dictionary. Level 1 (CSS1) font speciﬁcation. The ﬁrst font with the highest score is returned. This module provides a single FontManager instance that can be shared across backends and platforms. directory. The findfont() method does a nearest neighbor search to ﬁnd the font that most closely matches the speciﬁcation. class matplotlib. it is much more likely to be found. and size.font_manager A module for ﬁnding. The findfont() function returns the best TrueType (TTF) font ﬁle in the local or system font path that matches the speciﬁed FontProperties instance. Fontconﬁg has the advantage that it is the standard way to look up fonts on X11 platforms. If no good enough match is found. will only return fonts from the given directory (or subdirectory of that directory).FontManager(size=None. and using fonts across platforms. fontext=’ttf’. Each font is given a similarity score to the target font properties. fallback_to_default=True. name=’‘. 611 . Solaris). the FontManager singleton instance creates a list of TrueType fonts based on the font properties: name. Future versions may implement the Level 2 or 2. so if a font is installed. weight=’normal’) On import.FontEntry(fname=’‘. managing. size=’medium’) Bases: object A class for storing Font properties. rebuild_if_missing=True) Search the font list for the font that most closely matches the FontProperties prop. set the constant USE_FONTCONFIG in this ﬁle to True. The FontManager also handles Adobe Font Metrics (AFM) font ﬁles for use by the PostScript backend. style=’normal’. a default font is returned. findfont(prop. stretch. The design is based on the W3C Cascading Style Sheet. stretch=’normal’. findfont() performs a nearest neighbor search. weight=’normal’.font_manager.font_manager.CHAPTER FORTYFIVE MATPLOTLIB FONT_MANAGER 45. If no matches below a certain threshold are found. directory=None. Experimental support is included for using fontconﬁg on Unix variant platforms (Linux. is speciﬁed.1 speciﬁcations.

score_size(size1.0. A match between ‘italic’ and ‘oblique’ returns 0. get_default_size() Return the default font size.72pt) will lie between 0.Matplotlib.0.0 and 1.1 The result is cached. so subsequent lookups don’t have to perform the O(n) nearest neighbor search.0. weight2) Returns a match score between weight1 and weight2. get_default_weight() Return the default font weight. the result is the absolute distance between size1 and size2. Level 1 documentation for a description of the font ﬁnding algorithm. normalized between 0. will fallback to the default font family (usually “Bitstream Vera Sans” or “Helvetica”) if the ﬁrst lookup hard-fails. style2) Returns a match score between style1 and style2. No match will return 1. score_style(style1.0 and 1. An exact match anywhere in the list returns 0. family2) Returns a match score between the list of font families in families and the font family name family2.0. See the W3C Cascading Style Sheet. variant2) Returns a match score between variant1 and variant2. score_variant(variant1.1. normalized so that the usual range of font sizes (6pt . score_weight(weight1. otherwise 1. If size2 (the size speciﬁed in the font ﬁle) is ‘scalable’.0. An exact match returns 0. size2) Returns a match score between size1 and size2. No match returns 1.0. The result is the absolute value of the diﬀerence between the CSS numeric values of stretch1 and stretch2. since any font size can be generated. A match by generic font name will return 0.1.0. matplotlib font_manager . Otherwise. score_family(families. An exact match returns 0. this function always returns 0.0. score_stretch(stretch1. stretch2) Returns a match score between stretch1 and stretch2. If fallback_to_default is True.0. 612 Chapter 45.0. Release 1.

either ‘serif’. class matplotlib. by using the fname kwarg. normal.font_manager.0 and 1. style=None. or ‘monospace’. _init=None) Bases: object A class for storing and manipulating font properties. ‘normal’. stretch=None. ‘x-large’. ‘xxlarge’ or an absolute font size. ‘medium’. ‘small’. ‘x-small’. e.1.ttf ﬁle. e. The initial value is ‘normal’. This class will also accept a fontconﬁg pattern. e. 12 The default font property for TrueType fonts (as speciﬁed in the default matplotlibrc ﬁle) is: sans-serif. 45. size=None. ‘fantasy’.g. This approach allows all text sizes to be made larger or smaller based on the font manager’s default font size. See the documentation on fontconﬁg patterns. ‘normal’. 12. Level 1 font speciﬁcation. if it is the only argument provided.font_manager 613 . The font properties are those described in the W3C Cascading Style Sheet. Currently not implemented. ‘demibold’. ‘extra-condensed’. ‘large’. ‘heavy’. ‘italic’ or ‘oblique’. ‘bold’.FontProperties(family=None. the actual font to be used will be looked up from the associated rcParam in matplotlibrc. ‘condensed’. ‘semi-expanded’. •stretch: A numeric value in the range 0-1000 or one of ‘ultra-condensed’. ‘semi-condensed’. normal. a font may be speciﬁed using an absolute path to a . so the results of the same pattern may be diﬀerent in matplotlib than in other applications that use fontconﬁg.0. normalized between 0. ‘extra-expanded’ or ‘ultra-expanded’ •weight: A numeric value in the range 0-1000 or one of ‘ultralight’.1 The result is the absolute value of the diﬀerence between the CSS numeric values of weight1 and weight2. ‘roman’. set_default_weight(weight) Set the default font weight.Matplotlib. ‘cursive’. fname=None. Alternatively. Release 1. normal. ‘large’. ‘regular’. ‘demi’. Note that matplotlib’s internal font manager and fontconﬁg use a diﬀerent algorithm to lookup fonts. weight=None. ‘black’ •size: Either an relative value of ‘xx-small’. •style: Either ‘normal’. update_fonts(ﬁlenames) Update the font dictionary with new font ﬁles. ‘extra bold’. normal. ‘semibold’. ‘expanded’. ‘medium’. ‘light’. variant=None. matplotlib. The preferred usage of font sizes is to use the relative values. •variant: Either ‘normal’ or ‘small-caps’.g.g. scalable. The six properties are: •family: A list of font names in decreasing order of priority. In that case. ‘sans-serif’. We are merely borrowing its pattern syntax for use here.0. instead of absolute font sizes. This support does not require fontconﬁg to be installed. The items may include a generic font family name. ‘book’.

‘italic’ or ‘oblique’. May be either an alias (generic name is CSS parlance). ‘black’ set_family(family) Change the font family. ‘book’. Options are: ‘ultra-condensed’. ‘semibold’.Matplotlib. ‘roman’. ‘condensed’. get_style() Return the font style. Options are: A numeric value in the range 0-1000 or one of ‘light’. In this case. get_name() Return the name of the font that best matches the font properties. set_fontconfig_pattern(pattern) Set the properties by parsing a fontconﬁg pattern. get_weight() Set the font weight. such as: ‘serif’. get_stretch() Return the font stretch or width. ‘semi-expanded’. set_file(ﬁle) Set the ﬁlename of the fontﬁle to use. ‘normal’. ‘extra bold’. get_variant() Return the font variant. ‘ultraexpanded’. ‘extra-expanded’. matplotlib font_manager .0. ‘italic’ or ‘oblique’. We are merely borrowing its pattern syntax for use here. ‘demi’. ‘fantasy’. ‘normal’. ‘extra-condensed’. ‘demibold’. Values are: ‘normal’ or ‘small-caps’. get_size() Return the font size. or ‘monospace’. 614 Chapter 45. ‘expanded’. ‘cursive’. Release 1.1 copy() Return a deep copy of self get_family() Return a list of font names that comprise the font family. ‘medium’. or a real font name. get_fontconfig_pattern() Get a fontconﬁg pattern suitable for looking up the font as speciﬁed with fontconﬁg’s fc-match utility. get_size_in_points() get_slant() Return the font style. Values are: ‘normal’. This support does not require fontconﬁg to be installed or support for it to be enabled. ‘sans-serif’. ‘bold’. ‘regular’. ‘heavy’. get_file() Return the ﬁlename of the associated font. ‘semi-condensed’. Values are: ‘normal’. See the documentation on fontconﬁg patterns. See the documentation on fontconﬁg patterns. all other properties will be ignored.

‘demibold’. matplotlib.OSXInstalledFonts(directory=None. fontext=’ttf’) A function to create a font lookup list. such as: ‘serif’. set_stretch(stretch) Set the font stretch or width. ‘italic’ or ‘oblique’. ‘large’. font) A function for populating a FontKey instance by extracting information from the AFM font ﬁle. ‘black’ matplotlib. ‘expanded’. ‘light’. This is done by starting at the list of hardcoded paths in OSXFontDirectories and returning all nested directories within them. or ‘monospace’. fontext=’ttf’) Search for fonts in the speciﬁed font paths. matplotlib. ‘heavy’. fontext=’ttf’) Get list of font ﬁles on OS X . ‘x-large’.0. The default is to create a list of TrueType fonts. ‘medium’. ‘extra-condensed’. We are merely borrowing its pattern syntax for use here.Matplotlib. matplotlib.findSystemFonts(fontpaths=None. Values are: ‘normal’.afmFontProperty(fontpath. ‘small’. font is a class:AFM instance.font_manager 615 . If no paths are given. will use a standard set of system paths.font_manager. ‘semibold’. ‘bold’. matplotlib. or a numeric value in the range 0-1000. ‘semi-expanded’. Options are: ‘ultra-condensed’. Either an relative value of ‘xx-small’. set_size(size) Set the font size. ‘sans-serif’. ‘x-small’. 45.1. An AFM font list can optionally be created. or a real font name. ‘normal’. e. matplotlib.font_manager.font_manager. set_slant(style) Set the font style. ‘semi-condensed’. ‘book’. ‘cursive’. ‘xx-large’ or an absolute font size. Release 1. set_style(style) Set the font style. ‘roman’.ignores font suﬃx by default.OSXFontDirectory() Return the system font directories for OS X. ‘demi’. Values are: ‘normal’. ‘condensed’. as well as the list of fonts tracked by fontconﬁg if fontconﬁg is installed and available. **kw) matplotlib. May be either a numeric value in the range 0-1000 or one of ‘ultralight’. ‘normal’.findfont(prop.get_fontconfig_fonts(fontext=’ttf’) Grab a list of all the fonts that are being tracked by fontconﬁg by making a system call to fc-list.1 This support does not require fontconﬁg to be installed or support for it to be enabled. May be either an alias (generic name is CSS parlance). ‘fantasy’.createFontList(fontﬁles. set_weight(weight) Set the font weight. ‘extra-expanded’ or ‘ultraexpanded’. ‘italic’ or ‘oblique’.font_manager. set_variant(variant) Set the font variant. Values are: ‘normal’ or ‘small-caps’. matplotlib.font_manager.font_manager. 12.font_manager. set_name(family) Change the font family. ‘regular’. ‘extra bold’. A list of TrueType fonts are returned by default with AFM fonts as an option. ‘medium’.g.

fontconfig_pattern A module for parsing and generating fontconﬁg patterns.0.font_manager. matplotlib.font_manager. matplotlib.font_manager.font_manager. matplotlib font_manager .x11FontDirectory() Return the system font directories for X11. Release 1. ‘w’)) but closes the ﬁle to prevent ﬁlehandle leakage. or AFM fonts if fontext == ‘afm’.ttfFontProperty(font) A function for populating the FontKey by extracting information from the TrueType font ﬁle.weight_as_number(weight) Return the weight property as a numeric value. open(ﬁlename. matplotlib. matplotlib.font_manager.1 This is an easy way to grab all of the fonts the user wants to be made available to applications. A list of TrueType font ﬁlenames are returned by default. class matplotlib. fontext=’ttf’) Search for fonts in the speciﬁed font directory. 45. $WINDIR/Fonts will be returned.FontconfigPatternParser A simple pyparsing-based parser for fontconﬁg-style patterns.pickle_load(ﬁlename) Equivalent to pickle.win32InstalledFonts(directory=None. See the fontconﬁg pattern speciﬁcation for more information.font_manager. matplotlib.font_manager. This is done by starting at the list of hardcoded paths in X11FontDirectories and returning all nested directories within them. matplotlib.2 matplotlib.pickle_dump(data. 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.dump(data. matplotlib.win32FontDirectory() Return the user-speciﬁed font directory for Win32. matplotlib.ttfdict_to_fnames(d) ﬂatten a ttfdict to all the ﬁlenames it contains matplotlib.get_fontext_synonyms(fontext) Return a list of ﬁle extensions extensions that are synonyms for the given ﬁle extension ﬁleext. 616 Chapter 45. font is a FT2Font instance.font_manager.load(open(ﬁlename. without needing knowing where all of them reside.is_opentype_cff_font(ﬁlename) Returns True if the given font is a Postscript Compact Font Format Font embedded in an OpenType wrapper. String values are converted to their corresponding numeric value.font_manager.font_manager. ﬁlename) Equivalent to pickle.fontconfig_pattern. ‘r’)) but closes the ﬁle to prevent ﬁlehandle leakage. Used by the PostScript and PDF backends that can not subset these fonts.Matplotlib. matplotlib. See the fontconﬁg pattern speciﬁcation for more information. or use the system directories if none given.

value_escape() sub(repl.fontconfig_pattern 617 . count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl. string[.fontconfig_pattern. matplotlib.1 parse(pattern) Parse the given fontconﬁg pattern and return a dictionary of key/value pairs useful for initializing a font_manager. matplotlib. matplotlib. string[. 45. count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl.family_unescape() sub(repl.value_unescape() sub(repl. string[.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. generates a fontconﬁg pattern string.fontconfig_pattern.fontconfig_pattern.2. count = 0]) –> newstring Return the string obtained by replacing the leftmost nonoverlapping occurrences of pattern in string by the replacement repl. Release 1.FontProperties object.generate_fontconfig_pattern(d) Given a dictionary of key/value pairs.fontconfig_pattern. matplotlib. matplotlib. string[.Matplotlib.fontconfig_pattern. matplotlib.0.

1 618 Chapter 45. matplotlib font_manager .0.Matplotlib. Release 1.

class matplotlib. etc. hspace=None.. bottom=None.) can be tuned. default to the current value. SubplotSpec speciﬁes the location of the subplot in the given GridSpec.g.gridspec. right=None. Optionally. etc. The location of grid is determined by similar way as the SubplotParams.. The number of rows and number of columns of the grid need to be set. A base class of GridSpec that speciﬁes the geometry of the grid that a subplot will be placed. right. left=None. width_ratios=None) Bases: object height_ratios=None.gridspec. class matplotlib.g.gridspec gridspec is a module which speciﬁes the location of the subplot in the ﬁgure. left. width_ratios=None. the subplot layout parameters (e. the subplot layout parameters (e. update(**kwargs) Update the current values. Optionally. get_subplot_params(ﬁg=None) return a dictionary of subplot layout parameters. if set. If any kwarg is None. Optionally.GridSpecBase(nrows.GridSpec(nrows. otherwise to rc. get_geometry() get the geometry of the grid. left. top=None. The default parameters are from rcParams unless a ﬁgure attribute is set. ncols.GridSpecBase A class that speciﬁes the geometry of the grid that a subplot will be placed. eg 2. The number of rows and number of columns of the grid need to be set. The number of rows and number of columns of the grid need to be set.gridspec.CHAPTER FORTYSIX MATPLOTLIB GRIDSPEC 46.1 matplotlib. GridSpec speciﬁes the geometry of the grid that a subplot will be placed.) can be tuned. height_ratios=None) Bases: matplotlib. wspace=None. right.3 619 . ncols. the ratio of heights and widths of ros and columns can be speciﬁed.

matplotlib gridspec . If num2 is provided. num2=None) Bases: object speciﬁes the location of the subplot in the given GridSpec.2.gridspec. An instance of SubplotSpec is also needed to be set from which the layout parameters will be inheirted.Matplotlib. Unlike SuplorParams.gridspec. height_ratios=None. rowspan=1.3.GridSpecFromSubplotSpec(nrows. subplot_spec. ncols.gridspec. index is 0-based get_gridspec() get_position(ﬁg. The wspace and hspace of the layout can be optionally speciﬁed or the default values (from the ﬁgure or rcParams) will be used. get_geometry() get the subplot geometry. the subplot will span between num1-th cell and num2-th cell. wspace=None.SubplotSpec(gridspec. width_ratios=None) Bases: matplotlib. hspace=None.subplotpars 620 Chapter 46. num1. colspan=1) create and return a SuplotSpec instance. left and right positions of columns.GridSpecBase GridSpec whose subplot layout parameters are inherited from the location speciﬁed by a given SubplotSpec.0. Release 1. return_all=False) update the subplot position from ﬁg. The subplot will occupy the num1-th cell of the given gridspec. get_subplot_params(ﬁg=None) return a dictionary of subplot layout parameters. class matplotlib. The index stars from 0. get_height_ratios() get_subplot_params(ﬁg=None) get_width_ratios() new_subplotspec(loc. The number of rows and number of columns of the grid need to be set.1 get_grid_positions(ﬁg) return lists of bottom and top position of rows. eg 2. set_height_ratios(height_ratios) set_width_ratios(width_ratios) class matplotlib.

621 .

Release 1.Matplotlib. matplotlib mathtext .0.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.

TruetypeFonts Use the Bakoma TrueType fonts for rendering. since they are already oﬀset correctly from the baseline in TrueType fonts. otherwise this will always just return a scaled version of the glyph.Accent(c. each of which has its own proprietary 8-bit encoding. always=False) Bases: matplotlib. please email mdroe@stsci. state. class matplotlib.mathtext. depth. Symbols are strewn about a number of font ﬁles. If you ﬁnd TeX expressions that don’t parse or render properly. state) Bases: matplotlib.mathtext.1 47. When using a font with multiple height versions of some characters (such as the BaKoMa fonts). For a tutorial of its usage see Writing mathematical expressions.mathtext 623 . grow() render(x. When using a font with multiple width versions of some characters (such as the BaKoMa fonts). shrink() class matplotlib. class matplotlib. There is experimental support for using arbitrary fonts.mathtext. state. height.mathtext.mathtext mathtext is a module for parsing a subset of the TeX math syntax and drawing them to a matplotlib backend.Hlist AutoWidthChar will create a character as close to the given width as possible. The module uses pyparsing to parse the TeX expression. y) Render the character to the canvas. the correct glyph will be selected. char_class=<class ‘matplotlib. but please check KNOWN ISSUES below ﬁrst.mathtext. get_sized_alternatives_for_symbol(fontname.mathtext. class matplotlib. but results may vary without proper tweaking and metrics for those fonts.Matplotlib.mathtext. width.AutoWidthChar(c.Char’>) Bases: matplotlib.1.Char The font metrics need to be dealt with diﬀerently for accents. always=False. The Bakoma distribution of the TeX Computer Modern fonts.0.BakomaFonts(*args.1 matplotlib.AutoHeightChar(c. This document is primarily concerned with implementation details. the correct glyph will be selected.edu.mathtext. and STIX fonts are supported. Release 1. **kwargs) Bases: matplotlib. matplotlib. otherwise this will always just return a scaled version of the glyph. sym) 47.mathtext.Hlist AutoHeightChar will create a character as close to the given height and depth as possible.

mathtext. depth) Bases: matplotlib.mathtext.0.mathtext. It also delegates to a backend class to do the actual drawing. mathtext_backend) Bases: object An abstract base class for a system of fonts to use for mathtext.Fill Bases: matplotlib.mathtext. The class must be able to take symbol keys and font ﬁle names and return the character metrics.mathtext.Node Represents any node with a physical location. and depth.Glue class matplotlib.FT2Image() FT2Image class matplotlib.mathtext. y1.mathtext.mathtext.Filll Bases: matplotlib. Called when characters are strung together into Hlist to create Kern nodes.Fonts(default_font_prop. height.Box(width.Glue class matplotlib. The metrics must be converted to the TeX way.Char(c.mathtext. x2. and the advance (if diﬀerent from width) must be converted into a Kern node when the Char is added to its parent Hlist.1 class matplotlib.Matplotlib. Release 1.Node Represents a single character. matplotlib. height.FT2Font() FT2Font matplotlib. matplotlib mathtext .mathtext. Unlike TeX. state) Bases: matplotlib.Error(msg) Helper class to raise parser errors. y) Render the character to the canvas shrink() matplotlib. 624 Chapter 47. Note that TeX boxes have a width. grow() is_slanted() render(x. get_kerning(next) Return the amount of kerning between this and the given character.mathtext.mathtext.mathtext.mathtext. the font information and metrics are stored with each Char to make it easier to lookup the font metrics when needed. unlike Type1 and Truetype which use a full bounding box and an advance in the x-direction.Fil Bases: matplotlib.Glue class matplotlib. y2) shrink() class matplotlib. grow() render(x1.

mathtext_backend: A subclass of MathTextBackend used to delegate the actual rendering. rm. it. fontsize1. ‘x’ or ‘sigma’ fontsizeX: the fontsize in points dpi: the current dots-per-inch get_metrics(font. ‘1’. xmax. •xmin.mathtext 625 . fontsize2. Should return a list of symbols matching sym in various sizes.1 default_font_prop: A FontProperties object to use for the default non-math font. ymin. ‘1’.0. ‘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. fontX: one of the TeX font names: tt. font2. sym. •width: The width of the glyph in points. cal. or the base font for Unicode (generic) font rendering. ymax . matplotlib. fontclass2. •height: The height of the glyph in points. fontsize. sym2. rm. get_results(box) Get the data needed by the backend to render the math expression. sym) Override if your font provides multiple sizes of the same symbol. dpi) font: one of the TeX font names: tt. e.g. sym1. get_kern(font1.the ink rectangle of the glyph •iceberg . The return value is backendspeciﬁc. it. get_sized_alternatives_for_symbol(fontname. dpi) Get the kerning distance for font between sym1 and sym2. cal.g. bf or default/regular (non-math) font_class: TODO sym: a symbol in raw TeX form. bf or default/regular (non-math) fontclassX: TODO symX: a symbol in raw TeX form. sf. The expression renderer will select the most appropriate size for a given situation from this list.1.Matplotlib. e.the distance from the baseline to the top of the glyph. fontclass1. destroy() Fix any cyclical references before the object is about to be destroyed. 47. Release 1. This corresponds to TeX’s deﬁnition of “height”. font_class. sf.

mathtext.mathtext. get_used_characters() Get the set of characters that were used in the math expression. render_glyph(ox. fontsize. oy. set_canvas_size(w. y2). y1) to (x2.mathtext. get_xheight(font. Used as a base unit for drawing lines such as in a fraction or radical. class matplotlib. sym. h. Used by backends that need to subset fonts so they know which glyphs to include.1 get_underline_thickness(font.0. but it’s easier to stick to what TeX does. shrink_order=0) Bases: object See Glue.Hlist A convenience class to create an Hlist whose contents are centered within its enclosing box.) grow() shrink() class matplotlib.Matplotlib. dpi) Draw a glyph at •ox. dpi) Get the line thickness that matches the given font. stretch=0. copy=False) Bases: matplotlib. dpi) Get the xheight for the given font and fontsize. 626 Chapter 47. y2) Draw a ﬁlled rectangle from (x1.GlueSpec(width=0. render_rect_filled(x1.0.HCentered(elements) Bases: matplotlib.mathtext. copy() classmethod factory(glue_type) class matplotlib. fontsize. fontsize. font_class. matplotlib mathtext . which is shared between multiple glue objects.Node Most of the information in this object is stored in the underlying GlueSpec class. Only really necessary for the bitmap backends. Release 1.mathtext. x2. shrink=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.Glue(glue_type. facename.0. (This is a memory optimization which probably doesn’t matter anymore. d) Set the size of the buﬀer used to render the math expression.0.

’exactly’) produces a box whose width is exactly w.List A horizontal list of boxes.1. •w: speciﬁes a width •m: is either ‘exactly’ or ‘additional’. A kern node can also appear in a vertical list.mathtext. thickness=None) Bases: matplotlib.MathTextParser(output) Bases: object 47.Hrule(state. grow() shrink() class matplotlib.mathtext.mathtext.mathtext. do_kern=True) Bases: 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. and this function just creates the linked list in the correct way.mathtext. m=’additional’. class matplotlib. hpack(w. grow() shrink() class matplotlib. class matplotlib. Thus.mathtext. Release 1.Box A box with only width (zero height and depth). when its width denotes additional spacing in the vertical direction.Kern(width) Bases: matplotlib. or if a \vbox includes other boxes that have been shifted left.0.Hlist(elements. but some items may stick out if negative glue is used.Hbox(width) Bases: matplotlib. The Char nodes themselves determine the amount of kerning they need (in get_kerning()). while hpack(w.Box A list of nodes (either horizontal or vertical).List(elements) Bases: matplotlib.mathtext.0. and to adjust the glue if one of those dimensions is pre-speciﬁed. The computed sizes normally enclose all of the material inside the new box. m=’additional’) The main duty of hpack() is to compute the dimensions of the resulting boxes.mathtext.mathtext. kern() Insert Kern nodes between Char nodes to set kerning.1 class matplotlib. hpack(w=0.mathtext 627 .Node A Kern node has a width ﬁeld to specify a (normally negative) amount of spacing. ’additional’) yields a box whose width is the natural width plus w.Rule Convenience class to create a horizontal rule.0. The default values produce a box with the natural width.Matplotlib. class matplotlib. w=0. matplotlib. if the box is overfull.mathtext.mathtext.

matplotlib mathtext . 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 oﬀset of the baseline from the bottom of the image in pixels. get_depth(texstr. fontsize=14) texstr A valid mathtext string. color=’black’. texstr. Returns the oﬀset of the baseline from the bottom of the image in pixels. it is a FontProperties object specifying the “default” font to use in the math expression. fontsize=14) Writes a tex expression to a PNG ﬁle. fontsize=14) texstr A valid mathtext string. dpi=120. 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. so multiple calls to parse() with the same expression should be fast. The results are cached. 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. to_rgba(texstr. depth) •array is an NxM uint8 alpha ubyte mask array of rasterized tex. color=’black’. prop=None) Parse the given math expression s at the given dpi.1 Create a MathTextParser for the given backend output.Matplotlib. dpi=72. 628 Chapter 47. •depth is the oﬀset 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 parse(s. dpi=120. fontsize=14) Returns the oﬀset of the baseline from the bottom of the image in pixels. used for all non-math text. depth) •array is an NxM uint8 alpha ubyte mask array of rasterized tex. texstr A valid mathtext string. dpi=120. If prop is provided. to_png(ﬁlename.0. Release 1. dpi=120. ﬁlename A writable ﬁlename or ﬁleobject texstr A valid mathtext string.

get_hinting_type() get_results(box) render_glyph(ox.MathTextWarning Bases: exceptions. y1. 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. h. info) Draw a glyph described by info to the reference point (ox. x2.MathtextBackend Bases: object The base class for the mathtext backend-speciﬁc code. y2). Release 1. which is later transferred to the Agg image by the Agg backend.Warning class matplotlib.MathtextBackendBbox(real_backend) Bases: matplotlib.mathtext.mathtext. Subclasses need to override the following: •render_glyph() •render_filled_rect() •get_results() And optionally.mathtext. 47. matplotlib.MathtextBackendAggRender Bases: matplotlib. Only required for the Agg backend. oy). oy. h.Matplotlib.mathtext. y1) to (x2. y1.mathtext.mathtext.MathtextBackend A backend whose only purpose is to get a precise bounding box. info) render_rect_filled(x1. exception matplotlib. render_glyph(ox.MathtextBackend Render glyphs and rectangles to an FTImage buﬀer. render_filled_rect(x1. x2.1. y2) set_canvas_size(w.0. set_canvas_size(w.mathtext 629 .MathtextBackendAgg() class matplotlib. d) Dimension the drawing canvas matplotlib. oy. The purpose of MathtextBackend subclasses is to interface between mathtext and a speciﬁc matplotlib graphics backend. get_results(box) Return a backend-speciﬁc tuple to return to the backend after all processing is done.mathtext.1 •depth is the oﬀset of the baseline from the bottom of the image in pixels. y2) Draw a ﬁlled black rectangle from (x1. d) class matplotlib.

Matplotlib. y2) class matplotlib.mathtext. oy.MathtextBackendPs Bases: matplotlib.1 get_hinting_type() get_results(box) render_glyph(ox.MathtextBackend Store information to write a mathtext rendering to the Cairo backend.MathtextBackend Store information to write a mathtext rendering to the PDF backend. Release 1. y1. x2. get_results(box) render_glyph(ox.mathtext. y1.mathtext. oy.MathtextBackend Store information to write a mathtext rendering to the Cairo backend.mathtext.0.mathtext. y2) matplotlib. y2) class matplotlib. oy.MathtextBackend Store information to write a mathtext rendering to the PostScript backend. y2) class matplotlib. y1. No additional matplotlib backend is required. get_results(box) render_glyph(ox.MathtextBackendBitmapRender Bases: matplotlib. class matplotlib.mathtext. get_results(box) render_glyph(ox. oy. y1. info) render_rect_filled(x1. matplotlib mathtext . info) render_rect_filled(x1. x2.MathtextBackendAggRender get_results(box) class matplotlib.mathtext.MathtextBackendCairo Bases: matplotlib.mathtext. x2. info) render_rect_filled(x1. x2.mathtext.mathtext. info) render_rect_filled(x1.MathtextBackendPdf Bases: matplotlib.MathtextBackendBitmap() A backend to generate standalone mathtext images.MathtextBackendPath Bases: matplotlib. oy. x2.mathtext. info) render_rect_filled(x1. y2) 630 Chapter 47. y1. get_results(box) render_glyph(ox.

after which things will no longer get smaller. The grammar is based directly on that in TeX. though it cuts a few corners. render(x.0.Glue class matplotlib. States are pushed and popped from a stack as necessary. y1. in that raw text may also appear outside of pairs of $.MathtextBackendSvg Bases: matplotlib. It actually parses full strings containing math expressions. toks) Parser. x2.Parser Bases: object This is the pyparsing-based parser for math expressions. toks) 47. font_class.mathtext. oy.NegFil Bases: matplotlib.MathtextBackend Store information to write a mathtext rendering to the SVG backend. y2) class matplotlib.NegFill Bases: matplotlib.Glue class matplotlib. and the “current” state is always at the top of the stack.mathtext 631 .mathtext. loc. get_results(box) render_glyph(ox.NegFilll Bases: matplotlib.mathtext.Matplotlib.mathtext. copy() font Parser.mathtext. There are only three levels of sizes.mathtext.1.mathtext.1 class matplotlib. y) shrink() Shrinks one level smaller. class State(font_output.Node Bases: object A node in the TeX box model get_kerning(next) grow() Grows one level larger. fontsize.auto_sized_delimiter(s. Release 1.mathtext. info) render_rect_filled(x1.accent(s.mathtext. font. There is no limit to how big something can get.mathtext. matplotlib. class matplotlib.Glue class matplotlib. loc. dpi) Bases: object Stores the state of the parser.

loc.finish(s. fontsize. toks) Parser.is_dropsub(nucleus) Parser. toks) Parser.frac(s.get_state() Get the current State of the parser.math(s. toks) Parser. at the given fontsize and dpi.group(s. loc. toks) Parser. loc. toks) Parser. toks) Parser. toks) Parser. loc.function(s.binom(s.customspace(s.space(s.end_group(s. toks) Parser. loc.1 Parser.subsuperscript(s. dpi) Parse expression s using the given fonts_object for output. toks) Parser.pop_state() Pop a State oﬀ of the stack. loc. Parser.non_math(s. toks) Parser. toks) 632 Chapter 47.start_group(s. toks) Parser. Release 1.push_state() Push a new State onto the stack which is just a copy of the current state.clear() Clear any state before parsing.0. loc. Returns the parse tree of Node instances. loc. Parser. loc. toks) Parser. matplotlib mathtext .stackrel(s. fonts_object.Matplotlib. Parser.is_overunder(nucleus) Parser. loc.char_over_chars(s.is_slanted(nucleus) Parser. loc. loc. loc. toks) Parser.symbol(s.parse(s. toks) Parser. loc. loc. toks) Parser. toks) Parser. Parser.font(s. loc. loc.genfrac(s. loc. toks) Parser.sqrt(s. Parser.

render(x.mathtext 633 . the height and depth are never running in a Vlist. get_sized_alternatives_for_symbol(fontname. depth. such as “Blackboard”.mathtext. and height ﬁelds just as in an Hlist. matplotlib.” The width is never running in an Hlist. y. hlist_out() and vlist_out().0. fontsize.1. font2.mathtext.StixFonts(*args. sym) class matplotlib. Release 1. this sends them to output.Matplotlib. fontclass2. h) class matplotlib. the actual value will be determined by running the rule up to the boundary of the innermost enclosing box.mathtext. get_kern(font1. state) Bases: matplotlib.Ship Bases: object Once the boxes have been set up.mathtext. fontsize2. height.1 class matplotlib.StandardPsFonts(default_font_prop) Bases: matplotlib. 47. The global variables used in TeX to store state as it processes have become member variables here.mathtext.Fonts Use the standard postscript fonts for rendering to backend_ps Unlike the other font classes.StixSansFonts(*args.mathtext.mathtext.SsGlue Bases: matplotlib. sym2. this class: •supports “virtual fonts” which are complete alpha numeric character sets with diﬀerent font styles at special Unicode code points.mathtext. In addition to what UnicodeFonts provides.mathtext. if any of these dimensions is inf.StixFonts A font handling class for the STIX fonts (that uses sans-serif characters by default). static clamp(value) hlist_out(box) vlist_out(box) class matplotlib.mathtext. BakomaFont and UnicodeFont. Since boxes can be inside of boxes inside of boxes. which traverse the Hlist nodes and Vlist nodes inside of horizontal and vertical boxes. dpi) class matplotlib.Glue class matplotlib. depth.UnicodeFonts A font handling class for the STIX fonts. •handles sized alternative characters for the STIXSizeX fonts.mathtext. fontsize. this one requires the Ps backend. **kwargs) Bases: matplotlib. w. fontsize1. fontclass1. **kwargs) Bases: matplotlib.Rule(width.Box A Rule node stands for a solid black rectangle. it has width. This is called a “running dimension. sym1. the main work of Ship is done by two mutually recursive routines. dpi) get_underline_thickness(font. dpi) get_xheight(font. However.

sym) class matplotlib.Vlist(elements. m=’additional’) Bases: matplotlib. fontclass1.SubSuperCluster Bases: matplotlib. sym2. h=0. matplotlib mathtext . class matplotlib.mathtext.and super-script. dpi) TruetypeFonts.TruetypeFonts(default_font_prop.0.TruetypeFonts An abstract base class for handling Unicode fonts. l=inf ) The main duty of vpack() is to compute the dimensions of the resulting boxes. and to adjust the glue if one of those dimensions is pre-speciﬁed. fontsize.get_xheight(font. it can be reconﬁgured on the ﬂy.mathtext. •l: a maximum height 634 Chapter 47. **kwargs) Bases: matplotlib.mathtext.0.get_underline_thickness(font.mathtext. namely the nucleus. sub.Hlist SubSuperCluster is a sort of hack to get around that fact that this code do a two-pass parse like TeX.Matplotlib.Vbox(height. •h: speciﬁes a height •m: is either ‘exactly’ or ‘additional’. dpi) class matplotlib.mathtext. This lets us store enough information in the hlist itself. mathtext_backend) Bases: matplotlib.mathtext.0. class matplotlib.mathtext. fontclass2.Fonts A generic base class for all font setups that use Truetype fonts (through FT2Font).Box A box with only height (zero width). get_sized_alternatives_for_symbol(fontname.VCentered(elements) Bases: matplotlib. font2.get_kern(font1.destroy() TruetypeFonts.1 class matplotlib. such that if another script follows that needs to be attached.mathtext.mathtext. While some reasonably complete Unicode fonts (such as DejaVu) may work in some situations.mathtext. m=’additional’.UnicodeFonts(*args. class matplotlib. Release 1.mathtext.List A vertical list of boxes. class CachedFont(font) TruetypeFonts.Hlist A convenience class to create a Vlist whose contents are centered within its enclosing box. This class will “fallback” on the Bakoma fonts when a required symbol can not be found in the font. fontsize1. fontsize. fontsize2. vpack(h=0. the only Unicode font I’m aware of with a complete set of math symbols is STIX. depth) Bases: matplotlib. sym1. dpi) TruetypeFonts.mathtext.

mathtext.unichr_safe(index) Return the Unicode character corresponding to the index. ’exactly’) produces a box whose height is exactly h. matplotlib.mathtext. while vpack(h.e.e. 47.Matplotlib.mathtext. Release 1. or a Type1 symbol name (i. a TeX command (i. matplotlib.mathtext.Vrule(state) Bases: matplotlib. class matplotlib.mathtext 635 .1. ’additional’) yields a box whose height is the natural height plus h. r’pi’).get_unicode_index(symbol) get_unicode_index(symbol) -> integer Return the integer index (from the Unicode table) of symbol. 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.1 Thus. ‘phi’). matplotlib. symbol can be a single unicode character. vpack(h.Rule Convenience class to create a vertical rule.0.

1 636 Chapter 47. matplotlib mathtext . Release 1.Matplotlib.0.

1 matplotlib.2 Miscellaneous functions Functions that don’t exist in MATLAB.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 ﬁt line from an array find() Return the indices where some condition is true. and we compute it for a lot of pairs. prctile() ﬁnd 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. griddata() interpolate irregularly distributed data to a regular grid. but we compute coherence a lot in my lab. This is not a MATLAB function.CHAPTER FORTYEIGHT MATPLOTLIB MLAB 48. This function is optimized to do this eﬃciently by caching the direct FFTs.nonzero is similar but more general. 48. numpy.1. but are useful anyway: cohere_pairs() Coherence over all pairs. 637 .1.mlab Numerical python functions written for compatability with MATLAB commands with the same names.

checkrows=0) formatd = dict( weight = FormatFloat(2).show_all() gtk. Example usage: r = csv2rec(’somefile.800) win. cost = FormatThousands(2).1.csv’. formatd=formatd) scroll = rec2gtk(r. formatd=formatd) rec2csv(r.xls’.Window() win. matplotlib mlab . there are a bunch of Format objects you can pass into the functions that will do things like color negative values red.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 ﬁle csv2rec() import record array from CSV ﬁle with type inspection rec_append_fields() adds ﬁeld(s)/array(s) to record array rec_drop_fields() drop ﬁelds from record array rec_join() join two record arrays on sequence of ﬁelds 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 ﬁlter rec array ﬁelds into new ﬁelds For the rec viewer functions(e rec2csv). 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.0. Release 1. formatd=formatd) win = gtk. etc.1 rk4() A 4th order Runge-Kutta ODE integrator in case you ever ﬁnd yourself stranded without scipy (and the far superior scipy. ’test.csv’. set percent formatting and scaling.add(scroll) win.main() 638 Chapter 48.set_size_request(600.Matplotlib. ’test. ) rec2excel(r.

1.0. class matplotlib.mlab. the dataLim will be updated as new data come in.use numpy.dataLim).mlab. y data in a rotating buﬀer using numpy arrays under the hood. asarrays() Return x and y as arrays.loadtxt save() save ASCII ﬁle . last() Get the last x.mlab.1 48. func signature is func(fifo).FormatObj fromstr(s) toval(x) class matplotlib. None if no data set. N) Call func every time N events are passed.4 Deprecated functions The following are deprecated. add(x.1. register(func. TODO: add a grow method that will extend nmax Note: mlab seems like the wrong place for this class. 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 buﬀer and plot it to screen less freqeuently than the incoming.FormatDate fromstr(x) 48.use numpy. y or None. y) Add scalar x and y to the queue. 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.FormatBool Bases: matplotlib.mlab 639 .savetxt class matplotlib. matplotlib.mlab.mlab. their length will be the len of data added or nmax. Release 1.Axes.FormatObj fromstr(x) toval(x) class matplotlib.Matplotlib. If you set the dataLim attr to BBox (eg matplotlib.FormatDate(fmt) Bases: matplotlib.FormatDatetime(fmt=’%Y-%m-%d %H:%M:%S’) Bases: matplotlib. please import directly from numpy (with care–function signatures may diﬀer): load() load ASCII ﬁle .mlab. Buﬀer up to nmax points.FIFOBuffer(nmax) A FIFO queue to hold incoming x. update_datalim_to_current() Update the datalim in the current data in the ﬁfo.

Release 1.mlab.FormatFormatStr fromstr(s) toval(x) class matplotlib. numcols: the dimensions of a mu : a numdims array of means of a 640 Chapter 48.mlab.FormatMillions(precision=4) Bases: matplotlib.FormatFloat class matplotlib.FormatFloat(precision=4.1 class matplotlib.mlab.mlab. scale=1.FormatPercent(precision=4) Bases: matplotlib.mlab.FormatObj fromstr(s) tostr(x) toval(x) class matplotlib.mlab.PCA(a) compute the SVD of a and store data for PCA.FormatFormatStr(fmt) Bases: matplotlib.FormatFloat class matplotlib.mlab.mlab.0.FormatObj tostr(x) class matplotlib.0) Bases: matplotlib.Matplotlib.mlab.mlab.mlab. 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.mlab.FormatFloat class matplotlib.mlab.FormatObj tostr(x) class matplotlib.mlab.FormatInt Bases: matplotlib.FormatString Bases: matplotlib. matplotlib mlab .FormatThousands(precision=4) Bases: matplotlib.mlab.FormatObj fromstr(s) tostr(x) toval(x) class matplotlib.mlab.

noverlap=0. max_length=1025) Return the binary representation of the input number as a string. *args) amap(function.mlab. See bivariate normal at mathworld.mlab.. numpy..base_repr(number.]) -> array. sides=’default’..cohere(x. Increase the value of max_length for very large numbers.0.array(map(. mux=0. padding=0) Return the representation of a number in any given base. muy=0. .1. but it returns an array. sequence. window=<function window_hanning at 0x3a178c0>.mlab 641 . This is more eﬃcient than using base_repr() with base 2. This is just a convenient shorthand for matplotlib. matplotlib. dim=0) Return the matrix M with each row having zero mean and unit std. Works like map(). dropping any axes where fraction of variance<minfrac matplotlib.0.mlab. y Array or sequence containing the data Keyword arguments: |P xy |2 P xx Pyy (48. If dim = 1 operate on columns instead of rows. base=2.mlab.binary_repr(number.amap(fn. matplotlib. detrend=<function detrend_none at 0x3a1c668>. minfrac=0. sigmax=1. 2**1023 is the largest integer power of 2 which can be converted to a Python ﬂoat. sigmay=1. 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. sequence[. Y.1) 48.mlab.Matplotlib. matplotlib.0) Bivariate Gaussian distribution for equal shape X. Coherence is the normalized cross spectral density: C xy = x.0.. pad_to=None.) matplotlib.mlab. scale_by_freq=None) The coherence between x and y. Y. Note that on 32-bit machines.0) project x onto the principle axes. NFFT=256.0. Fs=2. Release 1. y.center_matrix(M. sigmaxy=0.0. (dim is opposite to the numpy axis kwarg.bivariate_normal(X.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.)).

this can give more points in the plot. which speciﬁes the number of data points used. This allows for integration over the returned frequency values. numpy. NFFT=256. The default is None. matplotlib. freqs. and detrend_linear(). where f are the frequencies of the coherence vector. which returns one-sided for real data and both for complex data. The return value is the tuple (Cxy. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes 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. P xx and Pyy .blackman(). Unlike in MATLAB. numpy. where the detrend parameter is a vector. Fs=2. numpy.mlab.signal. This can be diﬀerent from NFFT. while ‘twosided’ forces two-sided. ij.bartlett(). f ). which gives density in units of Hz^-1. It is used to calculate the Fourier frequencies. The default value is 2.0. in matplotlib is it a function. window=<function window_hanning at 0x3a178c0>.1 NFFT: integer The number of data points used in each block for the FFT. scale_by_freq: boolean Speciﬁes whether the resulting density values should be scaled by the scaling frequency. detrend_mean(). returnPxx=False) Call signature: 642 Chapter 48. For cohere. etc. The default value is 256. allowing for more detail. The default is True for MATLAB compatibility. but you can use a custom function as well. The default is window_hanning(). See Also: psd() and csd() For information about the methods used to compute P xy . Release 1. since the factors cancel out. scipy. Fs: scalar The sampling frequency (samples per time unit). Default gives the default behavior.hamming(). While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). If a function is passed as the argument. designed to remove the mean or linear trend. The default value is 0 (no overlap). detrend: callable The function applied to each segment before ﬀt-ing. scipy. window_none().signal(). in cycles per time unit. a power 2 is most eﬃcient. noverlap=0. This corresponds to the n parameter in the call to ﬀt(). The pylab module deﬁnes detrend_none(). preferSpeedOverMemory=True.Matplotlib. ‘onesided’ forces the return of a one-sided PSD. noverlap: integer The number of points of overlap between blocks.cohere_pairs(X.get_window(). matplotlib mlab . scaling the individual densities by the sampling frequency has no eﬀect. To create window vectors see window_hanning(). it must take a data segment as an argument and return the windowed version of the segment. Must be even. window: callable or ndarray A function or a vector of length NFFT. progressCallback=<function donothing_callback at 0x3a21500>. detrend=<function detrend_none at 0x3a1c668>.

freqs = cohere_pairs( X. X is a numSamples * numCols array ij is a list of tuples. ij.. But both solutions were more than 10x faster than naively crunching all possible pairs through cohere()..mlab 643 . cohere(X[:. Phase. See test/cohere_pairs_test.i].7GHZ Athlon with 512MB RAM compared with preferSpeedOverMemory = False. Keys are (i. I. because of the caching. to make a coherence Bode plot: subplot(211) plot( freqs. and you want to compute all nonredundant pairs. j).j) ) preferSpeedOverMemory is an optional bool. and will use subtantially less memory than if preferSpeedOverMemory is True. in X. This is useful if memory becomes critical. Returns: (Cxy.) Compute the coherence and phase for all pairs ij. Cxy[(i. j) key. matplotlib. this function is O(N) for most of the heavy lifting.. j) tuples -> coherence vector for that pair. If N is the number of pairs. Even when preferSpeedOverMemory is False. if X has 64 columns.19)]) For a large number of pairs. Phase[(12. limits the caching by only making one. Phase. X[:. 48. complex cache arrays. Defaults to true. •freqs: vector of frequencies. Cxy[(12. deﬁne ij as: ij = [] for i in range(64): for j in range(i+1. equal in length to either the coherence or phase vectors for any (i.. However. If False. cohere_pairs() will still give signiﬁcant performace gains over calling cohere() for each pair. preferSpeedOverMemory = True delivered a 33% performance boost on a 1. freqs) where: •Cxy: dictionary of (i. whereas calling cohere for each pair is O(N 2 ). In my tests with a 43000.19)]) subplot(212) plot( freqs.j) = •Phase: dictionary of phases of the cross spectral density at each frequency for each pair. it is also more memory intensive.64 array over all nonredundant pairs. because it caches most of the intensive computations.64): ij. rather than two.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. cohere_pairs() can be much more eﬃcient than just calling cohere() for each pair.e. Each tuple is a pair of indexes into the columns of X for which you want to compute coherence.append( (i. Release 1.j]). making 2 additional complex arrays with approximately the same number of elements as X.0. For example. Eg. .1 Cxy.1.Matplotlib. Number of dictionary keys is len(ij).

-1.5) ax.1 See Also: psd() For information about the methods used to compute P xy .contiguous_regions(mask) return a list of (ind0. 1) ind = cross_from_above(s. noverlap=0. Release 1. detrend=<function detrend_none at 0x3a1c668>. 2.mlab.plot(t.add_subplot(111) ax.vlines(t[ind].arange(0. The product of the 644 Chapter 48. Each block is detrended by the function detrend and windowed by the function window.0. -0.mlab. eg the i’s where: x[i-1]>threshold and x[i]<=threshold See Also: cross_from_below() and contiguous_regions() matplotlib.5) ax. pad_to=None.mlab.show() See Also: cross_from_above() and contiguous_regions() matplotlib.1) s = np. -1.cross_from_above(x. threshold) return the indices into x where x crosses some threshold from below. s.5) ax. sides=’default’. matplotlib. P xx and Pyy . noverlap gives the length of the overlap between blocks. 0. eg the i’s where: x[i-1]<threshold and x[i]>=threshold Example code: import matplotlib.axhline(-0.figure() ax = fig. ’-o’) ax.0.cross_from_below(x.mlab.csd(x.0. ind1) such that mask[ind0:ind1].pyplot as plt t = np. Fs=2.Matplotlib. matplotlib mlab .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. NFFT=256. 1) plt. y. scale_by_freq=None) The cross power spectral density by Welch’s average periodogram method. 0. The vectors x and y are divided into NFFT length blocks. window=<function window_hanning at 0x3a178c0>. threshold) return the indices into x where x crosses some threshold from below.vlines(t[ind].sin(2*np.5) ind = cross_from_below(s.pi*t) fig = plt.axhline(0.

0.signal(). Fs: scalar The sampling frequency (samples per time unit). This allows for integration over the returned frequency values. Refs: Bendat & Piersol – Random Data: Analysis and Measurement Procedures. window: callable or ndarray A function or a vector of length NFFT. x. it must take a data segment as an argument and return the windowed version of the segment. scale_by_freq: boolean Speciﬁes whether the resulting density values should be scaled by the scaling frequency. etc. allowing for more detail. ‘onesided’ forces the return of a one-sided PSD. which returns one-sided for real data and both for complex data. noverlap: integer The number of points of overlap between blocks. The default value is 256. freqs). It is used to calculate the Fourier frequencies. this can give more points in the plot. Must be even. y Array or sequence containing the data Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. The default is window_hanning(). Returns the tuple (Pxy.blackman(). in matplotlib is it a function. Unlike in MATLAB. To create window vectors see window_hanning(). and detrend_linear(). The default value is 0 (no overlap). in cycles per time unit. where the detrend parameter is a vector. scipy. while ‘twosided’ forces two-sided.get_window().1 direct FFTs of x and y are averaged over each segment to compute Pxy. pad_to: integer The number of points to which the data segment is padded when performing the FFT. matplotlib. designed to remove the mean or linear trend. This can be diﬀerent from NFFT. If len(x) < NFFT or len(y) < NFFT.1. which gives density in units of Hz^-1. detrend_mean(). The default is True for MATLAB compatibility. This corresponds to the n parameter in the call to ﬀt(). Release 1. The default is None. which speciﬁes the number of data points used. John Wiley & Sons (1986) 48. with a scaling to correct for power loss due to windowing. but you can use a custom function as well. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes which sides of the PSD to return.Matplotlib. freqs.signal. a power 2 is most eﬃcient. The pylab module deﬁnes detrend_none(). The default value is 2. numpy. scipy.mlab 645 .bartlett().hamming(). numpy. numpy. window_none(). they will be zero padded to NFFT. Default gives the default behavior. detrend: callable The function applied to each segment before ﬀt-ing. If a function is passed as the argument. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks).

mlab. If names is None.g. matplotlib. delimiter=’.fromrecords record array if any of the data are missing If no rows are found. ‘0000-00-00’ or ‘unused’ •missing: a string whose value signals a missing ﬁeld regardless of the column it appears in •use_mrecords: if True. In this case.mlab. matplotlib mlab . •fname: can be a ﬁlename or a ﬁle handle. e. s1 are xy sequences 646 Chapter 48.csvformat_factory(format) matplotlib. checkrows=0. use_mrecords=False) Load data from comma/space/tab delimited ﬁle in fname into a numpy record array and return the record array. ‘linear’ detrending matplotlib. is a list of header names.1 matplotlib. axis=0) Return x minus its mean along the speciﬁed axis matplotlib. it is a sequence of names to use for the column names. ‘. and illegal attribute name characters removed.detrend_none(x) Return x: no detrending matplotlib. comments=’#’. Release 1.mlab. missing=’‘.dist_point_to_segment(p.Matplotlib. converterd=None.csv2rec(fname.detrend_linear(y) Return y minus best ﬁt line. s1) Get the distance of a point to a segment. y) Return the distance between two points.mlab. •names: if not None.mlab. None is returned – see examples/loadrec. s0. names=None. skiprows=0. it is assumed there is no header row. spaces will be converted to underscores.dist(x. key=None) matplotlib. return an mrecords.mlab. In this case. if the ﬁlename ends in ‘.py matplotlib. If names is not None.0. no header will be read from the ﬁle •missingd is a dictionary mapping munged column names to ﬁeld values which signify that the ﬁeld does not contain actual data and should be masked. 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. When set to zero all rows are validated. The headers will be lower cased. a header row is required to automatically assign the recarray names. •converterd: if not None.demean(x.detrend(x. p. s0.gz’ •comments: the character used to indicate the start of a comment in the ﬁle •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. missingd=None. Support for gzipped ﬁles is automatic.mlab.

detrend=<function detrend_none at 0x3a1c668>. **kw) frange([start.find(condition) Return the indices where ravel(condition) is true matplotlib..arange‘.htm#Distance%20to%20Ray%20o matplotlib.mlab.arange().frange(xini. frange() can also be called with the keyword npts. This behavior is diﬀerent from that of range() and numpy. matplotlib. Similar to numpy.arange().xfin] where xﬁn <= x1.0 + log(2*pi*sigma**2. bins) Return the entropy of the data in y. x0+1. This sets the number of points the list should contain (and overrides the value step might have been given).mlab. keywords]) -> array of ﬂoats Return a numpy ndarray containing a progression of ﬂoats. This is deliberate.. but defaults to a closed interval. numpy.fftsurr(x.mlab. Note that numpy provides proper ﬂoating point exception handling with access to the underlying hardware.donothing_callback(*args) matplotlib.mlab. x0+2.mlab.d) returns [x0. matplotlib.1 This algorithm from http://softsurfer.. delta=None.x0+2d.1.5 * ( 1.exp_safe(x) Compute exponentials which safely underﬂow to zero. Distance is the standard Euclidean distance. Compare S with analytic calculation for a Gaussian: x = mu + sigma * randn(200000) Sanalytic = 0.mlab.arange() doesn’t oﬀer this option.0. but convenient to use..entropy(y. The usual behavior of range() can be obtained by setting the keyword closed = 0. All arguments can be ﬂoating point numbers. since frange() will probably be more useful for generating lists of points for function evaluation.2) where pi is the probability of observing y in the ith bin of bins.0) ) matplotlib. frange(x0. and endpoints are often desired in this use. in this case. start defaults to 0. frange() basically becomes :func:numpy.. . Where X is an M x N array or matrix. it speciﬁes the increment (or decrement).x0+d.com/Archive/algorithm_0102/algorithm_0102.mlab 647 . frange(x0.histogram()... Slow. x1]. Release 1. matplotlib. see numpy.mlab.x1. matplotlib. When step is given. The distances between successive rows is computed. step. pi log2 (pi ) (48. dow=<function window_none at 0x3a17cf8>) Compute an FFT phase randomized surrogate of x. and the endpoint is included.distances_along_curve(X) Computes the distance between a set of successive points in N dimensions. win- 48. xﬁn=None.] stop[. x1) returns [x0. bins can be a number of bins or a range of bins.Matplotlib.

mlab. Linear interpolation is only valid if matplotlib. The triangulation algorithm in this package is known to fail on some nearly pathological cases.delaunay package is used mpl_tookits..mlab. this object is simply a multi-index Kronecker delta: 648 Chapter 48. xi. In this case. z).delaunay package.net/project/showﬁles.natgrid only provides natural neighbor interpolation.6. x.. frac=0..]) >>> frange(1.5 ]) matplotlib.get_sparse_matrix(M. 2. If the interp keyword is set to ‘linear‘. Return value is (x. 3. y. but must be monotonically increasing. For ranks higher than 2. y) to the data in the (usually) nonuniformly spaced vectors (x..3.7.. z.delaunay package. 5. which contains code that is not redistributable under a BSD-compatible license. this function will use the mpl_toolkits. then linear interpolation is used instead of natural neighbor.10000000000000001) Return a M x N sparse matrix with frac elements randomly ﬁlled.yi) ﬁts a surface of the form z = f*(*x.]) >>> frange(3.Matplotlib. matplotlib. otherwise it will use the built-in matplotlib. When installed. A masked array is returned if any grid points are outside convex hull deﬁned by input data (no extrapolation is done). z) where x and y are the indices into Z and z are the values of Z at those indices. this algorithm is provided by the matplotlib. 1.. a separate toolkit (mpl_tookits. The natgrid matplotlib toolkit can be downloaded from http://sourceforge.2) array([1.natgrid algorithm. N.get_formatd(r.. 2.5.griddata(x. depending on floating point vagueries >>> frange(1.php?group_id=80706& matplotlib. typecode=None) Returns the identity matrix of shape (n.5. 3. 3. 1. uses natural neighbor interpolation based on Delaunay triangulation. Cond) Z and Cond are M x N matrices. matplotlib mlab . n) (rank r). can be either 1D or 2D. This toolkit is based on the NCAR natgrid library. the output grid is assumed to be regular with a constant grid spacing in both the x and y directions. y.mlab. you must use natural neighbor interpolation. rank=2.npts=5) array([ 1. . For regular grids with nonconstant grid spacing. Release 1. n.z.. griddata() interpolates this surface at the points speciﬁed by (xi. 6.0. formatd=None) build a formatd guaranteed to have a key for every dtype name matplotlib. . By default. xi and yi must describe a regular grid. 5]) or 1. 2.get_xyz_where(Z.natgrid) has been created that provides a more robust algorithm fof triangulation and interpolation.xi.125.1 Examples: >>> frange(3) array([ 0. yi.mlab.identity(n.y. y. Z are data and Cond is a boolean matrix where some condition is satisﬁed.mlab. written by Robert Kern. yi) to produce zi. and z are 1D arrays. y. matplotlib. interp=’nn’) zi = griddata(x.closed=0) array([ 0. For this reason.375. If interp keyword is set to ‘nn‘ (default).6.75 . dtype=’l’.

fprime) x is a very long trajectory from a map. ﬂattened out. matplotlib.0. matplotlib. Implemented as a separate function (not a call to norm() for speed). verts is a sequence of x... xi. extrap=False) This function provides simple (but somewhat less so than cbook. Release 1. gamma. use scipy. ﬂattened out. This function will be removed from matplotlib. but all must have length 1.mlab. use X.l2norm(a) Return the l2 norm of a.mlab.1. it is much faster. Implemented as a separate function (not a call to norm() for speed).. interpret accordingly. verts) points is a sequence of x.less_simple_linear_interpolation(x. it can have multiple axes. while this does true linear interpolation at an arbitrary set of points.levypdf(x. y.mlab. returns True if the supplied numpy array or matrix X looks like a vector. otherwise.e.. and fprime returns the derivative of x.inside_poly(points. y vertices of a polygon. alpha matplotlib.identity(n) – but surprisingly. This is very ineﬃcient linear interpolation meant to be used only for a small number of points in relatively non-intensive use cases. in which case this function tests if that curve is closed.mlab.Matplotlib. this function behaves in the default case (when only n is given) like numpy. These are presumably coordinates on a polygonal curve. Return value is a sequence of indices into points for the points that are inside the polygon.mlab.. Optionally a dtype (or typecode) may be given (it defaults to ‘l’). matplotlib..ispower2(n) Returns the log base 2 of n if n is a power of 2.mlab.1 / id[i0.=iR. For real linear interpolation. matplotlib.is_closed_polygon(X) Tests whether ﬁrst and last object in a sequence are the same. alpha) Returm the levy pdf evaluated at x for params gamma.mlab. meaning it has a one non-singleton axis (i. zero otherwise.iR] = -| \ 1 0 if i0=i1=. Since rank defaults to 2. 48. If you just want to see if the array has 1 axis.liaupunov(x.ndim == 1.mlab. matplotlib.isvector(X) Like the MATLAB function with the same name.mlab. matplotlib. matplotlib. except for one of them). simple_linear_interpolation() will give a list of point between a start and an end. y points.l1norm(a) Return the l1 norm of a. Note the potential ambiguity if n == 1: 2**0 == 1.simple_linear_interpolation()) linear interpolation. matplotlib.mlab 649 . matplotlib.i1..

Deprecated: use numpy.. if True. delimiter=None. Example usage: X = load(’test. if column 0 is a date string: converters = {0:datestr2num} •skiprows is the number of rows from the top to skip. It also seems that this function’s name is badly misspelled. you can do the same with “unpack”.1] # data in two columns Alternatively.dat’) # a matrix of data # a single column of data •comments: the character used to indicate the start of a comment in the ﬁle •delimiter is a string-like character used to seperate values in the ﬁle.ﬂoat64’>) Load ASCII data from fname into an array and return the array.5] to extract just the 2nd. unpack=False. is a dictionary mapping column number to a function that will convert that column to a ﬂoat (or the optional dtype if speciﬁed).dat’) t = X[:.io. The data must be regular. Eg. for that. is a sequence of integer column indexes to extract where 0 is the ﬁrst column. 5th and 6th columns •unpack. converters=None. caveat emptor.gz’. use scipy. dtype=<type ‘numpy. •usecols. if not None. see below: X = load(’test. Release 1.mlab. if the ﬁlename ends in ‘. If delimiter is unspeciﬁed or None.load(fname. matﬁle data is not supported.1 Returns : .4. matplotlib.Matplotlib. if not None.5 Strogatz (1994) “Nonlinear Dynamics and Chaos”. any whitespace string is a separator. matplotlib mlab . will transpose the matrix allowing you to unpack into named arguments on the left hand side: 650 Chapter 48.0. Note: What the function here calculates may not be what you really want.loadtxt. same number of values in every row fname can be a ﬁlename or a ﬁle handle.0] y = X[:. usecols=None. •converters.mio module.dat’) x = load(’test. Support for gzipped ﬁles is automatic. math: \lambda = \frac{1}{n}\sum \ln|f^’(x_i)| See Also: Lyapunov Exponent Sec 10. Wikipedia article on Lyapunov Exponent. skiprows=0. eg usecols=[1. comments=’#’.

py in the source tree Exercises these options. x. n) Compute the len(n) moving average of x. yv = poly_below(0. This is NOT a true matrix norm.dat’.longest_contiguous_ones(x) Return the indices of the longest stretch of contiguous ones in x. y) ax.mlab 651 . matplotlib. p=2) norm(a. matplotlib.y = load(’test. Where X is an M x N array or matrix. return the vertices of a polygon that has a horizontal base at xmin and an upper bound at the ys. 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.dat’. xs. *args) Return the normal pdf evaluated at x. Release 1.1. args provides mu. ln2=0. matplotlib.mlab..y.7]. assuming x is a vector of zeros and ones. yv) many of 48.69314718055994529) Return the log(x) in base 2. xmax.mlab. matplotlib. matplotlib.p=2) -> l-p norm of a.poly_below(xmin. Returns an array of length M consisting of the distance along the curve at each point (i. N) matplotlib.float_ See Also: See examples/pylab_examples/load_converter.Axes.axes.1 t.mlab. unpack=True) # for two column data x.e.5.fill(xv.mlab.z = load(’somefile. Intended for use with matplotlib. matplotlib.mlab. default: numpy.norm_flat(a.mlab.longest_ones(x) alias for longest_contiguous_ones matplotlib. ys) Given a sequence of xs and ys.mlab.fill().normpdf(x.Matplotlib. If there are two equally long stretches. usecols=[3. p can be a number or the string ‘Inﬁnity’ to get the L-inﬁnity norm. xmin is a scalar. eg: xv. pick the ﬁrst.movavg(x.mlab. considered as a ﬂat array.ﬂat Return the l-p norm of a.mlab. unpack=True) •dtype: the array will have this dtype.0.path_length(X) Computes the distance travelled along a polygonal curve in N dimensions. matplotlib.log2(x. since arrays of arbitrary rank are always ﬂattened. the rows of X). sigma matplotlib.logspace(xmin.

It is used to calculate the Fourier frequencies. The vector x is divided into NFFT length blocks. noverlap gives the length of the overlap between blocks.0)) Return the percentiles of x. Must be even.fill(). The default value is 2. 652 Chapter 48. NFFT=256. noverlap=0. ylower. y arrays for use with matplotlib. freqs. Eg if p = (25. fracVar) where: •Pcomponents : a (numVars. 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.0. p can either be a sequence of percentile values or a scalar. window=<function window_hanning at 0x3a178c0>. matplotlib. pad_to=None.mlab. ylower and yupper. sides=’default’. 1 indicates the value is >= the 25th and < 50th percentile. The default value is 256. The absolute(ﬀt(block))**2 of each segment are averaged to compute Pxx. the return value will be a len(x) array with values in [0. Each block is detrended by the function detrend and windowed by the function window.prctile(x. 75). P is a (numVars. Fs: scalar The sampling frequency (samples per time unit). it will be zero padded to NFFT. Release 1. numObs) array. x Array or sequence containing the data Keyword arguments: NFFT: integer The number of data points used in each block for the FFT.0. return the rank 0.0.axes. return the polygon that ﬁlls the regions between them. frac=0) WARNING: this function is deprecated – please see class PCA instead Compute the principal components of P.Axes. the largest value of x less than or equal to the p percentage point in the sequence is returned. If p is a sequence..prepca(P.mlab. 25. ylower or yupper can be scalar or iterable.psd(x. . 75.len(p). matplotlib. scale_by_freq=None) The power spectral density by Welch’s average periodogram method. p is either an array of percentiles in [0. with a scaling to correct for power loss due to windowing. If len(x) < NFFT.2. 50. its successor seems to be called “processpcs”. If they are iterable. matplotlib mlab . numObs) array •Trans [the weights matrix.. and 3 indicates the value is above the 75th percentile cutoﬀ. a power 2 is most eﬃcient.3] where 0 indicates the value is less than the 25th percentile.1 matplotlib. Return value is x.1. the ith element of the return sequence is the p*(i)-th percentile of *x..0. yupper) Given a sequence of x. Trans.. Return value is a tuple of the form (Pcomponents.100] or a scalar which indicates how many quantiles of data you want ranked. If p is a scalar. Fs=2. frac is the minimum fraction of variance that a component must contain to be included. matplotlib.poly_between(x. p=(0.Matplotlib. they must be equal in length to x. matplotlib.mlab. p) Return the rank for each element in x. in cycles per time unit.0.prctile_rank(x.mlab. ie. 100. 50. detrend=<function detrend_none at 0x3a1c668>.mlab.

scipy. Unlike in MATLAB. it must take a data segment as an argument and return the windowed version of the segment.get_window().1 detrend: callable The function applied to each segment before ﬀt-ing.blackman(). while ‘twosided’ forces two-sided. which gives density in units of Hz^-1. q1x. missingd=None. The default is None. q0y. q2y) Converts a quadratic Bezier curve to a cubic approximation. missing=’‘. this can give more points in the plot.rec2csv(r. The default is window_hanning(). The default is True for MATLAB compatibility. q2x. The pylab module deﬁnes detrend_none(). numpy.1. and the output is a tuple of x and y coordinates of the four control points of the cubic curve. window_none().mlab. Release 1.mlab 653 . q1y. freqs). numpy. which speciﬁes the number of data points used. This can be diﬀerent from NFFT.Matplotlib. The record array dtype names will be used for column headers. numpy. in matplotlib is it a function. This corresponds to the n parameter in the call to ﬀt(). formatd=None. detrend_mean(). matplotlib. which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes which sides of the PSD to return. scale_by_freq: boolean Speciﬁes whether the resulting density values should be scaled by the scaling frequency. John Wiley & Sons (1986) matplotlib. fname: can be a ﬁlename or a ﬁle handle.bartlett().quad2cubic(q0x. If a function is passed as the argument.gz’ 48. The inputs are the x and y coordinates of the three control points of a quadratic curve. and detrend_linear(). scipy. etc. matplotlib.signal().signal. Default gives the default behavior. withheader=True) Save the data from numpy recarray r into a comma-/space-/tab-delimited ﬁle.0. noverlap: integer The number of points of overlap between blocks.hamming(). designed to remove the mean or linear trend.mlab. which returns one-sided for real data and both for complex data. pad_to: integer The number of points to which the data segment is padded when performing the FFT. but you can use a custom function as well. delimiter=’. ‘onesided’ forces the return of a one-sided PSD. Support for gzipped ﬁles is automatic. The default value is 0 (no overlap). This allows for integration over the returned frequency values. Returns the tuple (Pxx. Refs: Bendat & Piersol – Random Data: Analysis and Measurement Procedures. where the detrend parameter is a vector. To create window vectors see window_hanning(). if the ﬁlename ends in ‘. window: callable or ndarray A function or a vector of length NFFT. ‘. allowing for more detail. While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks). fname.

mlab. ﬁelds : if not None.rec_groupby(r. groupby. do not write the attribute names in the ﬁrst row for formatd type FormatFloat. r: numpy recarray header: list of column headers padding: space between each column precision: number of decimal places to use for ﬂoats. padding=3. matplotlib. ﬁelds can be a list of strings like [’ﬁeld1’. ’avgsale’) ) Return record array has dtype names for each attribute name in the the groupby argument.rec_drop_fields(rec. arrs and dtypes do not have to be lists. ’numsales’).54 6. matplotlib.3] Output: ID ABC XYZ Price 12. Precision for non-ﬂoats is simply ignored. outname) tuples which will call x = func(attr) and assign x to the record array output with attribute outname. eg (‘date’. np.234 -0.mlab. stats) r is a numpy record array groupby is a sequence of record array attribute names that together form the grouping key. arrs. If appending a single ﬁeld.32 Return 0.Matplotlib. precision=3. matplotlib. a list of ﬁeld names to print. For example: stats = ( (’sales’. and for each outname name in the stats argument. They can just be the values themselves.mean. func. which can be used to ﬁll in masked values into your CSV ﬁle. (’sales’.0. names) Return a new numpy record array with ﬁelds in names dropped. ‘productcode’) stats is a sequence of (attr. Set to an integer to apply to all ﬂoats.1 withheader: if withheader is False.rec_append_fields(rec.rec2txt(r. 654 Chapter 48. names.2. we override the precision to store full precision ﬂoats in the CSV ﬁle See Also: csv2rec() For information about missing and missingd. ﬁelds=None) Returns a textual representation of a record array. header=None. matplotlib mlab .mlab.mlab.ﬁeld2’ Example: precision=[0. then names. ‘ﬁeld2’] or a single comma separated string like ‘ﬁeld1. with the associated group values.076 matplotlib. Release 1. len. Set to a list of integers to apply precision individually. dtypes=None) Return a new record array with ﬁeld names populated with data from arrays in arrs. with the associated stat summary output.

missing=0. name1. func.. "close".. or if postﬁxes [PF0. summaryfuncs) r is a numpy record array summaryfuncs is a list of (attr.) matplotlib. r2. y0. postﬁxes=None) Join a sequence of record arrays on single column key. Example: r = recs_join("date". r1 (also r2) must not have any duplicate keys. Otherwise use scipy.. . defaults=None. recs=[r0.recs_join(key. a len recs sequence of postﬁxes returns a record array with columns [rowkey.rk4(derivs. name. namePFN-1]. missing=0. t) Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. The defaults keyword is a dictionary ﬁlled with {column_name:default_value} pairs. namen-1]. recs. [rowkey. jointype=’inner’.mlab.1. The jointype keyword can be ‘inner’.mlab. r2postﬁx=‘2’) Join record arrays r1 and r2 on key.mlab. r1postﬁx=‘1’. jointype=’outer’. The keywords r1postﬁx and r2postﬁx are postﬁxed to column names (other than keys) that are both in r1 and r2. then their ﬁelds will be merged into a new record array containing the intersection of the ﬁelds of r1 and r2. PF1. r1]. Release 1.rec_summarize(r. This is a toy implementation which may be useful if you ﬁnd yourself stranded on a system w/o scipy. ‘outer’.mlab. with extra arrays for each element in summaryfuncs.integrate().mlab. matplotlib. names) Return a new numpy record array with only ﬁelds listed in names matplotlib. r1.mlab 655 . matplotlib.Matplotlib.0.. . . namePF1. The returned record array is identical to r.rec_join(key.. ‘leftouter’. y0 initial state vector 48..1 matplotlib. To do a rightouter join just reverse r1 and r2. key is a tuple of ﬁeld names – if key is a string it is assumed to be a single attribute name.rec_keep_fields(rec. PFN-1] are supplied. namePF0. outname) tuples which will apply func to the the array r*[attr] and assign the output to a new attribute name *outname. If r1 and r2 have equal values on all the keys in the key tuple. matplotlib. 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 ﬁeld is replaced by postﬁxes if not None.0.. name0.

save(fname.mlab.0. delimiter ‘. The load() function understands gzipped ﬁles transparently. Use numpy. matplotlib. t) If you have access to scipy.t): return -alpha*x + exp(-t) y0 = 1 yout = rk4(derivs.0. Example usage: save(’test.integrate tools rather than this function. X.safe_isnan(x) numpy.out’.isinf() for arbitrary types matplotlib. Deprecated.mlab. x.1 t sample times derivs returns the derivative of the system and has the signature dy = derivs(yi.safe_isinf(x) numpy.0.savetxt. (x.4e’) # use exponential notation delimiter is used to separate the ﬁelds.y. you should probably be using the scipy. delimiter=’ ‘) Save the data in X to ﬁle fname using fmt string to convert the data to strings. eg.out’. fname can be a ﬁlename or a ﬁle handle. X) # X is an array save(’test1. ﬂattened out.y.isnan() for arbitrary types matplotlib. fmt=’%1.0005 t = arange(0. matplotlib mlab .out’. d2) dt = 0. matplotlib.2) yout = rk4(derivs6.z)) # x. y0. x) # x is 1D save(’test3.gz’. 2.18e’.’ for comma-separated values.rms_flat(a) Return the root mean square of all the elements of a. Release 1. fmt=’%. the ﬁle is automatically saved in compressed gzip format.mlab. 656 Chapter 48. y0.mlab. dt) y0 = (1.z equal sized 1D arrays save(’test2. ti) Example 1 ## 2D system def derivs6(x.t): d1 = x[0] + 2*x[1] d2 = -3*x[0] + 4*x[1] return (d1. t) Example 2: ## 1D system alpha = 2 def derivs(x.Matplotlib. If the ﬁlename ends in ‘.out’.

but you can use a custom function as well. designed to remove the mean or linear trend.1. matplotlib. y1). Fs: scalar The sampling frequency (samples per time unit).is) matplotlib.e. It is used to calculate the Fourier frequencies. Data are split into NFFT length segements and the PSD of each section is computed. If x is real (i.Matplotlib. Fs=2. Institute of Theoretical Physics. y2) s2: (x3.Nemec at physik.0. so an aspect ratio is completely arbitrary. sides=’default’. noverlap=128. scale_by_freq=None) Compute a spectrogram of data in x. If x is complex then the complete spectrum is returned. (x2. Must be even. The pylab module deﬁnes detrend_none(). This method should be superior to that described in the appendix of A CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russel W. and detrend_linear(). 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.segments_intersect(s1. the abscissa are given in diﬀerent dimensions. and the amount of overlap of each segment is speciﬁed with noverlap. Release 1. in matplotlib is it a function. s2) Return True if s1 and s2 intersect. pad_to=None.de (inspired by a original implementation by Halldor Bjornsson. freqs. March 2006 halldor at vedur. For many functions. April 2006 Norbert. non-complex) only the spectrum of the positive frequencie is returned. University or Regensburg. The default value is 2.mlab 657 .specgram(x.mlab. detrend=<function detrend_none at 0x3a1c668>. in cycles per time unit. Icelandic Meteorological Oﬃce. 48. detrend: callable The function applied to each segment before ﬀt-ing. detrend_mean().mlab.uni-regensburg. Stineman (Creative Computing July 1980) in at least one aspect: Circles for interpolation demand a known aspect ratio between x. y3). however. where the detrend parameter is a vector. Keyword arguments: NFFT: integer The number of data points used in each block for the FFT. The windowing function window is applied to each segment.slopes(x. The default value is 256. s1 and s2 are deﬁned as: s1: (x1. a power 2 is most eﬃcient. Norbert Nemec. NFFT=256. Unlike in MATLAB. The parabola method gives very similar results to the circle method for most regular cases but behaves much better in special cases.1 matplotlib. window=<function window_hanning at 0x3a178c0>. y4) matplotlib.and y-values. (x4.mlab.

While not increasing the actual resolution of the psd (the minimum distance between resolvable peaks).40). which sets pad_to equal to NFFT sides: [ ‘default’ | ‘onesided’ | ‘twosided’ ] Speciﬁes which sides of the PSD to return.x.get_window(). yp = cos(x) xi = linspace(0. Default gives the default behavior. ‘onesided’ forces the return of a one-sided PSD. 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.2*pi.signal. The default value is 0 (no overlap). window_none().bartlett().y. scale_by_freq: boolean Speciﬁes whether the resulting density values should be scaled by the scaling frequency. pad_to: integer The number of points to which the data segment is padded when performing the FFT.yp). The default is None. plot(x. noverlap: integer The number of points of overlap between blocks. yp=None) Given data vectors x and y. yi = stineman_interp(xi. which speciﬁes the number of data points used.1 window: callable or ndarray A function or a vector of length NFFT. x. 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. in returning the mean of the segment periodograms. then interpolates over a ﬁner abscissa: x = linspace(0. The default is True for MATLAB compatibility. and in not returning times. etc. See Also: psd() psd() diﬀers in the default overlap. the slope vector yp and a new abscissa vector xi. t): •Pxx: 2-D array. which returns one-sided for real data and both for complex data. numpy. To create window vectors see window_hanning(). freqs.y. Release 1. the function stineman_interp() uses Stineman interpolation to calculate a vector yi corresponding to xi.2*pi.stineman_interp(xi. scipy. numpy. y = sin(x).signal(). while ‘twosided’ forces two-sided. which gives density in units of Hz^-1.xi. Stineman.Matplotlib. y. The default is window_hanning(). This corresponds to the n parameter in the call to ﬀt(). scipy. matplotlib mlab . Returns a tuple (Pxx. this can give more points in the plot.blackman(). If a function is passed as the argument.’o’. This allows for integration over the returned frequency values.0. Here’s an example that generates a coarse sine curve. it must take a data segment as an argument and return the windowed version of the segment. numpy.20).yi) The interpolation method is described in the article A CONSISTENTLY WELL BEHAVED METHOD OF INTERPOLATION by Russell W.hamming(). matplotlib. allowing for more detail. This can be diﬀerent from NFFT.mlab.

Release 1. simply return x 48. For values xi[j] < x[0] or xi[j] > x[-1]. P=2. compute over all elements of X.is Completely reworked and optimized for Python by Norbert Nemec.de matplotlib.uni-regensburg. axis=None) Finds the length of a set of vectors in n dimensions. University or Regensburg. The relevance of the data obtained from this. April 2006 Norbert. Institute of Theoretical Physics.mlab. Original implementation by Halldor Bjornsson. This is like the numpy.Matplotlib. of course.Nemec at physik.1. If axis is None.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. Computes (sum((x_i)^P))^(1/P) for each {x_i} being the elements of X along the given axis. the routine tries an extrapolation. For yp = None. x is assumed to be sorted in increasing order.. Icelandic Meteorolocial Oﬃce. but has the ability to work over a particular axis of the supplied array or matrix. matplotlib.window_hanning(x) return x times the hanning window of len(x) matplotlib. is questionable.mlab.0.window_none(x) No window function.mlab 659 .mlab.norm() function for vectors.0. the routine automatically determines the slopes using the slopes() routine. matplotlib.vector_lengths(X.. March 2006 halldor at vedur.

Matplotlib. matplotlib mlab .1 660 Chapter 48.0. Release 1.

path Contains a class for managing paths (polylines). as an optimization. with the given control points.1 matplotlib. to represent a cubic curve. The underlying storage is made up of two parallel numpy arrays: • vertices: an Nx2 ﬂoat array of vertices • codes: an N-length uint8 array of vertex types These two arrays always have the same length in the ﬁrst dimension. but have a default one provided for them by iter_segments(). with the given control point. 1 endpoint] Draw a quadratic Bezier curve from the current position. line and curve segments. •CURVE3 [1 control point.CHAPTER FORTYNINE MATPLOTLIB PATH 49. do not store a codes at all. 661 . possibly closed. 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. •CURVE4 [2 control points. you must provide three vertices as well as three codes CURVE3. to the given end point. they should use iter_segments() to get the vertex/code pairs. For example. to the given end point.path. This is important. codes=None. since many Path objects.Path(vertices. _interpolation_steps=1) Bases: object Path represents a series of possibly disconnected. class matplotlib. 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. •CLOSEPOLY [1 vertex (ignored)] Draw a line segment to the start point of the current polyline. •LINETO [1 vertex] Draw a line from the current position to the given vertex. Users of Path objects should not access the vertices and codes arrays directly. Instead. 1 endpoint] Draw a cubic Bezier curve from the current position.

That is. ﬁlled=True) Returns True if this path intersects a given Bbox. These two arrays must have the same length in the ﬁrst dimension.0. If n is not provided. Release 1. ymax) of the path.Matplotlib. if one path completely encloses the other. interpolation_steps is used as a hint to certain projections. is_wedge=False) (staticmethod) Returns an arc on the unit circle from angle theta1 to angle theta2 (in degrees). If n is provided. such as iter_segments(). Masionobe.path. matplotlib path . n=None. hatchpattern. that this path should be linearly interpolated immediately before drawing. they will be converted to NaNs which are then handled correctly by the Agg PathIterator and other consumers of path data. This attribute is primarily an implementation detail and is not intended for public use. xmax. density=6) Given a hatch speciﬁer. ymin. masked array or Python sequence. when True. the path will be transformed before performing the test.code_type. Does not currently handle interpolating curves. 662 Chapter 49. vertices will be treated as a series of line segments.Path. If vertices contains masked values. Unlike computing the extents on the vertices alone. code_type alias of uint8 contains_path(path. interpolated(steps) Returns a new path resampled to length N x steps.1 Create a new path with the given vertices and codes. If transform is not None. get_extents(transform=None) Returns the extents (xmin. it is the number of spline segments to make. contains_point(point. If transform is not None. transform=None) Returns True if this path completely contains the given path. L. classmethod arc(theta1. generates a Path that can be used in a repeated hatching pattern. 2003. quadratic or cubic Bezier curves. intersects_path() will return True. classmethod hatch(hatchpattern. codes is an N-length numpy array or Python sequence of type matplotlib. vertices is an Nx2 numpy ﬂoat array. If codes is None. density is the number of lines per unit square. theta2. intersects_bbox(bbox. the number of spline segments is determined based on the delta between theta1 and theta2. Drawing an elliptical arc using polylines. the path will be transformed before performing the test. such as Polar. transform=None) Returns True if the path contains the given point. ﬁlled. this algorithm will take into account the curves and deal with control points appropriately. treats the path as if it was ﬁlled.

If None. classmethod make_compound_path(*args) (staticmethod) Make a compound path from a list of Path objects. when True. See Also: 49. force stroke_width: the width of the stroke being drawn. treats the paths as if they were ﬁlled. transformed(transform) Return a transformed copy of the path. In other words. clip=None. Needed as a hint for the snapping algorithm. (width. stroke_width=1. intersects_path() will return True.0. all curves will be converted to line segments. must be a four-tuple (x1. This is useful for displaying in backends that do not support compound paths or Bezier curves. snap: if None.3 coordinate pairs. each polygon has no MOVETO instructions or curves. auto-snap to pixels. Only polygons (not curves) are supported. y2) deﬁning a rectangle in which to clip the path. the given aﬃne transformation will be applied to the path. curve segments will be returned as curve segments. clip: if not None. Each polygon is an Nx2 array of vertices. where vertices is a sequence of 1 . 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. to remove vertices that do not aﬀect the appearance of the path. height=0) Convert this path to a list of polygons.Matplotlib. curves: If True. use the should_simplify member variable. perform simpliﬁcation. perform no simpliﬁcation. code). snapping. Release 1. this method can provide a number of standard cleanups and conversions to the path. will remove all NaNs from the path and insert MOVETO commands to skip over them. If width and height are both non-zero then the lines will be simpliﬁed so that vertices outside of (0.1 intersects_path(other. If False. Additionally. remove_nans=True. Each iteration returns a 2-tuple (vertices. Return object is a Path to_polygons(transform=None. remove_nans: if True. iter_segments(transform=None. x2. y1. don’t snap. and if False. height) will be clipped. 0). If False. snap=False. If True. and code is one of the Path codes. That is. simplify=None. curves=True) Iterates over all of the curve segments in the path. ﬁlled=True) Returns True if this path intersects another given path. simplify: if True. matplotlib.1. width=0. transform: if not None.0. such as GDK.path 663 . to reduce fuzziness of rectilinear lines. ﬁlled. if one path completely encloses the other.

0. classmethod unit_circle() (staticmethod) Returns a Path of the unit circle. Release 1.transforms. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines.Matplotlib. 1). The circle is approximated using cubic Bezier curves. classmethod unit_regular_polygon(numVertices) 664 Chapter 49. 0). The circle is approximated using cubic Bezier curves.TransformedPath A specialized path class that will cache the transformed result and automatically update when the transform changes. Approximating a Circle or an Ellipse Using Four Bezier Cubic Splines. This uses 8 splines around the circle using the approach presented here: Lancaster. matplotlib path . 0) to (1.1 40 30 20 10 0 2 1 0 1 2 matplotlib. centered at (0. Don. This uses 4 splines around the circle using the approach presented here: Lancaster. classmethod unit_rectangle() (staticmethod) Returns a Path of the unit rectangle from (0. classmethod unit_regular_asterisk(numVertices) (staticmethod) Returns a Path for a unit regular asterisk with the given numVertices and radius of 1. classmethod unit_circle_righthalf() (staticmethod) Returns a Path of the right half of a unit circle.0. Don.

path. classmethod wedge(theta1. trans.path. remove_nans. centered at (0.0. transforms.path. matplotlib.path. p2) matplotlib.0. n=None) (staticmethod) Returns a wedge of the unit circle from angle theta1 to angle theta2 (in degrees).1 (staticmethod) Returns a Path for a unit regular polygon with the given numVertices and radius of 1.point_in_path_collection() point_in_path_collection(x. the number of spline segments is determined based on the delta between theta1 and theta2. paths. oﬀsetTrans. oﬀsets. If n is provided. height) matplotlib.path_intersects_path() path_intersects_path(p1.5) (staticmethod) Returns a Path for a unit regular star with the given numVertices and radius of 1.0.path. it is the number of spline segments to make. trans. trans) matplotlib. y. width. centered at (0. 0). If n is not provided.path. matplotlib. classmethod unit_regular_star(numVertices.convert_path_to_polygons() convert_path_to_polygons(path. ﬁlled) 49. simplify. Release 1. returns the bounding box that encapsulates all of them.path 665 . b.Matplotlib. trans) matplotlib. innerCircle=0. curves) matplotlib. btrans) matplotlib. trans. clip.1.get_path_extents() get_path_extents(path. path. 0). theta2. r. snap.point_in_path() point_in_path(x.path.cleanup_path() cleanup_path(path.path.get_path_collection_extents(*args) Given a sequence of Path objects.path_in_path() path_in_path(a. atrans. y. matplotlib.

matplotlib path . Release 1.Matplotlib.0.1 666 Chapter 49.

pyplot as plt x = np. though these can be overridden with keyword args.sin(x) plt. 667 . If normed = True. Data are plotted as plot(lags. maxlags is a positive integer detailing the number of lags to show. detrend=mlab. x is detrended by the detrend callable (default no normalization). vlines() rather than plot() is used to draw vertical lines from the origin to the acorr. 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’. maxlags=10. normalize the data by the autocorrelation at 0-th lag. The cross correlation is performed with numpy. **kwargs) Return value is a tuple (lags. e.1 matplotlib.detrend_none.pyplot Provides a MATLAB-like plotting framework.plot(x. y) matplotlib.correlate() with mode = 2.1).pyplot. 5. 0. **kwargs) call signature: acorr(x. Otherwise. hold=None. c.arange(0. pylab combines pyplot with numpy into a single namespace. usevlines=True. This is convenient for interactive work. but for programming it is recommended that the namespaces be kept separate. the plot style is determined by the kwargs. The default value of None will return all 2imeslen(x) − 1 lags. y = np.acorr(x. c.: import numpy as np import matplotlib. normed=True.g. If usevlines is True.CHAPTER FIFTY MATPLOTLIB PYPLOT 50. which are Line2D properties. **kwargs) Plot the autocorrelation of x.

00 0.8 0.annotate(*args.4 0.260 40 20 0 20 40 60 40 20 0 20 40 60 Additional kwargs: hold = [True|False] overrides default hold state matplotlib. xy.0. b) where •linecol is the LineCollection •b is the x-axis. xycoords=’data’.15 0. **kwargs) Keyword arguments: 668 Chapter 50.0 0.2 0. and acorr() below. Example: xcorr() above. linecol. xytext=None.6 0. textcoords=’data’.1 The return value is a tuple (lags. See Also: plot() or vlines() For documentation on valid kwargs. c.2060 1.10 0.05 0.pyplot. Example: 0.20 0.15 0.05 0. matplotlib pyplot .0 0.Matplotlib. Release 1. arrowprops=None.10 0. **kwargs) call signature: annotate(s.

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.pyplot 669 . y point xy with text s at x. Release 1.Matplotlib. defaults to xy. (If xytext = None. Otherwise.PathPatch xycoords and textcoords are strings that indicate the coordinates of xy and xytext. ie. defaults to xycoords). a YAArow patch instance is created and drawn. If the dictionary has a key arrowstyle. 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. shrink=0. is a dictionary of line properties (see matplotlib. and if textcoords = None.0.5.patches.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.05 is 5% any key for matplotlib.Line2D) for the arrow that connects annotation to the point. If d is the distance between the text and annotated point. 0. shrink will shorten the arrow so the tip and base are shink percent of the distance d away from the endpoints. matplotlib. if not None. 50.1.patches. a FancyArrowPatch instance is created with the given dictionary and is drawn.1 Annotate the x. any key for matplotlib. y location xytext.lines. arrowprops.

xycoords=’axes points’ You may use an instance of Transform or Artist. which behave as True only if xycoords is”data”.0 is lower left of ﬁgure and 1.0 transparent through 1.1 is upper. Additional kwargs are Text properties: Property agg_filter alpha animated axes backgroundcolor bbox clip_box clip_on clip_path Description unknown ﬂoat (0. Transform) | Patch | None ] 670 Chapter 50. If True.1 is lower left of axes and 1. If a ‘points’ or ‘pixels’ option is speciﬁed.0 opaque) [True | False] an Axes instance any matplotlib color rectangle prop dict a matplotlib. If False. See Annotating Axes for more details.transforms.Bbox instance [True | False] [ (Path. Release 1. values will be added to the bottom-left and if negative. the annotation will only be drawn when the xy is inside the axes. values will be subtracted from the top-right.1 Property ‘ﬁgure points’ ‘ﬁgure pixels’ ‘ﬁgure fraction’ ‘axes points’ ‘axes pixels’ ‘axes fraction’ ‘data’ ‘oﬀset points’ ‘polar’ Description points from the lower left corner of the ﬁgure pixels from the lower left corner of the ﬁgure 0. the annotation will always be drawn regardless of its position.0. you do not need to specify polar for the coordinate system since that is the native “data” coordinate system. The default is None.1 is upper right use the coordinate system of the object being annotated (default) Specify an oﬀset (in points) from the xy value you can specify theta. matplotlib pyplot .Matplotlib. even in cartesian plots. r for the annotation.-5). The annotation_clip attribute contols the visibility of the annotation when it goes outside the axes area. Note that if you are using a polar axes. 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.

y) to (x + dx. dx.Figure instance a matplotlib. dy.1 Table 50.font_manager.arrow(x.pyplot 671 .FontProperties instance an id string [ ‘center’ | ‘right’ | ‘left’ ] any string ﬂoat (multiple of font size) [True | False] [’left’ | ‘right’ | ‘center’ ] unknown [None|ﬂoat|boolean|callable] (x.pyplot. 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’ | ﬂoat ﬂoat any number matplotlib. dx. **kwargs) Draws arrow on speciﬁed axis from (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. dy.figure. Optional kwargs control the arrow properties: 50. hold=None. y.Matplotlib. Release 1.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. y + dy). **kwargs) call signature: arrow(x.1. matplotlib. y.

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.0.Matplotlib. matplotlib pyplot . Release 1.

if False.transforms.autogen_docstring(base) Autogenerated wrappers will get their docstring from a base function with an addendum. enable: [True | False | None] True (default) turns autoscaling on.Figure instance [True | False] an id string [ ‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘. axis=’both’. matplotlib.Matplotlib.figure. matplotlib.pyplot. 50. or None for default. otherwise treat tight as False. Transform) | Patch | None ] matplotlib color spec a callable function mpl color spec. use tight scaling if the only artist is an image. or ‘none’ for no color 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 Example: Description unknown ﬂoat or None [True | False] [True | False] or None for default an Axes instance a matplotlib.’ | ‘*’ ] any string [’solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’] ﬂoat or None for default [True | False] unknown [None|ﬂoat|boolean|callable] [True | False | None] unknown Transform instance a url string [True | False] any number Exception occurred rendering plot. let the locator and margins expand the view limits.autoscale(enable=True. or ‘none’ for no color a matplotlib. axis: [’x’ | ‘y’ | ‘both’] which axis to operate on.1.pyplot 673 . if None. tight=None) Convenience method for simple axis view autoscaling. None leaves the autoscaling state unchanged. and then. it performs the autoscaling on the speciﬁed axis or axes. or None for default. if autoscaling for either axis is on. Additional kwargs: hold = [True|False] overrides default hold state matplotlib.Bbox instance [True | False] [ (Path. It turns autoscaling on or oﬀ. The tight setting is retained for future autoscaling until it is explicitly changed. Release 1. False turns it oﬀ.0. default is ‘both’ tight: [True | False | None] If True. set view limits to data limits.pyplot.

and can be used to control the line properties. with the exception of ‘transform’: 674 Chapter 50.0=right but the y location is in data coordinates. xmax=1.75) Valid kwargs are Line2D properties. default white.5=middle. height] in normalized (0. •draw a thick red hline at y = 0 that spans the xrange >>> axhline(linewidth=4. the horizontal extent i