0% found this document useful (0 votes)
10 views29 pages

Mat Plot Lib

The Matplotlib Mini Guide provides an overview of the Matplotlib library, including the structure of figures, axes, and artists. It contains sample codes for various types of plots such as pie charts, bar charts, and scatter plots, along with explanations of key concepts and functions. The guide serves as a practical reference for users looking to create visualizations using Matplotlib.

Uploaded by

thuy duong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views29 pages

Mat Plot Lib

The Matplotlib Mini Guide provides an overview of the Matplotlib library, including the structure of figures, axes, and artists. It contains sample codes for various types of plots such as pie charts, bar charts, and scatter plots, along with explanations of key concepts and functions. The guide serves as a practical reference for users looking to create visualizations using Matplotlib.

Uploaded by

thuy duong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Matplotlib Mini Guide

Phan Nguyen Ky Phuc

January 7, 2024

Contents

1 Parts of a Figure 1

2 Sample codes 5

2.1 Basic pie chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2 Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.3 Stacked Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.4 Horizontal Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.5 Scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.6 Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.7 Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.8 Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.9 Text and Annotate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.10 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.11 Set Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Patches 9

4 Backend 9

5 Moving Spine and Ticker 9

5.1 Setting Ticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

6 Legend and Annotation 11

7 Axes 12

1 Parts of a Figure

Matplotlib is hierarchically organized.

1
Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

• The top of the tree-like structure of matplotlib objects is the figure object.

• A figure can be seen as the container which contains one or more plots.

• The plots are called axes in matplotlib jargon.

Figure 1: Matplotlib Object Hierarchy 1

Figure
The whole figure. The figure keeps track of all the child Axes, a smattering of ’special’ artists (titles, figure
legends, etc), and the canvas. A figure can contain any number of Axes, but will typically have at least
one.The easiest way to create a new figure is with pyplot:
1 f i g = p l t . f i g u r e ( ) # an empty f i g u r e with no Axes
2 f i g , ax = p l t . s u b p l o t s ( ) # a f i g u r e with a s i n g l e Axes
3 f i g , a x s = p l t . s u b p l o t s ( 2 , 2 ) # a f i g u r e with a 2 x2 g r i d o f Axes

It’s convenient to create the axes together with the figure, but you can also add axes later on, allowing for
more complex axes layouts.
Axes
This is what you think of as ’a plot’, it is the region of the image with the data space. A given figure can
contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in
the case of 3D) Axis objects (be aware of the difference between Axes and Axis) which take care of the data
limits. Each Axes can set:

• ax.set_ylim(), ax.set_xlim(),ax.set_xscale(’linear’),ax.set_yscale(’log’)

• ax.set_title(), ax.set_xlabel(), ax.set_ylabel(), ax.legend(), ax.grid(True)

• ax.text(), ax.annotation()

• ax.plot(), ax.scatter(), ax.pie(), ax.bar(), ax.barh(),ax.add_table(),ax.fill()

Matplotlib Mini Guide Page 2


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

• ax.add_patch(),

• ax.clear()

The Axes class and its member functions are the primary entry point to working with the OO interface.
Axis
Axis take care of setting the graph limits and generating the ticks (the marks on the axis) and ticklabels
(strings labeling the ticks). The location of the ticks is determined by a Locator object and the ticklabel
strings are formatted by a Formatter. The combination of the correct Locator and Formatter gives very fine
control over the tick locations and labels.
Artist
Basically everything you can see on the figure is an artist (even the Figure, Axes, and Axis objects). This
includes Text objects, Line2D objects, collections objects, Patch objects ... (you get the idea). When the
figure is rendered, all of the artists are drawn to the canvas. MostArtists are tied to an Axes; such an Artist
cannot be shared by multiple Axes, or moved from one to another.
1 x = np . l i n s p a c e ( 0 , 2 , 1 0 0 )
2 # Note t h a t even i n t h e OO−s t y l e , we u s e ‘ . p y p l o t . f i g u r e ‘ t o c r e a t e t h e f i g u r e .
3 f i g , ax = p l t . s u b p l o t s ( ) # C r e a t e a f i g u r e and an a x e s .
4 ax . p l o t ( x , x , l a b e l= ’ l i n e a r ’ ) # P l o t some data on t h e a x e s .
5 ax . p l o t ( x , x ∗ ∗ 2 , l a b e l= ’ q u a d r a t i c ’ ) # P l o t more data on t h e a x e s . . .
6 ax . p l o t ( x , x ∗ ∗ 3 , l a b e l= ’ c u b i c ’ ) # . . . and some more .
7 ax . s e t _ x l a b e l ( ’ x l a b e l ’ ) # Add an x−l a b e l t o t h e a x e s .
8 ax . s e t _ y l a b e l ( ’ y l a b e l ’ ) # Add a y−l a b e l t o t h e a x e s .
9 ax . s e t _ t i t l e ( " S im pl e P l o t " ) # Add a t i t l e t o t h e a x e s .
10 ax . l e g e n d ( ) # Add a l e g e n d .

Typically one finds oneself making the same plots over and over again, but with different data sets, which
leads to needing to write specialized functions to do the plotting. The recommended function signature is
something like:
1 d e f my_plotter ( ax , data1 , data2 , param_dict ) :
2 """
3 A h e l p e r f u n c t i o n t o make a graph
4 Parameters
5 −−−−−−−−−−
6 ax : Axes
7 The a x e s t o draw t o
8 data1 : a r r a y
9 The x data
10 data2 : a r r a y
11 The y data
12 param_dict : d i c t
13 D i c t i o n a r y o f kwargs t o p a s s t o ax . p l o t
14 Returns
15 −−−−−−−
16 out : l i s t
17 l i s t o f a r t i s t s added
18 """
19 out = ax . p l o t ( data1 , data2 , ∗∗ param_dict )
20 r e t u r n out

which you would then use as:


1 data1 , data2 , data3 , data4 = np . random . randn ( 4 , 1 0 0 )
2 f i g , ax = p l t . s u b p l o t s ( 1 , 1 )
3 my_plotter ( ax , data1 , data2 , { ’ marker ’ : ’ x ’ } )

or if you wanted to have 2 sub-plots:

Matplotlib Mini Guide Page 3


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

1 f i g , ( ax1 , ax2 ) = p l t . s u b p l o t s ( 1 , 2 )
2 my_plotter ( ax1 , data1 , data2 , { ’ marker ’ : ’ x ’ })
3 my_plotter ( ax2 , data3 , data4 , { ’ marker ’ : ’ o ’ })

Legends
The default legend behavior for axes attempts to find the location that covers the fewest data points
(loc=’best’). This can be a very expensive computation if there are lots of data points. In this case,
you may want to provide a specific location.
Using the fast style
The fast style can be used to automatically set simplification and chunking parameters to reasonable settings
to speed up plotting large amounts of data. It can be used simply by running:
1 im po rt m a t p l o t l i b . s t y l e a s m p l s t y l e
2 mplstyle . use ( ’ f a s t ’ )

It is very light weight, so it plays nicely with other styles, just make sure the fast style is applied last so that
other styles do not overwrite the settings:
1 m p l s t y l e . u s e ( [ ’ dark_background ’ , ’ g g p l o t ’ , ’ f a s t ’ ] )

Character Color and Marker

Matplotlib Mini Guide Page 4


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

Plotting with categorical variables


