FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/pyplot.py at mplot3d/asanyarray · WeatherGod/matplotlib · GitHub
WeatherGod
matplotlib
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
pyplot.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3036 lines (2413 loc) · 88.4 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
pyplot.py
Copy path
File metadata and controls
3036 lines (2413 loc) · 88.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Provides a MATLAB-like plotting framework.
:mod:`~matplotlib.pylab` combines pyplot with numpy into a single namespace.
This is convenient for interactive work, but for programming it
is recommended that the namespaces be kept separate, e.g.::
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
"""
import
sys
import
matplotlib
from
matplotlib
import
_pylab_helpers
,
interactive
from
matplotlib
.
cbook
import
dedent
,
silent_list
,
is_string_like
,
is_numlike
from
matplotlib
import
docstring
from
matplotlib
.
figure
import
Figure
,
figaspect
from
matplotlib
.
backend_bases
import
FigureCanvasBase
from
matplotlib
.
image
import
imread
as
_imread
from
matplotlib
.
image
import
imsave
as
_imsave
from
matplotlib
import
rcParams
,
rcParamsDefault
,
get_backend
from
matplotlib
.
rcsetup
import
interactive_bk
as
_interactive_bk
from
matplotlib
.
artist
import
getp
,
get
,
Artist
from
matplotlib
.
artist
import
setp
as
_setp
from
matplotlib
.
axes
import
Axes
,
Subplot
,
_string_to_bool
from
matplotlib
.
projections
import
PolarAxes
from
matplotlib
import
mlab
# for csv2rec, detrend_none, window_hanning
from
matplotlib
.
scale
import
get_scale_docs
,
get_scale_names
from
matplotlib
import
cm
from
matplotlib
.
cm
import
get_cmap
,
register_cmap
import
numpy
as
np
# We may not need the following imports here:
from
matplotlib
.
colors
import
Normalize
,
normalize
# latter for backwards compat.
from
matplotlib
.
lines
import
Line2D
from
matplotlib
.
text
import
Text
,
Annotation
from
matplotlib
.
patches
import
Polygon
,
Rectangle
,
Circle
,
Arrow
from
matplotlib
.
widgets
import
SubplotTool
,
Button
,
Slider
,
Widget
from
ticker
import
TickHelper
,
Formatter
,
FixedFormatter
,
NullFormatter
,\
FuncFormatter
,
FormatStrFormatter
,
ScalarFormatter
,\
LogFormatter
,
LogFormatterExponent
,
LogFormatterMathtext
,\
Locator
,
IndexLocator
,
FixedLocator
,
NullLocator
,\
LinearLocator
,
LogLocator
,
AutoLocator
,
MultipleLocator
,\
MaxNLocator
## Backend detection ##
def
_backend_selection
():
""" If rcParams['backend_fallback'] is true, check to see if the
current backend is compatible with the current running event
loop, and if not switches to a compatible one.
"""
backend
=
rcParams
[
'backend'
]
if
not
rcParams
[
'backend_fallback'
]
or
\
backend
not
in
_interactive_bk
:
return
is_agg_backend
=
rcParams
[
'backend'
].
endswith
(
'Agg'
)
if
'wx'
in
sys
.
modules
and
not
backend
in
(
'WX'
,
'WXAgg'
):
import
wx
if
wx
.
App
.
IsMainLoopRunning
():
rcParams
[
'backend'
]
=
'wx'
+
'Agg'
*
is_agg_backend
elif
'qt'
in
sys
.
modules
and
not
backend
==
'QtAgg'
:
import
qt
if
not
qt
.
qApp
.
startingUp
():
# The mainloop is running.
rcParams
[
'backend'
]
=
'qtAgg'
elif
'PyQt4.QtCore'
in
sys
.
modules
and
not
backend
==
'Qt4Agg'
:
import
PyQt4
.
QtGui
if
not
PyQt4
.
QtGui
.
qApp
.
startingUp
():
# The mainloop is running.
rcParams
[
'backend'
]
=
'qt4Agg'
elif
'gtk'
in
sys
.
modules
and
not
backend
in
(
'GTK'
,
'GTKAgg'
,
'GTKCairo'
):
import
gobject
if
gobject
.
MainLoop
().
is_running
():
rcParams
[
'backend'
]
=
'gtk'
+
'Agg'
*
is_agg_backend
elif
'Tkinter'
in
sys
.
modules
and
not
backend
==
'TkAgg'
:
#import Tkinter
pass
#what if anything do we need to do for tkinter?
_backend_selection
()
## Global ##
from
matplotlib
.
backends
import
pylab_setup
new_figure_manager
,
draw_if_interactive
,
_show
=
pylab_setup
()
@
docstring
.
copy_dedent
(
Artist
.
findobj
)
def
findobj
(
o
=
None
,
match
=
None
):
if
o
is
None
:
o
=
gcf
()
return
o
.
findobj
(
match
)
def
switch_backend
(
newbackend
):
"""
Switch the default backend to newbackend. This feature is
**experimental**, and is only expected to work switching to an
image backend. Eg, if you have a bunch of PostScript scripts that
you want to run from an interactive ipython session, you may want
to switch to the PS backend before running them to avoid having a
bunch of GUI windows popup. If you try to interactively switch
from one GUI backend to another, you will explode.
Calling this command will close all open windows.
"""
close
(
'all'
)
global
new_figure_manager
,
draw_if_interactive
,
_show
matplotlib
.
use
(
newbackend
,
warn
=
False
)
reload
(
matplotlib
.
backends
)
from
matplotlib
.
backends
import
pylab_setup
new_figure_manager
,
draw_if_interactive
,
_show
=
pylab_setup
()
def
show
():
"""
In non-interactive mode, display all figures and block until
the figures have been closed; in interactive mode it has no
effect unless figures were created prior to a change from
non-interactive to interactive mode (not recommended). In
that case it displays the figures but does not block.
"""
global
_show
_show
()
def
isinteractive
():
"""
Return *True* if matplotlib is in interactive mode, *False* otherwise.
"""
return
matplotlib
.
is_interactive
()
def
ioff
():
'Turn interactive mode off.'
matplotlib
.
interactive
(
False
)
def
ion
():
'Turn interactive mode on.'
matplotlib
.
interactive
(
True
)
def
pause
(
interval
):
"""
Pause for *interval* seconds.
If there is an active figure it will be updated and displayed,
and the gui event loop will run during the pause.
If there is no active figure, or if a non-interactive backend
is in use, this executes time.sleep(interval).
This can be used for crude animation. For more complex
animation, see :mod:`matplotlib.animation`.
"""
backend
=
rcParams
[
'backend'
]
if
backend
in
_interactive_bk
:
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
figManager
is
not
None
:
canvas
=
figManager
.
canvas
canvas
.
draw
()
was_interactive
=
isinteractive
()
if
not
was_interactive
:
ion
()
show
()
canvas
.
start_event_loop
(
interval
)
if
not
was_interactive
:
ioff
()
return
# No on-screen figure is active, so sleep() is all we need.
import
time
time
.
sleep
(
interval
)
@
docstring
.
copy_dedent
(
matplotlib
.
rc
)
def
rc
(
*
args
,
**
kwargs
):
matplotlib
.
rc
(
*
args
,
**
kwargs
)
@
docstring
.
copy_dedent
(
matplotlib
.
rcdefaults
)
def
rcdefaults
():
matplotlib
.
rcdefaults
()
draw_if_interactive
()
# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions:
def
gci
():
"""
Get the current :class:`~matplotlib.cm.ScalarMappable` instance
(image or patch collection), or *None* if no images or patch
collections have been defined. The commands
:func:`~matplotlib.pyplot.imshow` and
:func:`~matplotlib.pyplot.figimage` create
:class:`~matplotlib.image.Image` instances, and the commands
:func:`~matplotlib.pyplot.pcolor` and
:func:`~matplotlib.pyplot.scatter` create
:class:`~matplotlib.collections.Collection` instances.
The current image is an attribute of the current axes, or the
nearest earlier axes in the current figure that contains an
image.
"""
return
gcf
().
_gci
()
def
sci
(
im
):
"""
Set the current image (target of colormap commands like
:func:`~matplotlib.pyplot.jet`, :func:`~matplotlib.pyplot.hot` or
:func:`~matplotlib.pyplot.clim`). The current image is an
attribute of the current axes.
"""
gca
().
_sci
(
im
)
## Any Artist ##
# (getp is simply imported)
@
docstring
.
copy
(
_setp
)
def
setp
(
*
args
,
**
kwargs
):
ret
=
_setp
(
*
args
,
**
kwargs
)
draw_if_interactive
()
return
ret
## Figures ##
def
figure
(
num
=
None
,
# autoincrement if None, else integer from 1-N
figsize
=
None
,
# defaults to rc figure.figsize
dpi
=
None
,
# defaults to rc figure.dpi
facecolor
=
None
,
# defaults to rc figure.facecolor
edgecolor
=
None
,
# defaults to rc figure.edgecolor
frameon
=
True
,
FigureClass
=
Figure
,
**
kwargs
):
"""
call signature::
figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
Create a new figure and return a :class:`matplotlib.figure.Figure`
instance. If *num* = *None*, the figure number will be incremented and
a new figure will be created. The returned figure objects have a
*number* attribute holding this number.
If *num* is an integer, and ``figure(num)`` already exists, make it
active and return a reference to it. If ``figure(num)`` does not exist
it will be created. Numbering starts at 1, MATLAB style::
figure(1)
If you are creating many figures, make sure you explicitly call "close"
on the figures you are not using, because this will enable pylab
to properly clean up the memory.
Optional keyword arguments:
========= =======================================================
Keyword Description
========= =======================================================
figsize width x height in inches; defaults to rc figure.figsize
dpi resolution; defaults to rc figure.dpi
facecolor the background color; defaults to rc figure.facecolor
edgecolor the border color; defaults to rc figure.edgecolor
========= =======================================================
rcParams defines the default values, which can be modified in the
matplotlibrc file
*FigureClass* is a :class:`~matplotlib.figure.Figure` or derived
class that will be passed on to :meth:`new_figure_manager` in the
backends which allows you to hook custom Figure classes into the
pylab interface. Additional kwargs will be passed on to your
figure init function.
"""
if
figsize
is
None
:
figsize
=
rcParams
[
'figure.figsize'
]
if
dpi
is
None
:
dpi
=
rcParams
[
'figure.dpi'
]
if
facecolor
is
None
:
facecolor
=
rcParams
[
'figure.facecolor'
]
if
edgecolor
is
None
:
edgecolor
=
rcParams
[
'figure.edgecolor'
]
if
num
is
None
:
allnums
=
[
f
.
num
for
f
in
_pylab_helpers
.
Gcf
.
get_all_fig_managers
()]
if
allnums
:
num
=
max
(
allnums
)
+
1
else
:
num
=
1
else
:
num
=
int
(
num
)
# crude validation of num argument
figManager
=
_pylab_helpers
.
Gcf
.
get_fig_manager
(
num
)
if
figManager
is
None
:
if
get_backend
().
lower
()
==
'ps'
:
dpi
=
72
figManager
=
new_figure_manager
(
num
,
figsize
=
figsize
,
dpi
=
dpi
,
facecolor
=
facecolor
,
edgecolor
=
edgecolor
,
frameon
=
frameon
,
FigureClass
=
FigureClass
,
**
kwargs
)
# make this figure current on button press event
def
make_active
(
event
):
_pylab_helpers
.
Gcf
.
set_active
(
figManager
)
cid
=
figManager
.
canvas
.
mpl_connect
(
'button_press_event'
,
make_active
)
figManager
.
_cidgcf
=
cid
_pylab_helpers
.
Gcf
.
set_active
(
figManager
)
figManager
.
canvas
.
figure
.
number
=
num
draw_if_interactive
()
return
figManager
.
canvas
.
figure
def
gcf
():
"Return a reference to the current figure."
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
figManager
is
not
None
:
return
figManager
.
canvas
.
figure
else
:
return
figure
()
fignum_exists
=
_pylab_helpers
.
Gcf
.
has_fignum
def
get_fignums
():
"Return a list of existing figure numbers."
fignums
=
_pylab_helpers
.
Gcf
.
figs
.
keys
()
fignums
.
sort
()
return
fignums
def
get_current_fig_manager
():
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
figManager
is
None
:
gcf
()
# creates an active figure as a side effect
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
return
figManager
@
docstring
.
copy_dedent
(
FigureCanvasBase
.
mpl_connect
)
def
connect
(
s
,
func
):
return
get_current_fig_manager
().
canvas
.
mpl_connect
(
s
,
func
)
@
docstring
.
copy_dedent
(
FigureCanvasBase
.
mpl_disconnect
)
def
disconnect
(
cid
):
return
get_current_fig_manager
().
canvas
.
mpl_disconnect
(
cid
)
def
close
(
*
args
):
"""
Close a figure window
``close()`` by itself closes the current figure
``close(num)`` closes figure number *num*
``close(h)`` where *h* is a :class:`Figure` instance, closes that figure
``close('all')`` closes all the figure windows
"""
if
len
(
args
)
==
0
:
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
figManager
is
None
:
return
else
:
_pylab_helpers
.
Gcf
.
destroy
(
figManager
.
num
)
elif
len
(
args
)
==
1
:
arg
=
args
[
0
]
if
arg
==
'all'
:
_pylab_helpers
.
Gcf
.
destroy_all
()
elif
isinstance
(
arg
,
int
):
_pylab_helpers
.
Gcf
.
destroy
(
arg
)
elif
isinstance
(
arg
,
Figure
):
_pylab_helpers
.
Gcf
.
destroy_fig
(
arg
)
else
:
raise
TypeError
(
'Unrecognized argument type %s to close'
%
type
(
arg
))
else
:
raise
TypeError
(
'close takes 0 or 1 arguments'
)
def
clf
():
"""
Clear the current figure
"""
gcf
().
clf
()
draw_if_interactive
()
def
draw
():
"""
Redraw the current figure.
This is used in interactive mode to update a figure that
has been altered using one or more plot object method calls;
it is not needed if figure modification is done entirely
with pyplot functions, if a sequence of modifications ends
with a pyplot function, or if matplotlib is in non-interactive
mode and the sequence of modifications ends with :func:`show` or
:func:`savefig`.
A more object-oriented alternative, given any
:class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
was created using a :module:`~matplotlib.pyplot` function, is::
fig.canvas.draw()
"""
get_current_fig_manager
().
canvas
.
draw
()
@
docstring
.
copy_dedent
(
Figure
.
savefig
)
def
savefig
(
*
args
,
**
kwargs
):
fig
=
gcf
()
return
fig
.
savefig
(
*
args
,
**
kwargs
)
@
docstring
.
copy_dedent
(
Figure
.
ginput
)
def
ginput
(
*
args
,
**
kwargs
):
"""
Blocking call to interact with the figure.
This will wait for *n* clicks from the user and return a list of the
coordinates of each click.
If *timeout* is negative, does not timeout.
"""
return
gcf
().
ginput
(
*
args
,
**
kwargs
)
@
docstring
.
copy_dedent
(
Figure
.
waitforbuttonpress
)
def
waitforbuttonpress
(
*
args
,
**
kwargs
):
"""
Blocking call to interact with the figure.
This will wait for *n* key or mouse clicks from the user and
return a list containing True's for keyboard clicks and False's
for mouse clicks.
If *timeout* is negative, does not timeout.
"""
return
gcf
().
waitforbuttonpress
(
*
args
,
**
kwargs
)
# Putting things in figures
@
docstring
.
copy_dedent
(
Figure
.
text
)
def
figtext
(
*
args
,
**
kwargs
):
ret
=
gcf
().
text
(
*
args
,
**
kwargs
)
draw_if_interactive
()
return
ret
@
docstring
.
copy_dedent
(
Figure
.
suptitle
)
def
suptitle
(
*
args
,
**
kwargs
):
ret
=
gcf
().
suptitle
(
*
args
,
**
kwargs
)
draw_if_interactive
()
return
ret
@
docstring
.
Appender
(
"Addition kwargs: hold = [True|False] overrides default hold state"
,
"
\n
"
)
@
docstring
.
copy_dedent
(
Figure
.
figimage
)
def
figimage
(
*
args
,
**
kwargs
):
# allow callers to override the hold state by passing hold=True|False
ret
=
gcf
().
figimage
(
*
args
,
**
kwargs
)
draw_if_interactive
()
#sci(ret) # JDH figimage should not set current image -- it is not mappable, etc
return
ret
def
figlegend
(
handles
,
labels
,
loc
,
**
kwargs
):
"""
Place a legend in the figure.
*labels*
a sequence of strings
*handles*
a sequence of :class:`~matplotlib.lines.Line2D` or
:class:`~matplotlib.patches.Patch` instances
*loc*
can be a string or an integer specifying the legend
location
A :class:`matplotlib.legend.Legend` instance is returned.
Example::
figlegend( (line1, line2, line3),
('label1', 'label2', 'label3'),
'upper right' )
.. seealso::
:func:`~matplotlib.pyplot.legend`
"""
l
=
gcf
().
legend
(
handles
,
labels
,
loc
,
**
kwargs
)
draw_if_interactive
()
return
l
## Figure and Axes hybrid ##
def
hold
(
b
=
None
):
"""
Set the hold state. If *b* is None (default), toggle the
hold state, else set the hold state to boolean value *b*::
hold() # toggle hold
hold(True) # hold is on
hold(False) # hold is off
When *hold* is *True*, subsequent plot commands will be added to
the current axes. When *hold* is *False*, the current axes and
figure will be cleared on the next plot command.
"""
fig
=
gcf
()
ax
=
fig
.
gca
()
fig
.
hold
(
b
)
ax
.
hold
(
b
)
# b=None toggles the hold state, so let's get get the current hold
# state; but should pyplot hold toggle the rc setting - me thinks
# not
b
=
ax
.
ishold
()
rc
(
'axes'
,
hold
=
b
)
def
ishold
():
"""
Return the hold status of the current axes
"""
return
gca
().
ishold
()
def
over
(
func
,
*
args
,
**
kwargs
):
"""
over calls::
func(*args, **kwargs)
with ``hold(True)`` and then restores the hold state.
"""
h
=
ishold
()
hold
(
True
)
func
(
*
args
,
**
kwargs
)
hold
(
h
)
## Axes ##
def
axes
(
*
args
,
**
kwargs
):
"""
Add an axes at position rect specified by:
- ``axes()`` by itself creates a default full ``subplot(111)`` window axis.
- ``axes(rect, axisbg='w')`` where *rect* = [left, bottom, width,
height] in normalized (0, 1) units. *axisbg* is the background
color for the axis, default white.
- ``axes(h)`` where *h* is an axes instance makes *h* the current
axis. An :class:`~matplotlib.axes.Axes` instance is returned.
======= ============ ================================================
kwarg Accepts Desctiption
======= ============ ================================================
axisbg color the axes background color
frameon [True|False] display the frame?
sharex otherax current axes shares xaxis attribute with otherax
sharey otherax current axes shares yaxis attribute with otherax
polar [True|False] use a polar axes?
======= ============ ================================================
Examples:
* :file:`examples/pylab_examples/axes_demo.py` places custom axes.
* :file:`examples/pylab_examples/shared_axis_demo.py` uses
*sharex* and *sharey*.
"""
nargs
=
len
(
args
)
if
len
(
args
)
==
0
:
return
subplot
(
111
,
**
kwargs
)
if
nargs
>
1
:
raise
TypeError
(
'Only one non keyword arg to axes allowed'
)
arg
=
args
[
0
]
if
isinstance
(
arg
,
Axes
):
a
=
gcf
().
sca
(
arg
)
else
:
rect
=
arg
a
=
gcf
().
add_axes
(
rect
,
**
kwargs
)
draw_if_interactive
()
return
a
def
delaxes
(
*
args
):
"""
``delaxes(ax)``: remove *ax* from the current figure. If *ax*
doesn't exist, an error will be raised.
``delaxes()``: delete the current axes
"""
if
not
len
(
args
):
ax
=
gca
()
else
:
ax
=
args
[
0
]
ret
=
gcf
().
delaxes
(
ax
)
draw_if_interactive
()
return
ret
def
sca
(
ax
):
"""
Set the current Axes instance to *ax*. The current Figure
is updated to the parent of *ax*.
"""
managers
=
_pylab_helpers
.
Gcf
.
get_all_fig_managers
()
for
m
in
managers
:
if
ax
in
m
.
canvas
.
figure
.
axes
:
_pylab_helpers
.
Gcf
.
set_active
(
m
)
m
.
canvas
.
figure
.
sca
(
ax
)
return
raise
ValueError
(
"Axes instance argument was not found in a figure."
)
def
gca
(
**
kwargs
):
"""
Return the current axis instance. This can be used to control
axis properties either using set or the
:class:`~matplotlib.axes.Axes` methods, for example, setting the
xaxis range::
plot(t,s)
set(gca(), 'xlim', [0,10])
or::
plot(t,s)
a = gca()
a.set_xlim([0,10])
"""
ax
=
gcf
().
gca
(
**
kwargs
)
return
ax
# More ways of creating axes:
def
subplot
(
*
args
,
**
kwargs
):
"""
Create a subplot command, creating axes with::
subplot(numRows, numCols, plotNum)
where *plotNum* = 1 is the first plot number and increasing *plotNums*
fill rows first. max(*plotNum*) == *numRows* * *numCols*
You can leave out the commas if *numRows* <= *numCols* <=
*plotNum* < 10, as in::
subplot(211) # 2 rows, 1 column, first (upper) plot
``subplot(111)`` is the default axis.
New subplots that overlap old will delete the old axes. If you do
not want this behavior, use
:meth:`matplotlib.figure.Figure.add_subplot` or the
:func:`~matplotlib.pyplot.axes` command. Eg.::
from pylab import *
plot([1,2,3]) # implicitly creates subplot(111)
subplot(211) # overlaps, subplot(111) is killed
plot(rand(12), rand(12))
subplot(212, axisbg='y') # creates 2nd subplot with yellow background
Keyword arguments:
*axisbg*:
The background color of the subplot, which can be any valid
color specifier. See :mod:`matplotlib.colors` for more
information.
*polar*:
A boolean flag indicating whether the subplot plot should be
a polar projection. Defaults to False.
*projection*:
A string giving the name of a custom projection to be used
for the subplot. This projection must have been previously
registered. See :func:`matplotlib.projections.register_projection`
.. seealso::
:func:`~matplotlib.pyplot.axes`
For additional information on :func:`axes` and
:func:`subplot` keyword arguments.
:file:`examples/pylab_examples/polar_scatter.py`
For an example
**Example:**
.. plot:: mpl_examples/pylab_examples/subplot_demo.py
"""
fig
=
gcf
()
a
=
fig
.
add_subplot
(
*
args
,
**
kwargs
)
bbox
=
a
.
bbox
byebye
=
[]
for
other
in
fig
.
axes
:
if
other
==
a
:
continue
if
bbox
.
fully_overlaps
(
other
.
bbox
):
byebye
.
append
(
other
)
for
ax
in
byebye
:
delaxes
(
ax
)
draw_if_interactive
()
return
a
def
subplots
(
nrows
=
1
,
ncols
=
1
,
sharex
=
False
,
sharey
=
False
,
squeeze
=
True
,
subplot_kw
=
None
,
**
fig_kw
):
"""Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, including the enclosing figure object, in a single call.
Keyword arguments:
nrows : int
Number of rows of the subplot grid. Defaults to 1.
ncols : int
Number of columns of the subplot grid. Defaults to 1.
sharex : bool
If True, the X axis will be shared amongst all subplots. If
True and you have multiple rows, the x tick labels on all but
the last row of plots will have visible set to False
sharey : bool
If True, the Y axis will be shared amongst all subplots. If
True and you have multiple columns, the y tick labels on all but
the first column of plots will have visible set to False
squeeze : bool
If True, extra dimensions are squeezed out from the returned axis object:
- if only one subplot is constructed (nrows=ncols=1), the
resulting single Axis object is returned as a scalar.
- for Nx1 or 1xN subplots, the returned object is a 1-d numpy
object array of Axis objects are returned as numpy 1-d
arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d
array.
If False, no squeezing at all is done: the returned axis object is always
a 2-d array contaning Axis instances, even if it ends up being 1x1.
subplot_kw : dict
Dict with keywords passed to the add_subplot() call used to create each
subplots.
fig_kw : dict
Dict with keywords passed to the figure() call. Note that all keywords
not recognized above will be automatically included here.
Returns:
fig, ax : tuple
- fig is the Matplotlib Figure object
- ax can be either a single axis object or an array of axis
objects if more than one supblot was created. The dimensions
of the resulting array can be controlled with the squeeze
keyword, see above.
**Examples:**
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Two subplots, unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Four polar axes
plt.subplots(2, 2, subplot_kw=dict(polar=True))
"""
if
subplot_kw
is
None
:
subplot_kw
=
{}
fig
=
figure
(
**
fig_kw
)
# Create empty object array to hold all axes. It's easiest to make it 1-d
# so we can just append subplots upon creation, and then
nplots
=
nrows
*
ncols
axarr
=
np
.
empty
(
nplots
,
dtype
=
object
)
# Create first subplot separately, so we can share it if requested
ax0
=
fig
.
add_subplot
(
nrows
,
ncols
,
1
,
**
subplot_kw
)
if
sharex
:
subplot_kw
[
'sharex'
]
=
ax0
if
sharey
:
subplot_kw
[
'sharey'
]
=
ax0
axarr
[
0
]
=
ax0
# Note off-by-one counting because add_subplot uses the MATLAB 1-based
# convention.
for
i
in
range
(
1
,
nplots
):
axarr
[
i
]
=
fig
.
add_subplot
(
nrows
,
ncols
,
i
+
1
,
**
subplot_kw
)
# returned axis array will be always 2-d, even if nrows=ncols=1
axarr
=
axarr
.
reshape
(
nrows
,
ncols
)
# turn off redundant tick labeling
if
sharex
and
nrows
>
1
:
# turn off all but the bottom row
for
ax
in
axarr
[:
-
1
,:].
flat
:
for
label
in
ax
.
get_xticklabels
():
label
.
set_visible
(
False
)
if
sharey
and
ncols
>
1
:
# turn off all but the first column
for
ax
in
axarr
[:,
1
:].
flat
:
for
label
in
ax
.
get_yticklabels
():
label
.
set_visible
(
False
)
if
squeeze
:
# Reshape the array to have the final desired dimension (nrow,ncol),
# though discarding unneeded dimensions that equal 1. If we only have
# one subplot, just return it instead of a 1-element array.
if
nplots
==
1
:
ret
=
fig
,
axarr
[
0
,
0
]
else
:
ret
=
fig
,
axarr
.
squeeze
()
else
:
# returned axis array will be always 2-d, even if nrows=ncols=1
ret
=
fig
,
axarr
.
reshape
(
nrows
,
ncols
)
return
ret
from
gridspec
import
GridSpec
def
subplot2grid
(
shape
,
loc
,
rowspan
=
1
,
colspan
=
1
,
**
kwargs
):
"""
It creates a subplot in a grid of *shape*, at location of *loc*,
spanning *rowspan*, *colspan* cells in each direction.
The index for loc is 0-based. ::
subplot2grid(shape, loc, rowspan=1, colspan=1)
is identical to ::
gridspec=GridSpec(shape[0], shape[2])
subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
subplot(subplotspec)
"""
fig
=
gcf
()
s1
,
s2
=
shape
subplotspec
=
GridSpec
(
s1
,
s2
).
new_subplotspec
(
loc
,
rowspan
=
rowspan
,
colspan
=
colspan
)
a
=
fig
.
add_subplot
(
subplotspec
,
**
kwargs
)
bbox
=
a
.
bbox
byebye
=
[]
for
other
in
fig
.
axes
:
if
other
==
a
:
continue
if
bbox
.
fully_overlaps
(
other
.
bbox
):
byebye
.
append
(
other
)
for
ax
in
byebye
:
delaxes
(
ax
)
draw_if_interactive
()
return
a
def
twinx
(
ax
=
None
):
"""
Make a second axes overlay *ax* (or the current axes if *ax* is
*None*) sharing the xaxis. The ticks for *ax2* will be placed on
the right, and the *ax2* instance is returned.
.. seealso::
:file:`examples/api_examples/two_scales.py`
For an example
"""
if
ax
is
None
:
ax
=
gca
()
ax1
=
ax
.
twinx
()
draw_if_interactive
()
return
ax1
def
twiny
(
ax
=
None
):
"""
Make a second axes overlay *ax* (or the current axes if *ax* is
*None*) sharing the yaxis. The ticks for *ax2* will be placed on
the top, and the *ax2* instance is returned.
"""
if
ax
is
None
:
ax
=
gca
()
ax1
=
ax
.
twiny
()
draw_if_interactive
()
return
ax1
def
subplots_adjust
(
*
args
,
**
kwargs
):
"""
call signature::
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
Tune the subplot layout via the
:class:`matplotlib.figure.SubplotParams` mechanism. The parameter
meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
fig
=
gcf
()
fig
.
subplots_adjust
(
*
args
,
**
kwargs
)
draw_if_interactive
()
def
subplot_tool
(
targetfig
=
None
):
"""
Launch a subplot tool window for *targetfig* (default gcf).
A :class:`matplotlib.widgets.SubplotTool` instance is returned.
"""
tbar
=
rcParams
[
'toolbar'
]
# turn off the navigation toolbar for the toolfig
rcParams
[
'toolbar'
]
=
'None'
if
targetfig
is
None
:
manager
=
get_current_fig_manager
()
targetfig
=
manager
.
canvas
.
figure
else
:
# find the manager for this figure
for
manager
in
_pylab_helpers
.
Gcf
.
_activeQue
:
if
manager
.
canvas
.
figure
==
targetfig
:
break
else
:
raise
RuntimeError
(
'Could not find manager for targetfig'
)
toolfig
=
figure
(
figsize
=
(
6
,
3
))
toolfig
.
subplots_adjust
(
top
=
0.9
)
ret
=
SubplotTool
(
targetfig
,
toolfig
)
rcParams
[
'toolbar'
]
=
tbar
_pylab_helpers
.
Gcf
.
set_active
(
manager
)
# restore the current figure
return
ret
def
tight_layout
(
pad
=
1.2
,
h_pad
=
None
,
w_pad
=
None
):
"""Adjust subplot parameters to give specified padding.
Parameters
----------
pad : float
padding between the figure edge and the edges of subplots, as a fraction of the font-size.
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL