2
2
`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
3
3
a MATLAB-like way of plotting.
4
4
5
- pyplot is mainly intended for interactive plots and simple cases of programmatic
6
- plot generation::
5
+ pyplot is mainly intended for interactive plots and simple cases of
6
+ programmatic plot generation::
7
7
8
8
import numpy as np
9
9
import matplotlib.pyplot as plt
64
64
MaxNLocator
65
65
from matplotlib .backends import pylab_setup
66
66
67
+
67
68
## Backend detection ##
69
+
68
70
def _backend_selection ():
69
71
""" If rcParams['backend_fallback'] is true, check to see if the
70
72
current backend is compatible with the current running event
@@ -74,7 +76,7 @@ def _backend_selection():
74
76
if not rcParams ['backend_fallback' ] or backend not in _interactive_bk :
75
77
return
76
78
is_agg_backend = rcParams ['backend' ].endswith ('Agg' )
77
- if 'wx' in sys .modules and not backend in ('WX' , 'WXAgg' ):
79
+ if 'wx' in sys .modules and backend not in ('WX' , 'WXAgg' ):
78
80
import wx
79
81
if wx .App .IsMainLoopRunning ():
80
82
rcParams ['backend' ] = 'wx' + 'Agg' * is_agg_backend
@@ -224,7 +226,8 @@ def switch_backend(newbackend):
224
226
global _backend_mod , new_figure_manager , draw_if_interactive , _show
225
227
matplotlib .use (newbackend , warn = False , force = True )
226
228
from matplotlib .backends import pylab_setup
227
- _backend_mod , new_figure_manager , draw_if_interactive , _show = pylab_setup ()
229
+ _backend_mod , new_figure_manager , draw_if_interactive , _show = \
230
+ pylab_setup ()
228
231
229
232
230
233
def show (* args , ** kw ):
@@ -284,10 +287,8 @@ def pause(interval):
284
287
else :
285
288
time .sleep (interval )
286
289
287
-
288
290
## Any Artist ##
289
291
290
-
291
292
def xkcd (scale = 1 , length = 100 , randomness = 2 ):
292
293
"""
293
294
Turns on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
@@ -360,7 +361,6 @@ def __enter__(self):
360
361
361
362
return dummy_ctx ()
362
363
363
-
364
364
## Figures ##
365
365
366
366
def figure (num = None , # autoincrement if None, else integer from 1-N
@@ -604,10 +604,8 @@ def close(*args):
604
604
else :
605
605
raise TypeError ('close takes 0 or 1 arguments' )
606
606
607
-
608
607
## Axes ##
609
608
610
-
611
609
def axes (arg = None , ** kwargs ):
612
610
"""
613
611
Add an axes to the current figure and make it the current axes.
@@ -683,8 +681,10 @@ def axes(arg=None, **kwargs):
683
681
684
682
def delaxes (ax = None ):
685
683
"""
686
- Remove the given `Axes` *ax* from the current figure. If *ax* is *None*,
687
- the current axes is removed. A KeyError is raised if the axes doesn't exist.
684
+ Remove the given `Axes` *ax* from the current figure.
685
+
686
+ If *ax* is *None*, the current axes is removed. A KeyError is raised if the
687
+ axes doesn't exist.
688
688
"""
689
689
if ax is None :
690
690
ax = gca ()
@@ -736,12 +736,13 @@ def subplot(*args, **kwargs):
736
736
import matplotlib.pyplot as plt
737
737
# plot a line, implicitly creating a subplot(111)
738
738
plt.plot([1,2,3])
739
- # now create a subplot which represents the top plot of a grid
740
- # with 2 rows and 1 column. Since this subplot will overlap the
741
- # first, the plot (and its axes) previously created, will be removed
739
+ # now create a subplot which represents the top plot of a grid with
740
+ # 2 rows and 1 column. Since this subplot will overlap the first, the
741
+ # plot (and its axes) previously created, will be removed
742
742
plt.subplot(211)
743
743
plt.plot(range(12))
744
- plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
744
+ # create a second subplot with yellow background
745
+ plt.subplot(212, facecolor='y')
745
746
746
747
If you do not want this behavior, use the
747
748
:meth:`~matplotlib.figure.Figure.add_subplot` method or the
@@ -778,28 +779,26 @@ def subplot(*args, **kwargs):
778
779
779
780
"""
780
781
# if subplot called without arguments, create subplot(1,1,1)
781
- if len (args )== 0 :
782
- args = (1 ,1 , 1 )
782
+ if len (args ) == 0 :
783
+ args = (1 , 1 , 1 )
783
784
784
785
# This check was added because it is very easy to type
785
786
# subplot(1, 2, False) when subplots(1, 2, False) was intended
786
787
# (sharex=False, that is). In most cases, no error will
787
788
# ever occur, but mysterious behavior can result because what was
788
789
# intended to be the sharex argument is instead treated as a
789
790
# subplot index for subplot()
790
- if len (args ) >= 3 and isinstance (args [2 ], bool ) :
791
- warnings .warn ("The subplot index argument to subplot() appears"
792
- " to be a boolean. Did you intend to use subplots()?" )
791
+ if len (args ) >= 3 and isinstance (args [2 ], bool ):
792
+ warnings .warn ("The subplot index argument to subplot() appears "
793
+ "to be a boolean. Did you intend to use subplots()?" )
793
794
794
795
fig = gcf ()
795
796
a = fig .add_subplot (* args , ** kwargs )
796
797
bbox = a .bbox
797
- byebye = []
798
- for other in fig .axes :
799
- if other == a : continue
800
- if bbox .fully_overlaps (other .bbox ):
801
- byebye .append (other )
802
- for ax in byebye : delaxes (ax )
798
+ byebye = [other for other in fig .axes
799
+ if other is not a and bbox .fully_overlaps (other .bbox )]
800
+ for ax in byebye :
801
+ delaxes (ax )
803
802
804
803
return a
805
804
@@ -1021,24 +1020,28 @@ def subplot_tool(targetfig=None):
1021
1020
"""
1022
1021
Launch a subplot tool window for a figure.
1023
1022
1024
- A :class:`matplotlib.widgets.SubplotTool` instance is returned.
1023
+ Returns
1024
+ -------
1025
+ `matplotlib.widgets.SubplotTool`
1025
1026
"""
1026
- tbar = rcParams [' toolbar' ] # turn off the navigation toolbar for the toolfig
1027
- rcParams [' toolbar' ] = ' None'
1027
+ tbar = rcParams [" toolbar" ] # Turn off the nav toolbar for the toolfig.
1028
+ rcParams [" toolbar" ] = " None"
1028
1029
if targetfig is None :
1029
1030
manager = get_current_fig_manager ()
1030
1031
targetfig = manager .canvas .figure
1031
1032
else :
1032
- # find the manager for this figure
1033
+ # Find the manager for this figure.
1033
1034
for manager in _pylab_helpers .Gcf ._activeQue :
1034
- if manager .canvas .figure == targetfig : break
1035
- else : raise RuntimeError ('Could not find manager for targetfig' )
1035
+ if manager .canvas .figure == targetfig :
1036
+ break
1037
+ else :
1038
+ raise RuntimeError ("Could not find manager for targetfig" )
1036
1039
1037
- toolfig = figure (figsize = (6 ,3 ))
1040
+ toolfig = figure (figsize = (6 , 3 ))
1038
1041
toolfig .subplots_adjust (top = 0.9 )
1039
- ret = SubplotTool (targetfig , toolfig )
1040
- rcParams [' toolbar' ] = tbar
1041
- _pylab_helpers .Gcf .set_active (manager ) # restore the current figure
1042
+ ret = SubplotTool (targetfig , toolfig )
1043
+ rcParams [" toolbar" ] = tbar
1044
+ _pylab_helpers .Gcf .set_active (manager ) # Restore the current figure.
1042
1045
return ret
1043
1046
1044
1047
@@ -1057,10 +1060,8 @@ def box(on=None):
1057
1060
on = not ax .get_frame_on ()
1058
1061
ax .set_frame_on (on )
1059
1062
1060
-
1061
1063
## Axis ##
1062
1064
1063
-
1064
1065
def xlim (* args , ** kwargs ):
1065
1066
"""
1066
1067
Get or set the *x* limits of the current axes.
@@ -1225,15 +1226,14 @@ def rgrids(*args, **kwargs):
1225
1226
"""
1226
1227
ax = gca ()
1227
1228
if not isinstance (ax , PolarAxes ):
1228
- raise RuntimeError (' rgrids only defined for polar axes' )
1229
- if len (args )== 0 :
1229
+ raise RuntimeError (" rgrids only defined for polar axes" )
1230
+ if len (args ) == 0 :
1230
1231
lines = ax .yaxis .get_gridlines ()
1231
1232
labels = ax .yaxis .get_ticklabels ()
1232
1233
else :
1233
1234
lines , labels = ax .set_rgrids (* args , ** kwargs )
1234
-
1235
- return ( silent_list ('Line2D rgridline' , lines ),
1236
- silent_list ('Text rgridlabel' , labels ) )
1235
+ return (silent_list ("Line2D rgridline" , lines ),
1236
+ silent_list ("Text rgridlabel" , labels ))
1237
1237
1238
1238
1239
1239
def thetagrids (* args , ** kwargs ):
@@ -1271,31 +1271,27 @@ def thetagrids(*args, **kwargs):
1271
1271
1272
1272
- *labels* are :class:`~matplotlib.text.Text` instances.
1273
1273
1274
- Note that on input, the *labels* argument is a list of strings,
1275
- and on output it is a list of :class:`~matplotlib.text.Text`
1276
- instances.
1274
+ Note that on input, the *labels* argument is a list of strings, and on
1275
+ output it is a list of :class:`~matplotlib.text.Text` instances.
1277
1276
1278
1277
Examples::
1279
1278
1280
1279
# set the locations of the radial gridlines and labels
1281
- lines, labels = thetagrids( range(45,360,90) )
1280
+ lines, labels = thetagrids(range(45, 360, 90))
1282
1281
1283
1282
# set the locations and labels of the radial gridlines and labels
1284
- lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )
1283
+ lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
1285
1284
"""
1286
1285
ax = gca ()
1287
1286
if not isinstance (ax , PolarAxes ):
1288
- raise RuntimeError (' rgrids only defined for polar axes' )
1289
- if len (args )== 0 :
1287
+ raise RuntimeError (" rgrids only defined for polar axes" )
1288
+ if len (args ) == 0 :
1290
1289
lines = ax .xaxis .get_ticklines ()
1291
1290
labels = ax .xaxis .get_ticklabels ()
1292
1291
else :
1293
1292
lines , labels = ax .set_thetagrids (* args , ** kwargs )
1294
-
1295
- return (silent_list ('Line2D thetagridline' , lines ),
1296
- silent_list ('Text thetagridlabel' , labels )
1297
- )
1298
-
1293
+ return (silent_list ("Line2D thetagridline" , lines ),
1294
+ silent_list ("Text thetagridlabel" , labels ))
1299
1295
1300
1296
## Plotting Info ##
1301
1297
@@ -1362,16 +1358,15 @@ def colors():
1362
1358
Here is an example that creates a pale turquoise title::
1363
1359
1364
1360
title('Is this the best color?', color='#afeeee')
1365
-
1366
1361
"""
1367
- pass
1368
1362
1369
1363
1370
1364
def colormaps ():
1371
1365
"""
1372
1366
Matplotlib provides a number of colormaps, and others can be added using
1373
- :func:`~matplotlib.cm.register_cmap`. This function documents the built-in
1374
- colormaps, and will also return a list of all registered colormaps if called.
1367
+ `~matplotlib.cm.register_cmap`. This function documents the built-in
1368
+ colormaps, and will also return a list of all registered colormaps if
1369
+ called.
1375
1370
1376
1371
You can set the colormap for an image, pcolor, scatter, etc,
1377
1372
using a keyword argument::
@@ -1628,7 +1623,7 @@ def pad(s, l):
1628
1623
exclude = {"colormaps" , "colors" , "connect" , "disconnect" ,
1629
1624
"get_current_fig_manager" , "ginput" , "plotting" ,
1630
1625
"waitforbuttonpress" }
1631
- commands = sorted (set (__all__ ) - exclude - set (colormaps ()))
1626
+ commands = sorted (set (__all__ ) - exclude - set (colormaps ()))
1632
1627
1633
1628
first_sentence = re .compile (r"(?:\s*).+?\.(?:\s+|$)" , flags = re .DOTALL )
1634
1629
@@ -1676,9 +1671,7 @@ def colorbar(mappable=None, cax=None, ax=None, **kw):
1676
1671
'with contourf).' )
1677
1672
if ax is None :
1678
1673
ax = gca ()
1679
-
1680
- ret = gcf ().colorbar (mappable , cax = cax , ax = ax , ** kw )
1681
- return ret
1674
+ return gcf ().colorbar (mappable , cax = cax , ax = ax , ** kw )
1682
1675
colorbar .__doc__ = matplotlib .colorbar .colorbar_doc
1683
1676
1684
1677
@@ -1743,7 +1736,6 @@ def matshow(A, fignum=None, **kw):
1743
1736
kwarg to "lower" if you want the first row in the array to be
1744
1737
at the bottom instead of the top.
1745
1738
1746
-
1747
1739
*fignum*: [ None | integer | False ]
1748
1740
By default, :func:`matshow` creates a new figure window with
1749
1741
automatic numbering. If *fignum* is given as an integer, the
@@ -1758,9 +1750,9 @@ def matshow(A, fignum=None, **kw):
1758
1750
if fignum is False or fignum is 0 :
1759
1751
ax = gca ()
1760
1752
else :
1761
- # Extract actual aspect ratio of array and make appropriately sized figure
1753
+ # Extract array's actual aspect ratio; make appropriately sized figure.
1762
1754
fig = figure (fignum , figsize = figaspect (A ))
1763
- ax = fig .add_axes ([0.15 , 0.09 , 0.775 , 0.775 ])
1755
+ ax = fig .add_axes ([0.15 , 0.09 , 0.775 , 0.775 ])
1764
1756
1765
1757
im = ax .matshow (A , ** kw )
1766
1758
sci (im )
0 commit comments