1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 f i g , axs = p l t . s u b p l o t s ( 1 , 2)
3 a =[ ’ a ’ , ’ b ’ , ’ c ’ ]
4 y=[1 ,3 ,5]
5 a x s [ 0 ] . bar ( a , y )
6 axs [ 1 ] . s c a t t e r ( a , y )

2 Sample codes

2.1 Basic pie chart


1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 # P i e c h a r t , where t h e s l i c e s w i l l be o r d e r e d and p l o t t e d c o u n t e r −c l o c k w i s e :
3 l a b e l s = ’ F r og s ’ , ’ Hogs ’ , ’ Dogs ’ , ’ Logs ’
4 s i z e s = [ 1 5 , 30 , 45 , 10]
5 e x p l o d e = ( 0 , 0 . 1 , 0 , 0 ) # o n l y " e x p l o d e " t h e 2nd s l i c e ( i . e . ’ Hogs ’ )
6 f i g 1 , ax1 = p l t . s u b p l o t s ( )
7 ax1 . p i e ( s i z e s , e x p l o d e=e x p l o d e , l a b e l s=l a b e l s , a u t o p c t= ’ %1.1 f%%’ ,
8 shadow=True , s t a r t a n g l e =90)
9 ax1 . a x i s ( ’ e q u a l ’ ) # Equal a s p e c t r a t i o e n s u r e s t h a t p i e i s drawn a s a c i r c l e .
10 p l t . show ( )

2.2 Bar Chart


1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 x= ( ’G1 ’ , ’G2 ’ , ’G3 ’ , ’G4 ’ , ’G5 ’ )
3 y = [1 ,3 ,4 ,2 ,7]

Matplotlib Mini Guide Page 5


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

4 f i g , ax=p l t . s u b p l o t s ( )
5 ax . bar ( x , y , c o l o r= ’ c ’ )
6 p l t . show ( )

2.3 Stacked Bar Chart

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 x= ( ’G1 ’ , ’G2 ’ , ’G3 ’ , ’G4 ’ , ’G5 ’ )
3 y1 = [ 1 , 3 , 4 , 2 , 7 ]
4 y2 = [ 1 , 2 , 2 , 1 , 1 ]
5 f i g , ax=p l t . s u b p l o t s ( )
6 ax . bar ( x , y1 , c o l o r= ’ c ’ , l a b e l= ’Men ’ )
7 ax . bar ( x , y2 , c o l o r= ’ y ’ , bottom=y1 , l a b e l= ’Women ’ )
8 ax . l e g e n d ( )
9 p l t . show ( )

2.4 Horizontal Bar Chart

1 from m a t p l o t l i b im po rt pyplot as p l t
2 x= ( ’G1 ’ , ’G2 ’ , ’G3 ’ , ’G4 ’ , ’G5 ’ )
3 y1 = [ 1 , 3 , 4 , 2 , 7 ]
4 y2 = [ 1 , 2 , 2 , 1 , 1 ]
5 f i g , ax=p l t . s u b p l o t s ( )
6 ax . barh ( x , y1 , c o l o r= ’ c ’ , l a b e l= ’Men ’ )
7 ax . barh ( x , y2 , c o l o r= ’ y ’ , l e f t =y1 , l a b e l= ’Women ’ )
8 ax . i n v e r t _ y a x i s ( )
9 ax . l e g e n d ( )
10 p l t . show ( )

2.5 Scatter

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 from m a t p l o t l i b im po rt p y p l o t a s p l t
3 x= ( ’G1 ’ , ’G2 ’ , ’G3 ’ , ’G4 ’ , ’G5 ’ )
4 y1 = [ 1 , 3 , 4 , 2 , 7 ]
5 y2 = [ 1 , 2 , 2 , 1 , 1 ]
6 f i g , ax=p l t . s u b p l o t s ( )
7 ax . s c a t t e r ( x , y1 , c o l o r= ’ r ’ , marker= ’ x ’ , l a b e l= ’Women ’ )
8 ax . l e g e n d ( )
9 p l t . show ( )

2.6 Plot

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 x= ( ’G1 ’ , ’G2 ’ , ’G3 ’ , ’G4 ’ , ’G5 ’ )
3 y1 = [ 1 , 3 , 4 , 2 , 7 ]
4 y2 = [ 1 , 2 , 2 , 1 , 1 ]
5 f i g , ax=p l t . s u b p l o t s ( )
6 ax . p l o t ( x , y1 , ’ r−< ’ , x , y2 , ’ b−−o ’ )
7 ax . l e g e n d ( )
8 p l t . show ( )

2.7 Table

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 x= ( ’G1 ’ , ’G2 ’ , ’G3 ’ , ’G4 ’ , ’G5 ’ )
3 y1 = [ 1 , 3 , 4 , 2 , 7 ]
4 y2 = [ 1 , 2 , 2 , 1 , 1 ]

Matplotlib Mini Guide Page 6


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

5 f i g , ax=p l t . s u b p l o t s ( )
6

7 columns = ( ’ F r e e z e ’ , ’ Wind ’ , ’ Flood ’ )


8 rows =[ ’AD ’ , ’AC ’ , ’DC ’ ]
9 t a b l e=p l t . t a b l e ( c e l l T e x t = [ [ 1 , 3 , 4 ] , [ 2 , 5 , 6 ] , [ 3 , 7 , 8 ] ] , c e l l C o l o u r s = [ [ ’ r ’ , ’ b ’ , ’ g ’ ] , [ ’ r ’ , ’ b ’ , ’ g ’
] , [ ’ r ’ , ’ b ’ , ’ g ’ ] ] , r o w L a b e l s=rows ,
10 c o l L a b e l s=columns , l o c= ’ bottom ’ )
11 ax . p l o t ( x , y1 , ’ r−o ’ )
12 ax . add_table ( t a b l e )
13 p l t . show ( )

2.8 Fill

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 x= ( 1 , 2 , 7 , 0 , )
3 y1 = [ 1 , 3 , 4 , 0 ]
4 f i g , ax=p l t . s u b p l o t s ( )
5 ax . f i l l ( x , y1 , ’ r ’ )
6 p l t . show ( )

2.9 Text and Annotate

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 x= ( 1 , 2 , 7 , 0 , )
3 y1 = [ 1 , 3 , 4 , 0 ]
4 f i g , ax=p l t . s u b p l o t s ( )
5 ax . s e t _ x l i m ( ( 0 , 5 ) )
6 ax . s e t _ y l i m ( ( 0 , 5 ) )
7 ax . t e x t ( 1 , 1 , ’ Good Weather ’ )
8 ax . a n n o t a t e ( ’ a n n o t a t e ’ , xy =(2 , 1 ) , x y t e x t =(3 , 4 ) , a r r o w p r o p s=d i c t ( f a c e c o l o r= ’ b ’ , s h r i n k =0 .0 5)
)
9 p l t . show ( )

2.10 Subplots

1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt numpy a s np
3 np . random . s e e d ( 1 9 6 8 0 8 0 1 )
4 data = np . random . randn ( 2 , 1 0 0 )
5 f i g , a x s = p l t . s u b p l o t s ( 2 , 2 , f i g s i z e =(5 , 5 ) )
6 a x s [ 0 , 0 ] . h i s t ( data [ 0 ] )
7 a x s [ 1 , 0 ] . s c a t t e r ( data [ 0 ] , data [ 1 ] )
8 a x s [ 0 , 1 ] . p l o t ( data [ 0 ] , data [ 1 ] )
9 a x s [ 1 , 1 ] . h i s t 2 d ( data [ 0 ] , data [ 1 ] )
10 p l t . show ( )

2.11 Set Styles

1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 p l t . s t y l e . u s e ( ’ dark_background ’ )

To print all available styles


1 print ( plt . style . available )
2

3 [ ’ S o l a r i z e _ L i g h t 2 ’ , ’ _ c l a s s i c _ t e s t _ p a t c h ’ , ’bmh ’ , ’ c l a s s i c ’ , ’ dark_background ’ , ’ f a s t ’ ,
4 , ’ f i v e t h i r t y e i g h t ’ , ’ g g p l o t ’ , ’ g r a y s c a l e ’ , ’ s e a b o r n ’ , ’ s e a b o r n −b r i g h t ’ , ’ s e a b o r n −c o l o r b l i n d ’
,

Matplotlib Mini Guide Page 7


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

5 , ’ s e a b o r n −dark ’ , ’ s e a b o r n −dark−p a l e t t e ’ , ’ s e a b o r n −d a r k g r i d ’ , ’ s e a b o r n −deep ’ , ’ s e a b o r n −muted ’


,
6 , ’ s e a b o r n −notebook ’ , ’ s e a b o r n −paper ’ , ’ s e a b o r n −p a s t e l ’ , ’ s e a b o r n −p o s t e r ’ , ’ s e a b o r n −t a l k ’ ,
7 , ’ s e a b o r n −t i c k s ’ , ’ s e a b o r n −w h i t e ’ , ’ s e a b o r n −w h i t e g r i d ’ , ’ t a b l e a u −c o l o r b l i n d 1 0 ’ ]

Matplotlib Mini Guide Page 8


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

3 Patches

Figure 2: Matplotlib.patches

Example Code
1 from m a t p l o t l i b im po rt p y p l o t a s p l t
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p a t c h e s a s p a t c h e s
4 f i g , ax=p l t . s u b p l o t s ( )
5 ax . s e t ( x l i m = [ 0 , 1 0 ] , y l i m = [ 0 , 1 0 ] )
6 r e c=p a t c h e s . R e c t a n g l e ( ( 0 , 0 ) , 4 , 5 , c o l o r= ’ r e d ’ )
7 c i r=p a t c h e s . C i r c l e ( ( 6 , 2 ) , 1 , c o l o r= ’ b l u e ’ )
8 ax . s e t _ a s p e c t ( ’ e q u a l ’ )
9 ax . add_patch ( r e c )
10 ax . add_patch ( c i r )

4 Backend
1 from m a t p l o t l i b . backends . backend_qt5agg imp ort FigureCanvasQTAgg a s FigureCanvas
2 from m a t p l o t l i b . backends . backend_qt5agg imp ort NavigationToolbar2QT a s N a v i g a t i o n T o o l b a r
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4 im po rt m a t p l o t l i b . p a t c h e s a s p a t c h e s

5 Moving Spine and Ticker

Matplotlib Mini Guide Page 9


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3

4 X = np . l i n s p a c e (−2 ∗ np . pi , 2 ∗ np . pi , 7 0 , e n d p o i n t=True )
5 F1 = np . s i n ( 2 ∗ X)
6 F2 = ( 2 ∗X∗∗5 + 4∗X∗∗4 − 4 . 8 ∗X∗∗3 + 1 . 2 ∗X∗∗2 + X + 1 ) ∗np . exp(−X∗ ∗ 2 )
7

8 f i g , ax = p l t . s u b p l o t s ( )
9

10 # making t h e top and r i g h t s p i n e i n v i s i b l e :


11 ax . s p i n e s [ ’ top ’ ] . s e t _ c o l o r ( ’ none ’ )
12 ax . s p i n e s [ ’ r i g h t ’ ] . s e t _ c o l o r ( ’ none ’ )
13

14 # moving bottom s p i n e up t o y=0 p o s i t i o n :


15 ax . x a x i s . s e t _ t i c k s _ p o s i t i o n ( ’ bottom ’ )
16 ax . s p i n e s [ ’ bottom ’ ] . s e t _ p o s i t i o n ( ( ’ data ’ , 0 ) )
17

18 # moving l e f t s p i n e t o t h e r i g h t t o p o s i t i o n x == 0 :
19 ax . y a x i s . s e t _ t i c k s _ p o s i t i o n ( ’ l e f t ’ )
20 ax . s p i n e s [ ’ l e f t ’ ] . s e t _ p o s i t i o n ( ( ’ data ’ , 0 ) )
21

22 ax . p l o t (X, F1 , X, F2 )
23

24 p l t . show ( )

5.1 Setting Ticks

1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 f i g , ax = p l t . s u b p l o t s ( )
3 # set xticks locations :
4 ax . s e t _ x t i c k s ( [ 7 , 1 3 , 1 9 , 3 3 , 4 2 ] )
5 # set xticks labels :
6 ax . s e t _ x t i c k l a b e l s ( [ ’ B e r l i n ’ , ’ London ’ , ’ Hamburg ’ , ’ Toronto ’ ] )

1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3

4 X = np . l i n s p a c e (−2 ∗ np . pi , 2 ∗ np . pi , 7 0 , e n d p o i n t=True )
5 X = np . l i n s p a c e (−2 ∗ np . pi , 2 ∗ np . pi , 7 0 , e n d p o i n t=True )
6 F1 = np . s i n (X∗ ∗ 2 )
7 F2 = X ∗ np . s i n (X)
8

9 f i g , ax = p l t . s u b p l o t s ( )
10

11 # making t h e top and r i g h t s p i n e i n v i s i b l e :


12 ax . s p i n e s [ ’ top ’ ] . s e t _ c o l o r ( ’ none ’ )
13 ax . s p i n e s [ ’ r i g h t ’ ] . s e t _ c o l o r ( ’ none ’ )
14 # moving bottom s p i n e up t o y=0 p o s i t i o n :
15 ax . x a x i s . s e t _ t i c k s _ p o s i t i o n ( ’ bottom ’ )
16 ax . s p i n e s [ ’ bottom ’ ] . s e t _ p o s i t i o n ( ( ’ data ’ , 0 ) )
17 # moving l e f t s p i n e t o t h e r i g h t t o p o s i t i o n x == 0 :
18 ax . y a x i s . s e t _ t i c k s _ p o s i t i o n ( ’ l e f t ’ )
19 ax . s p i n e s [ ’ l e f t ’ ] . s e t _ p o s i t i o n ( ( ’ data ’ , 0 ) )
20

21 ax . s e t _ x t i c k s ( [ − 6 . 2 8 , −3.14 , 3 . 1 4 , 6 . 2 8 ] )
22 ax . s e t _ y t i c k s ( [ − 3 , −1, 0 , +1 , 3 ] )
23 ax . p l o t (X, F1 )
24 ax . p l o t (X, F2 )
25

26 p l t . show ( )

Matplotlib Mini Guide Page 10


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

6 Legend and Annotation


1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 X = np . l i n s p a c e (−2 ∗ np . pi , 2 ∗ np . pi , 7 0 , e n d p o i n t=True )
4 F1 = np . s i n (X∗ ∗ 2 )
5 F2 = X ∗ np . s i n (X)
6

7 f i g , ax = p l t . s u b p l o t s ( )
8 ax . p l o t (X, F1 , l a b e l= ’ F1 ’ )
9 ax . p l o t (X, F2 , l a b e l= ’ F2 ’ )
10 ax . l e g e n d ( l o c= ’ b e s t ’ )
11 loc_minimum = ( 0 , 0 )
12 glo_minimum = ( 5 , −5)
13 ax . a n n o t a t e ( " l o c a l minimum" , loc_minimum )
14 ax . a n n o t a t e ( " g l o b a l minimum" , glo_minimum )
15 p l t . show ( )

1 ax . a n n o t a t e ( " i n f l e c t i o n p o i n t " ,
2 xy =(0 , p ( 0 ) ) ,
3 x y t e x t =(−3, −30) ,
4 a r r o w p r o p s=d i c t ( f a c e c o l o r= ’ o r a n g e ’ , s h r i n k =0 .0 5) )

1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2

4 d e f demo_con_style ( ax , c o n n e c t i o n s t y l e ) :
5 x1 , y1 = 0 . 3 , 0 . 2
6 x2 , y2 = 0 . 8 , 0 . 6
7

8 ax . p l o t ( [ x1 , x2 ] , [ y1 , y2 ] , " . " )
9 ax . a n n o t a t e ( " " ,
10 xy=(x1 , y1 ) , x y c o o r d s= ’ data ’ ,
11 x y t e x t =(x2 , y2 ) , t e x t c o o r d s= ’ data ’ ,
12 a r r o w p r o p s=d i c t ( a r r o w s t y l e="−>" , c o l o r=" 0 . 5 " ,
13 s hr in k A =5 , s h r i n k B =5 ,
14 patchA=None , patchB=None ,
15 c o n n e c t i o n s t y l e=c o n n e c t i o n s t y l e ) )
16

17 ax . t e x t ( . 0 5 , . 9 5 , c o n n e c t i o n s t y l e . r e p l a c e ( " , " , " , \ n" ) ,


18 t r a n s f o r m=ax . t r a n s A x e s , ha=" l e f t " , va=" top " )
19

20

21 f i g , a x s = p l t . s u b p l o t s ( 3 , 5 , f i g s i z e =(8 , 4 . 8 ) )
22 demo_con_style ( a x s [ 0 , 0 ] , " a n g l e 3 , angleA =90 , angleB=0" )
23 demo_con_style ( a x s [ 1 , 0 ] , " a n g l e 3 , angleA =0 , angleB =90" )
24 demo_con_style ( a x s [ 0 , 1 ] , " a r c 3 , rad =0. " )
25 demo_con_style ( a x s [ 1 , 1 ] , " a r c 3 , rad =0.3 " )
26 demo_con_style ( a x s [ 2 , 1 ] , " a r c 3 , rad =−0.3" )
27 demo_con_style ( a x s [ 0 , 2 ] , " a n g l e , angleA =−90, angleB =180 , rad=0" )
28 demo_con_style ( a x s [ 1 , 2 ] , " a n g l e , angleA =−90, angleB =180 , rad=5" )
29 demo_con_style ( a x s [ 2 , 2 ] , " a n g l e , angleA =−90, angleB =10 , rad=5" )
30 demo_con_style ( a x s [ 0 , 3 ] , " arc , angleA =−90, angleB =0 ,armA=30 ,armB=30 , rad=0" )
31 demo_con_style ( a x s [ 1 , 3 ] , " arc , angleA =−90, angleB =0 ,armA=30 ,armB=30 , rad=5" )
32 demo_con_style ( a x s [ 2 , 3 ] , " arc , angleA =−90, angleB =0 ,armA=0 ,armB=40 , rad=0" )
33 demo_con_style ( a x s [ 0 , 4 ] , " bar , f r a c t i o n =0.3 " )
34 demo_con_style ( a x s [ 1 , 4 ] , " bar , f r a c t i o n =−0.3" )
35 demo_con_style ( a x s [ 2 , 4 ] , " bar , a n g l e =180 , f r a c t i o n =−0.2" )
36

37 f o r ax i n a x s . f l a t :

Matplotlib Mini Guide Page 11


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

38 ax . s e t ( x l i m =(0 , 1 ) , y l i m =(0 , 1 ) , x t i c k s = [ ] , y t i c k s = [ ] , a s p e c t =1)


39 f i g . t i g h t _ l a y o u t ( pad =0.2)
40

41 p l t . show ( )

7 Axes
1 #! / u s r / b i n / env python3
2 # −∗− c o d i n g : u t f −8 −∗−
3 """
4 C r e a t e d on Tue May 5 1 0 : 2 8 : 5 0 2020
5

6 @author : kyphuc
7 """
8

9 #! / u s r / b i n / env python3
10 # −∗− c o d i n g : u t f −8 −∗−
11 """
12 C r e a t e d on Tue May 5 1 0 : 2 8 : 5 0 2020
13

14 @author : kyphuc
15 """
16

17 im po rt s y s
18 im po rt pandas a s pd
19 from PyQt5 . QtWidgets im por t ∗
20 from m a t p l o t l i b . backends . backend_qt5agg imp ort FigureCanvasQTAgg a s FigureCanvas
21 from m a t p l o t l i b . backends . backend_qt5agg imp ort NavigationToolbar2QT a s N a v i g a t i o n T o o l b a r
22 im po rt m a t p l o t l i b . p y p l o t a s p l t
23 im po rt m a t p l o t l i b . p a t c h e s a s p a t c h e s
24 im po rt random
25

26 c l a s s F i g u r e ( QWidget ) :
27 d e f __init__ ( s e l f , ∗ ∗ kwargs ) :
28 s u p e r ( ) . __init__ ( )
29 s e l f . i t e m s=kwargs [ ’ i t e m s ’ ]
30

31 s e l f . _layout = QGridLayout ( )
32 s e l f . setWindowTitle ( ’ Figure ’ )
33

34 self . add_figure ( 1 , 0 , 9 , 1 0 )
35 self . add_toolbar ( 0 , 0 , 1 , 1 0 )
36 self . add_button ( ’ b t n C l o s e ’ , ’ C l o s e ’ , 1 0 , 9 , 1 , 1 , s e l f . f c n _ C l o s e )
37 self . add_button ( ’ b t n P l o t ’ , ’ P l o t ’ , 1 0 , 8 , 1 , 1 , s e l f . f c n _ P l o t )
38

39

40 self . add_label ( ’ Xlabel ’ , ’ Xlabel ’ ,1 ,11 ,1 ,1)


41 self . add_label ( ’ Ylabel ’ , ’ Ylabel ’ ,2 ,11 ,1 ,1)
42 self . add_label ( ’ Xlim ’ , ’ Xlim ’ , 3 , 1 1 , 1 , 1 )
43 self . add_label ( ’ Ylim ’ , ’ Ylim ’ , 4 , 1 1 , 1 , 1 )
44 self . add_label ( ’ Grid ’ , ’ Grid ’ , 5 , 1 1 , 1 , 1 )
45 self . add_label ( ’ Title ’ , ’ Title ’ ,10 ,0 ,1 ,1)
46

47 self . add_lineEdit ( ’ edtXlabel ’ ,1 ,12 ,1 ,1)


48 self . add_lineEdit ( ’ edtYlabel ’ ,2 ,12 ,1 ,1)
49 self . add_lineEdit ( ’ edtXlim ’ , 3 , 1 2 , 1 , 1 )
50 self . add_lineEdit ( ’ edtYlim ’ , 4 , 1 2 , 1 , 1 )
51 self . add_lineEdit ( ’ edtTitle ’ ,10 ,1 ,1 ,7)
52 self . add_combobox ( ’ cmbGrid ’ , 5 , 1 2 , 1 , 1 )

Matplotlib Mini Guide Page 12


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

53 s e l f . s e t L a y o u t ( s e l f . _layout )
54

55

56 s e l f . r e s i z e (1200 ,600)
57 s e l f . show ( )
58

59 d e f add_toolbar ( s e l f , row , c o l , row_span , col_span ) :


60 s e l f . t o o l b a r = N a v i g a t i o n T o o l b a r ( s e l f . canvas , s e l f )
61 s e l f . _layout . addWidget ( s e l f . t o o l b a r , row , c o l , row_span , col_span )
62

63 d e f a d d _ f i g u r e ( s e l f , row , c o l , row_span , col_span ) :


64 """ C r e a t e f i g u r e c a n v a s and add them t o Window"""
65 s e l f . figure = plt . figure ()
66 s e l f . c a n v a s = FigureCanvas ( s e l f . f i g u r e )
67 s e l f . _layout . addWidget ( s e l f . canvas , row , c o l , row_span , col_span )
68

69 d e f a d d _ l a b e l ( s e l f , component , t e x t , row , c o l , row_span , col_span ) :


70 """ C r e a t e and add l a b e l t o Window"""
71 s e t a t t r ( s e l f , component , QLabel ( t e x t ) )
72 l a b e l=g e t a t t r ( s e l f , component )
73 l a b e l . setStyleSheet ( ’ c o l o r : blue ’ )
74 s e l f . _layout . addWidget ( l a b e l , row , c o l , row_span , col_span )
75

76 d e f add_button ( s e l f , component , t e x t , row , c o l , row_span , col_span , f u n c ) :


77 """ C r e a t e and add bu tt on t o Window"""
78 s e t a t t r ( s e l f , component , QPushButton ( t e x t ) )
79 b ut to n=g e t a t t r ( s e l f , component )
80 b ut to n . c l i c k e d . c o n n e c t ( f u n c )
81 s e l f . _layout . addWidget ( button , row , c o l , row_span , col_span )
82

83 d e f a d d _ l i n e E d i t ( s e l f , component , row , c o l , row_span , col_span ) :


84 """ C r e a t e and add l a b e l t o Window"""
85 s e t a t t r ( s e l f , component , QLineEdit ( ) )
86 l i n e E d i t=g e t a t t r ( s e l f , component )
87 l i n e E d i t . se tFi xe dWi dt h ( col_span ∗ 1 0 0 )
88 s e l f . _layout . addWidget ( l i n e E d i t , row , c o l , row_span , col_span )
89

90 d e f add_combobox ( s e l f , component , row , c o l , row_span , col_span ) :


91 s e t a t t r ( s e l f , component , QComboBox ( ) )
92 combobox=g e t a t t r ( s e l f , component )
93 combobox . addItem ( " o f f " )
94 combobox . addItem ( " on " )
95 s e l f . _layout . addWidget ( combobox , row , c o l , row_span , col_span )
96

97 def fcn_Close ( s e l f ) :
98 plt . close ()
99 s e l f . close ()
100 QApplication . quit ( )
101

102 def fcn_Plot ( s e l f ) :


103 ax= s e l f . f c n _ P l o t S e t t i n g ( )
104 c o l o r l i s t =[ ’ r e d ’ , ’ g r e e n ’ , ’ b l u e ’ , ’ y e l l o w ’ , ’ c ’ , ’m ’ , ’ k ’ ]
105 f o r item i n s e l f . i t e m s :
106 #c o l o r I n d=random . r a n d i n t ( 0 , l e n ( c o l o r l i s t ) −1)
107 c o l o r I n d=item . machine%l e n ( c o l o r l i s t )
108 p=p a t c h e s . R e c t a n g l e ( ( item . b e g i n , item . machine −1) , item . f i n i s h −item . b e g i n , 1 , c o l o r=
c o l o r l i s t [ colorInd ] )
109 ax . add_patch ( p )

Matplotlib Mini Guide Page 13


Ho Chi Minh City International University Matplotlib Mini Guide
Industrial Systems Engineering Department Lecturer: Phan Nguyen Ky Phuc

110 ax . t e x t ( ( item . b e g i n+item . f i n i s h ) / 2 , item . machine − 0 . 5 , "J"+s t r ( item . i d ) , f o n t s i z e= ’ x


−s m a l l ’ , r o t a t i o n= ’ v e r t i c a l ’ , c o l o r= ’ r e d ’ , v e r t i c a l a l i g n m e n t= ’ c e n t e r ’ , h o r i z o n t a l a l i g n m e n t= ’
center ’ )
111 s e l f . c a n v a s . draw ( )
112

113 def fcn_PlotSetting ( s e l f ) :


114 """ Read S e t t i n g P l o t """
115 s e l f . figure . clear ()
116 ax = s e l f . f i g u r e . add_subplot ( 1 1 1 )
117 i f s e l f . edtXlabel . text () :
118 ax . s e t _ x l a b e l ( s e l f . e d t X l a b e l . t e x t ( ) )
119 else :
120 ax . s e t _ x l a b e l ( "X Value " )
121

122 if s e l f . edtYlabel . text () :


123 ax . s e t _ y l a b e l ( s e l f . e d t Y l a b e l . t e x t ( ) )
124 else :
125 ax . s e t _ y l a b e l ( "Y Value " )
126 i f s e l f . cmbGrid . c u r r e n t T e x t ( )==" on " :
127 ax . g r i d ( True )
128 else :
129 ax . g r i d ( F a l s e )
130 i f s e l f . edtXlim . t e x t ( ) :
131 x r a n g e =[ f l o a t ( x ) f o r x i n s e l f . edtXlim . t e x t ( ) . s p l i t ( " , " ) ]
132 ax . s e t _ x l i m ( [ min ( x r a n g e ) ,max( x r a n g e ) ] )
133 i f s e l f . edtYlim . t e x t ( ) :
134 y r a n g e =[ f l o a t ( y ) f o r y i n s e l f . edtYlim . t e x t ( ) . s p l i t ( " , " ) ]
135 ax . s e t _ y l i m ( [ min ( y r a n g e ) ,max( y r a n g e ) ] )
136 i f s e l f . edtTitle . text () :
137 ax . s e t _ t i t l e ( s e l f . e d t T i t l e . t e x t ( ) )
138 r e t u r n ax
139 c l a s s Item ( o b j e c t ) :
140 d e f __init__ ( s e l f , p a r e n t=None , ∗ ∗ kwargs ) :
141 s u p e r ( ) . __init__ ( )
142 s e l f . i d=kwargs [ ’ i d ’ ]
143 s e l f . b e g i n=kwargs [ ’ b e g i n ’ ]
144 s e l f . f i n i s h=kwargs [ ’ f i n i s h ’ ]
145 s e l f . machine=kwargs [ ’ machine ’ ]
146

147 d e f main ( ) :
148 itemList =[]
149 item1=Item ( i d =1 , b e g i n =0 , f i n i s h =1 , machine =1)
150 item2=Item ( i d =2 , b e g i n =3 , f i n i s h =4 , machine =2)
151 item3=Item ( i d =3 , b e g i n =5 , f i n i s h =8 , machine =2)
152 item4=Item ( i d =4 , b e g i n =10 , f i n i s h =15 , machine =3)
153 item5=Item ( i d =5 , b e g i n =16 , f i n i s h =17 , machine =4)
154 i t e m L i s t =[ item1 , item2 , item3 , item4 , item5 ]
155

156 app = Q A p p l i c a t i o n ( s y s . a r g v )
157 s c r e e n = F i g u r e ( i t e m s=i t e m L i s t )
158 s c r e e n . show ( )
159 s y s . e x i t ( app . exec_ ( ) )
160

161 i f __name__ == ’__main__ ’ :


162 main ( )

Matplotlib Mini Guide Page 14


Matplotlib is partcipating in GSOC 2020! See discourse for details. Apply by March 31, 2020.

John Hunter Excellence in Plotting Contest 2020 submissions are open! Entries are due June 1, 2020.

Version 3.2.1
Fork me on GitHub

Installa on Documenta on Examples Tutorials Contribu ng


home | contents » API Overview » previous | next | modules | index

Table of Contents
matplotlib.axes matplotlib.axes
Table of Contents The Axes class
Subplots
The Axes class Plotting

Subplots Basic
Spans
Plotting Spectral
Basic Statistics
Spans Binned
Spectral Contours
Array
Statistics
Unstructured Triangles
Binned Text and Annotations
Contours Fields
Array Clearing
Unstructured Triangles Appearance
Text and Annotations Property cycle
Fields Axis / limits
Axis Limits and direction
Clearing
Axis Labels, title, and
Appearance legend
Axis scales
Property cycle Autoscaling and margins
Aspect ratio
Axis / limits
Ticks and tick labels
Axis Limits and direction
Units
Axis Labels, title, and legend
Adding Artists
Axis scales
Twinning
Autoscaling and margins Axes Position
Aspect ratio Async/Event based
Ticks and tick labels Interactive
/
Units Children
Drawing
Adding Artists Bulk property manipulation
General Artist Properties
Twinning
Artist Methods
Axes Position Projection
Other
Async/Event based Inheritance
Interactive
Related Topics
Children
Documentation overview
Drawing API Overview
Bulk property manipulation Previous:
matplotlib.artist.ArtistInspector
General Artist Properties Next:
Artist Methods matplotlib.axes.SubplotBase

Projection
Show Page Source
Other

Inheritance

The Axes class


class matplotlib.axes.Axes(fig, rect, facecolor=None, frameon=True,
sharex=None, sharey=None, label='', xscale=None, yscale=None,
**kwargs) [source]

Bases: matplotlib.axes._base._AxesBase

The Axes contains most of the figure elements: Axis, Tick, Line2D, Text,
Polygon, etc., and sets the coordinate system.

The Axes instance supports callbacks through a callbacks attribute which is


a CallbackRegistry instance. 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.

Attributes: dataLim : Bbox

The bounding box enclosing all data


displayed in the Axes.

viewLim : Bbox

The view limits in data coordinates.

Build an axes in a figure.


/
Parameters: fig : Figure

The axes is build in the Figure fig.

rect : [left, bottom, width, height]

The axes is build in the rectangle rect. rect is in


Figure coordinates.

sharex, sharey : Axes, optional

The x or y axis is shared with the x or y axis in the


input Axes.

frameon : bool, optional

True means that the axes frame is visible.

**kwargs

Other optional keyword arguments:

Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which
takes a (m, n, 3) float
array and a dpi value,
and returns a (m, n, 3)
array
alpha float or None
anchor 2-tuple of floats or {'C',
'SW', 'S', 'SE', ...}
animated bool
aspect {'auto', 'equal'} or num
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes,
Renderer], Bbox]
axisbelow bool or 'line'
clip_box Bbox
clip_on bool
clip_path Patch or (Path,
Transform) or None
/
Property Description
contains callable
facecolor color
fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or
callable
position [left, bottom, width,
height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool or None
sketch_params (scale: float, length:
float, randomness:
float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top:
float)
xmargin float greater than -0.5
xscale {"linear", "log",
"symlog", "logit", ...}
xticklabels List[str]
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top:
float)
/
Property Description
ymargin float greater than -0.5
yscale {"linear", "log",
"symlog", "logit", ...}
yticklabels List[str]
yticks unknown
zorder float

Returns: axes : Axes

The new Axes object.

Subplots
SubplotBase Base class for subplots, which are Axes instances with additional
methods to facilitate generating and manipulating a set of Axes
within a figure.

subplot_class_factory This makes a new class that inherits from SubplotBase and the
given axes_class (which is assumed to be a subclass of axes.Axes).

Plo ng
Basic
Axes.plot Plot y versus x as lines and/or markers.

Axes.errorbar Plot y versus x as lines and/or markers with attached errorbars.

Axes.scatter A scatter plot of y vs.

Axes.plot_date Plot data that contains dates.

Axes.step Make a step plot.

Axes.loglog Make a plot with log scaling on both the x and y axis.

Axes.semilogx Make a plot with log scaling on the x axis.

Axes.semilogy Make a plot with log scaling on the y axis.

Axes.fill_between Fill the area between two horizontal curves.

Axes.fill_betweenx Fill the area between two vertical curves.

Axes.bar Make a bar plot.

Axes.barh Make a horizontal bar plot.

Axes.stem Create a stem plot.

Axes.eventplot Plot identical parallel lines at the given positions.

Axes.pie Plot a pie chart.


/
Axes.stackplot Draw a stacked area plot.

Axes.broken_barh Plot a horizontal sequence of rectangles.

Axes.vlines Plot vertical lines.

Axes.hlines Plot horizontal lines at each y from xmin to xmax.

Axes.fill Plot filled polygons.

Spans
Axes.axhline Add a horizontal line across the axis.

Axes.axhspan Add a horizontal span (rectangle) across the axis.

Axes.axvline Add a vertical line across the axes.

Axes.axvspan Add a vertical span (rectangle) across the axes.

Spectral
Axes.acorr Plot the autocorrelation of x.

Axes.angle_spectrum Plot the angle spectrum.

Axes.cohere Plot the coherence between x and y.

Axes.csd Plot the cross-spectral density.

Axes.magnitude_spectrum Plot the magnitude spectrum.

Axes.phase_spectrum Plot the phase spectrum.

Axes.psd Plot the power spectral density.

Axes.specgram Plot a spectrogram.

Axes.xcorr Plot the cross correlation between x and y.

Sta s cs
Axes.boxplot Make a box and whisker plot.

Axes.violinplot Make a violin plot.

Axes.violin Drawing function for violin plots.

Axes.bxp Drawing function for box and whisker plots.

Binned
Axes.hexbin Make a 2D hexagonal binning plot of points x, y.

Axes.hist Plot a histogram.

Axes.hist2d Make a 2D histogram plot.

Contours
Axes.clabel Label a contour plot.

Axes.contour Plot contours.


/
Axes.contourf Plot contours.

Array
Axes.imshow Display data as an image; i.e.

Axes.matshow Plot the values of a 2D matrix or array as color-coded image.

Axes.pcolor Create a pseudocolor plot with a non-regular rectangular grid.

Axes.pcolorfast Create a pseudocolor plot with a non-regular rectangular grid.

Axes.pcolormesh Create a pseudocolor plot with a non-regular rectangular grid.

Axes.spy Plot the sparsity pattern of a 2D array.

Unstructured Triangles
Axes.tripcolor Create a pseudocolor plot of an unstructured triangular grid.

Axes.triplot Draw a unstructured triangular grid as lines and/or markers.

Axes.tricontour Draw contours on an unstructured triangular grid.

Axes.tricontourf Draw contours on an unstructured triangular grid.

Text and Annota ons


Axes.annotate Annotate the point xy with text text.

Axes.text Add text to the axes.

Axes.table Add a table to an Axes.

Axes.arrow Add an arrow to the axes.

Axes.inset_axes Add a child inset axes to this existing axes.

Axes.indicate_inset Add an inset indicator to the axes.

Axes.indicate_inset_zoom Add an inset indicator rectangle to the axes based on the axis
limits for an inset_ax and draw connectors between inset_ax and
the rectangle.

Axes.secondary_xaxis Add a second x-axis to this axes.

Axes.secondary_yaxis Add a second y-axis to this axes.

Fields
Axes.barbs Plot a 2D field of barbs.

Axes.quiver Plot a 2D field of arrows.

Axes.quiverkey Add a key to a quiver plot.

Axes.streamplot Draw streamlines of a vector flow.

Clearing
Axes.cla Clear the current axes.
/
Axes.clear Clear the axes.

Appearance
Axes.axis Convenience method to get or set some axis properties.

Axes.set_axis_off Turn the x- and y-axis off.

Axes.set_axis_on Turn the x- and y-axis on.

Axes.set_frame_on Set whether the axes rectangle patch is drawn.

Axes.get_frame_on Get whether the axes rectangle patch is drawn.

Axes.set_axisbelow Set whether axis ticks and gridlines are above or below most artists.

Axes.get_axisbelow Get whether axis ticks and gridlines are above or below most artists.

Axes.grid Configure the grid lines.

Axes.get_facecolor Get the facecolor of the Axes.

Axes.get_fc Get the facecolor of the Axes.

Axes.set_facecolor Set the facecolor of the Axes.

Axes.set_fc Set the facecolor of the Axes.

Property cycle
Axes.set_prop_cycle Set the property cycle of the Axes.

Axis / limits
Axes.get_xaxis Return the XAxis instance.

Axes.get_yaxis Return the YAxis instance.

Axis Limits and direc on


Axes.invert_xaxis Invert the x-axis.

Axes.xaxis_inverted Return whether the x-axis is inverted.

Axes.invert_yaxis Invert the y-axis.

Axes.yaxis_inverted Return whether the y-axis is inverted.

Axes.set_xlim Set the x-axis view limits.

Axes.get_xlim Return the x-axis view limits.

Axes.set_ylim Set the y-axis view limits.

Axes.get_ylim Return the y-axis view limits.

Axes.update_datalim Extend the dataLim Bbox to include the given points.

Axes.update_datalim_bounds Extend the datalim Bbox to include the given Bbox.

Axes.set_xbound Set the lower and upper numerical bounds of the x-axis.

Axes.get_xbound Return the lower and upper x-axis bounds, in increasing order.

Axes.set_ybound Set the lower and upper numerical bounds of the y-axis. /
Axes.get_ybound Return the lower and upper y-axis bounds, in increasing order.

Axis Labels, tle, and legend


Axes.set_xlabel Set the label for the x-axis.

Axes.get_xlabel Get the xlabel text string.

Axes.set_ylabel Set the label for the y-axis.

Axes.get_ylabel Get the ylabel text string.

Axes.set_title Set a title for the axes.

Axes.get_title Get an axes title.

Axes.legend Place a legend on the axes.

Axes.get_legend Return the Legend instance, or None if no legend is


defined.

Axes.get_legend_handles_labels Return handles and labels for legend

Axis scales
Axes.set_xscale Set the x-axis scale.

Axes.get_xscale Return the x-axis scale as string.

Axes.set_yscale Set the y-axis scale.

Axes.get_yscale Return the y-axis scale as string.

Autoscaling and margins


Axes.use_sticky_edges When autoscaling, whether to obey all Artist.sticky_edges.

Axes.margins Set or retrieve autoscaling margins.

Axes.set_xmargin Set padding of X data limits prior to autoscaling.

Axes.set_ymargin Set padding of Y data limits prior to autoscaling.

Axes.relim Recompute the data limits based on current artists.

Axes.autoscale Autoscale the axis view to the data (toggle).

Axes.autoscale_view Autoscale the view limits using the data limits.

Axes.set_autoscale_on Set whether autoscaling is applied on plot commands

Axes.get_autoscale_on Get whether autoscaling is applied for both axes on plot commands

Axes.set_autoscalex_on Set whether autoscaling for the x-axis is applied on plot commands

Axes.get_autoscalex_on Get whether autoscaling for the x-axis is applied on plot commands

Axes.set_autoscaley_on Set whether autoscaling for the y-axis is applied on plot commands

Axes.get_autoscaley_on Get whether autoscaling for the y-axis is applied on plot commands

Aspect ra o
Axes.apply_aspect Adjust the Axes for a specified data aspect ratio.

/
Axes.set_aspect Set the aspect of the axis scaling, i.e.

Axes.get_aspect

Axes.set_adjustable Define which parameter the Axes will change to achieve a given aspect.

Axes.get_adjustable

Ticks and ck labels


Axes.set_xticks Set the x ticks with list of ticks

Axes.get_xticks Return the x ticks as a list of locations

Axes.set_xticklabels Set the x-tick labels with list of string labels.

Axes.get_xticklabels Get the x tick labels as a list of Text instances.

Axes.get_xmajorticklabels Get the major x tick labels.

Axes.get_xminorticklabels Get the minor x tick labels.

Axes.get_xgridlines Get the x grid lines as a list of Line2D instances.

Axes.get_xticklines Get the x tick lines as a list of Line2D instances.

Axes.xaxis_date Sets up x-axis ticks and labels that treat the x data as dates.

Axes.set_yticks Set the y ticks with list of ticks

Axes.get_yticks Return the y ticks as a list of locations

Axes.set_yticklabels Set the y-tick labels with list of strings labels.

Axes.get_yticklabels Get the y tick labels as a list of Text instances.

Axes.get_ymajorticklabels Get the major y tick labels.

Axes.get_yminorticklabels Get the minor y tick labels.

Axes.get_ygridlines Get the y grid lines as a list of Line2D instances.

Axes.get_yticklines Get the y tick lines as a list of Line2D instances.

Axes.yaxis_date Sets up y-axis ticks and labels that treat the y data as dates.

Axes.minorticks_off Remove minor ticks from the axes.

Axes.minorticks_on Display minor ticks on the axes.

Axes.ticklabel_format Change the ScalarFormatter used by default for linear axes.

Axes.tick_params Change the appearance of ticks, tick labels, and gridlines.

Axes.locator_params Control behavior of major tick locators.

Units
Axes.convert_xunits Convert x using the unit type of the xaxis.

Axes.convert_yunits Convert y using the unit type of the yaxis.

Axes.have_units Return True if units are set on any axis.

Adding Ar sts
Axes.add_artist Add an Artist to the axes, and return the artist.
/
Axes.add_child_axes Add an AxesBase to the axes' children; return the child axes.

Axes.add_collection Add a Collection to the axes' collections; return the collection.

Axes.add_container Add a Container to the axes' containers; return the container.

Axes.add_image Add an AxesImage to the axes' images; return the image.

Axes.add_line Add a Line2D to the axes' lines; return the line.

Axes.add_patch Add a Patch to the axes' patches; return the patch.

Axes.add_table Add a Table to the axes' tables; return the table.

Twinning
Axes.twinx Create a twin Axes sharing the xaxis.

Axes.twiny Create a twin Axes sharing the yaxis.

Axes.get_shared_x_axes Return a reference to the shared axes Grouper object for x axes.

Axes.get_shared_y_axes Return a reference to the shared axes Grouper object for y axes.

Axes Posi on
Axes.get_anchor Get the anchor location.

Axes.set_anchor Define the anchor location.

Axes.get_axes_locator Return the axes_locator.

Axes.set_axes_locator Set the axes locator.

Axes.reset_position Reset the active position to the original position.

Axes.get_position Get a copy of the axes rectangle as a Bbox.

Axes.set_position Set the axes position.

Async/Event based
Axes.stale Whether the artist is 'stale' and needs to be re-drawn for the output to
match the internal state of the artist.

Axes.pchanged Call all of the registered callbacks.

Axes.add_callback Add a callback function that will be called whenever one of the
Artist's properties changes.

Axes.remove_callback Remove a callback based on its observer id.

Interac ve
Axes.can_pan Return True if this axes supports any pan/zoom button
functionality.

Axes.can_zoom Return True if this axes supports the zoom box button functionality.

Axes.get_navigate Get whether the axes responds to navigation commands

Axes.set_navigate Set whether the axes responds to navigation toolbar commands


/
Axes.get_navigate_mode Get the navigation toolbar button status: 'PAN', 'ZOOM', or None

Axes.set_navigate_mode Set the navigation toolbar button status;

Axes.start_pan Called when a pan operation has started.

Axes.drag_pan Called when the mouse moves during a pan operation.

Axes.end_pan Called when a pan operation completes (when the mouse button is
up.)

Axes.format_coord Return a format string formatting the x, y coordinates.

Axes.format_cursor_data Return a string representation of data.

Axes.format_xdata Return x formatted as an x-value.

Axes.format_ydata Return y formatted as an y-value.

Axes.mouseover If this property is set to True, the artist will be queried for custom
context information when the mouse cursor moves over it.

Axes.in_axes Return True if the given mouseevent (in display coords) is in the
Axes

Axes.pick Process a pick event.

Axes.pickable Return whether the artist is pickable.

Axes.get_picker Return the picking behavior of the artist.

Axes.set_picker Define the picking behavior of the artist.

Axes.set_contains Define a custom contains test for the artist.

Axes.get_contains Return the custom contains function of the artist if set, or None.

Axes.contains Test whether the artist contains the mouse event.

Axes.contains_point Return whether point (pair of pixel coordinates) is inside the axes
patch.

Axes.get_cursor_data Return the cursor data for a given event.

Children
Axes.get_children Return a list of the child Artists of this Artist.

Axes.get_images return a list of Axes images contained by the Axes

Axes.get_lines Return a list of lines contained by the Axes

Axes.findobj Find artist objects.

Drawing
Axes.draw Draw everything (plot lines, axes, labels)

Axes.draw_artist This method can only be used after an initial draw which
caches the renderer.

Axes.redraw_in_frame This method can only be used after an initial draw which
caches the renderer.

Axes.get_renderer_cache

Axes.get_rasterization_zorder Return the zorder value below which artists will be


/
rasterized.

Axes.set_rasterization_zorder
Parameters:

Axes.get_window_extent Return the axes bounding box in display space; args and
kwargs are empty.

Axes.get_tightbbox Return the tight bounding box of the axes, including axis
and their decorators (xlabel, title, etc).

Bulk property manipula on


Axes.set A property batch setter.

Axes.update Update this artist's properties from the dictionary props.

Axes.properties Return a dictionary of all the properties of the artist.

Axes.update_from Copy properties from other to self.

General Ar st Proper es
Axes.set_agg_filter Set the agg filter.

Axes.set_alpha Set the alpha value used for blending - not supported on all
backends.

Axes.set_animated Set the artist's animation state.

Axes.set_clip_box Set the artist's clip Bbox.

Axes.set_clip_on Set whether the artist uses clipping.

Axes.set_clip_path Set the artist's clip path.

Axes.set_gid Set the (group) id for the artist.

Axes.set_label Set a label that will be displayed in the legend.

Axes.set_path_effects Set the path effects.

Axes.set_rasterized Force rasterized (bitmap) drawing in vector backend output.

Axes.set_sketch_params Sets the sketch parameters.

Axes.set_snap Set the snapping behavior.

Axes.set_transform Set the artist transform.

Axes.set_url Set the url for the artist.

Axes.set_visible Set the artist's visibility.

Axes.set_zorder Set the zorder for the artist.

Axes.get_agg_filter Return filter function to be used for agg filter.

Axes.get_alpha Return the alpha value used for blending - not supported on all
backends

Axes.get_animated Return the animated state.

Axes.get_clip_box Return the clipbox.

Axes.get_clip_on Return whether the artist uses clipping.

Axes.get_clip_path Return the clip path. /


Axes.get_gid Return the group id.

Axes.get_label Return the label used for this artist in the legend.

Axes.get_path_effects

Axes.get_rasterized Return whether the artist is to be rasterized.

Axes.get_sketch_params Returns the sketch parameters for the artist.

Axes.get_snap Returns the snap setting.

Axes.get_transform Return the Transform instance used by this artist.

Axes.get_url Return the url.

Axes.get_visible Return the visibility.

Axes.get_zorder Return the artist's zorder.

Axes.axes The Axes instance the artist resides in, or None.

Axes.set_figure Set the Figure for this Axes.

Axes.get_figure Return the Figure instance the artist belongs to.

Ar st Methods
Axes.remove Remove the artist from the figure if possible.

Axes.is_transform_set Return whether the Artist has an explicitly set transform.

Projec on
Methods used by Axis that must be overridden for non-rectilinear Axes.

Axes.name

Axes.get_xaxis_transform Get the transformation used for drawing x-axis labels,


ticks and gridlines.

Axes.get_yaxis_transform Get the transformation used for drawing y-axis labels,


ticks and gridlines.

Axes.get_data_ratio Return the aspect ratio of the scaled data.

Axes.get_data_ratio_log [Deprecated] Return the aspect ratio of the raw data in log
scale.

Axes.get_xaxis_text1_transform
Returns:

Axes.get_xaxis_text2_transform
Returns:

Axes.get_yaxis_text1_transform
Returns:

Axes.get_yaxis_text2_transform
Returns:

Other /
Axes.zorder

Axes.get_default_bbox_extra_artists Return a default list of artists that are used


for the bounding box calculation.

Axes.get_transformed_clip_path_and_affine Return the clip path with the non-affine part


of its transformation applied, and the
remaining affine part of its transformation.

Axes.has_data Return True if any artists have been added


to axes.

Inheritance
matplotlib artist Artist matplotlib axes base
© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2018 The Matplotlib
development team.
Last updated on Mar 19, 2020. Created using Sphinx 2.2.2. Doc version v3.2.1-6-g9a2f0578f.

You might also like