FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/pyplot.py at master · flothesof/matplotlib · GitHub
flothesof
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
3877 lines (3102 loc) · 121 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
pyplot.py
Copy path
File metadata and controls
3877 lines (3102 loc) · 121 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
# Note: The first part of this file can be modified in place, but the latter
# part is autogenerated by the boilerplate.py script.
"""
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)
"""
from
__future__
import
(
absolute_import
,
division
,
print_function
,
unicode_literals
)
from
matplotlib
.
externals
import
six
import
sys
import
warnings
import
types
from
cycler
import
cycler
import
matplotlib
import
matplotlib
.
colorbar
from
matplotlib
import
style
from
matplotlib
import
_pylab_helpers
,
interactive
from
matplotlib
.
cbook
import
dedent
,
silent_list
,
is_string_like
,
is_numlike
from
matplotlib
.
cbook
import
_string_to_bool
from
matplotlib
import
docstring
from
matplotlib
.
backend_bases
import
FigureCanvasBase
from
matplotlib
.
figure
import
Figure
,
figaspect
from
matplotlib
.
gridspec
import
GridSpec
from
matplotlib
.
image
import
imread
as
_imread
from
matplotlib
.
image
import
imsave
as
_imsave
from
matplotlib
import
rcParams
,
rcParamsDefault
,
get_backend
from
matplotlib
import
rc_context
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
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
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
'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
'PyQt5.QtCore'
in
sys
.
modules
and
not
backend
==
'Qt5Agg'
:
import
PyQt5
.
QtWidgets
if
not
PyQt5
.
QtWidgets
.
qApp
.
startingUp
():
# The mainloop is running.
rcParams
[
'backend'
]
=
'qt5Agg'
elif
(
'gtk'
in
sys
.
modules
and
backend
not
in
(
'GTK'
,
'GTKAgg'
,
'GTKCairo'
)):
if
'gi'
in
sys
.
modules
:
from
gi
.
repository
import
GObject
ml
=
GObject
.
MainLoop
else
:
import
gobject
ml
=
gobject
.
MainLoop
if
ml
().
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
_backend_mod
,
new_figure_manager
,
draw_if_interactive
,
_show
=
pylab_setup
()
_IP_REGISTERED
=
None
_INSTALL_FIG_OBSERVER
=
False
def
install_repl_displayhook
():
"""
Install a repl display hook so that any stale figure are automatically
redrawn when control is returned to the repl.
This works with both IPython terminals and vanilla python shells.
"""
global
_IP_REGISTERED
global
_INSTALL_FIG_OBSERVER
class
_NotIPython
(
Exception
):
pass
# see if we have IPython hooks around, if use them
try
:
if
'IPython'
in
sys
.
modules
:
from
IPython
import
get_ipython
ip
=
get_ipython
()
if
ip
is
None
:
raise
_NotIPython
()
if
_IP_REGISTERED
:
return
def
post_execute
():
if
matplotlib
.
is_interactive
():
draw_all
()
# IPython >= 2
try
:
ip
.
events
.
register
(
'post_execute'
,
post_execute
)
except
AttributeError
:
# IPython 1.x
ip
.
register_post_execute
(
post_execute
)
_IP_REGISTERED
=
post_execute
_INSTALL_FIG_OBSERVER
=
False
else
:
_INSTALL_FIG_OBSERVER
=
True
# import failed or ipython is not running
except
(
ImportError
,
_NotIPython
):
_INSTALL_FIG_OBSERVER
=
True
def
uninstall_repl_displayhook
():
"""
Uninstalls the matplotlib display hook.
.. warning
Need IPython >= 2 for this to work. For IPython < 2 will raise a
``NotImplementedError``
.. warning
If you are using vanilla python and have installed another
display hook this will reset ``sys.displayhook`` to what ever
function was there when matplotlib installed it's displayhook,
possibly discarding your changes.
"""
global
_IP_REGISTERED
global
_INSTALL_FIG_OBSERVER
if
_IP_REGISTERED
:
from
IPython
import
get_ipython
ip
=
get_ipython
()
try
:
ip
.
events
.
unregister
(
'post_execute'
,
_IP_REGISTERED
)
except
AttributeError
:
raise
NotImplementedError
(
"Can not unregister events "
"in IPython < 2.0"
)
_IP_REGISTERED
=
None
if
_INSTALL_FIG_OBSERVER
:
_INSTALL_FIG_OBSERVER
=
False
draw_all
=
_pylab_helpers
.
Gcf
.
draw_all
@
docstring
.
copy_dedent
(
Artist
.
findobj
)
def
findobj
(
o
=
None
,
match
=
None
,
include_self
=
True
):
if
o
is
None
:
o
=
gcf
()
return
o
.
findobj
(
match
,
include_self
=
include_self
)
def
switch_backend
(
newbackend
):
"""
Switch the default backend. This feature is **experimental**, and
is only expected to work switching to an image backend. e.g., 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
_backend_mod
,
new_figure_manager
,
draw_if_interactive
,
_show
matplotlib
.
use
(
newbackend
,
warn
=
False
,
force
=
True
)
from
matplotlib
.
backends
import
pylab_setup
_backend_mod
,
new_figure_manager
,
draw_if_interactive
,
_show
=
pylab_setup
()
def
show
(
*
args
,
**
kw
):
"""
Display a figure.
When running in ipython with its pylab mode, display all
figures and return to the ipython prompt.
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.
A single experimental keyword argument, *block*, may be
set to True or False to override the blocking behavior
described above.
"""
global
_show
return
_show
(
*
args
,
**
kw
)
def
isinteractive
():
"""
Return status of interactive mode.
"""
return
matplotlib
.
is_interactive
()
def
ioff
():
'Turn interactive mode off.'
matplotlib
.
interactive
(
False
)
uninstall_repl_displayhook
()
def
ion
():
'Turn interactive mode on.'
matplotlib
.
interactive
(
True
)
install_repl_displayhook
()
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`.
This function is experimental; its behavior may be changed
or extended in a future release.
"""
backend
=
rcParams
[
'backend'
]
if
backend
in
_interactive_bk
:
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
figManager
is
not
None
:
canvas
=
figManager
.
canvas
if
canvas
.
figure
.
stale
:
canvas
.
draw
()
show
(
block
=
False
)
canvas
.
start_event_loop
(
interval
)
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
.
rc_context
)
def
rc_context
(
rc
=
None
,
fname
=
None
):
return
matplotlib
.
rc_context
(
rc
,
fname
)
@
docstring
.
copy_dedent
(
matplotlib
.
rcdefaults
)
def
rcdefaults
():
matplotlib
.
rcdefaults
()
if
matplotlib
.
is_interactive
():
draw_all
()
# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions:
def
gci
():
"""
Get the current colorable artist. Specifically, returns 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. This image will be the 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
):
return
_setp
(
*
args
,
**
kwargs
)
def
xkcd
(
scale
=
1
,
length
=
100
,
randomness
=
2
):
"""
Turns on `xkcd <http://xkcd.com/>`_ sketch-style drawing mode.
This will only have effect on things drawn after this function is
called.
For best results, the "Humor Sans" font should be installed: it is
not included with matplotlib.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source line.
length : float, optional
The length of the wiggle along the line.
randomness : float, optional
The scale factor by which the length is shrunken or expanded.
Notes
-----
This function works by a number of rcParams, so it will probably
override others you have set before.
If you want the effects of this function to be temporary, it can
be used as a context manager, for example::
with plt.xkcd():
# This figure will be in XKCD-style
fig1 = plt.figure()
# ...
# This figure will be in regular style
fig2 = plt.figure()
"""
if
rcParams
[
'text.usetex'
]:
raise
RuntimeError
(
"xkcd mode is not compatible with text.usetex = True"
)
from
matplotlib
import
patheffects
context
=
rc_context
()
try
:
rcParams
[
'font.family'
]
=
[
'Humor Sans'
,
'Comic Sans MS'
]
rcParams
[
'font.size'
]
=
14.0
rcParams
[
'path.sketch'
]
=
(
scale
,
length
,
randomness
)
rcParams
[
'path.effects'
]
=
[
patheffects
.
withStroke
(
linewidth
=
4
,
foreground
=
"w"
)]
rcParams
[
'axes.linewidth'
]
=
1.5
rcParams
[
'lines.linewidth'
]
=
2.0
rcParams
[
'figure.facecolor'
]
=
'white'
rcParams
[
'grid.linewidth'
]
=
0.0
rcParams
[
'axes.grid'
]
=
False
rcParams
[
'axes.unicode_minus'
]
=
False
rcParams
[
'axes.prop_cycle'
]
=
cycler
(
'color'
, [
'b'
,
'r'
,
'c'
,
'm'
])
rcParams
[
'axes.edgecolor'
]
=
'black'
rcParams
[
'xtick.major.size'
]
=
8
rcParams
[
'xtick.major.width'
]
=
3
rcParams
[
'ytick.major.size'
]
=
8
rcParams
[
'ytick.major.width'
]
=
3
except
:
context
.
__exit__
(
*
sys
.
exc_info
())
raise
return
context
## 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
):
"""
Creates a new figure.
Parameters
----------
num : integer or string, optional, default: none
If not provided, a new figure will be created, and the figure number
will be incremented. The figure objects holds this number in a `number`
attribute.
If num is provided, and a figure with this id already exists, make
it active, and returns a reference to it. If this figure does not
exists, create it and returns it.
If num is a string, the window title will be set to this figure's
`num`.
figsize : tuple of integers, optional, default: None
width, height in inches. If not provided, defaults to rc
figure.figsize.
dpi : integer, optional, default: None
resolution of the figure. If not provided, defaults to rc figure.dpi.
facecolor :
the background color. If not provided, defaults to rc figure.facecolor
edgecolor :
the border color. If not provided, defaults to rc figure.edgecolor
Returns
-------
figure : Figure
The Figure instance returned will also be passed to new_figure_manager
in the backends, which allows to hook custom Figure classes into the
pylab interface. Additional kwargs will be passed to the figure init
function.
Notes
-----
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.
rcParams defines the default values, which can be modified in the
matplotlibrc file
"""
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'
]
allnums
=
get_fignums
()
next_num
=
max
(
allnums
)
+
1
if
allnums
else
1
figLabel
=
''
if
num
is
None
:
num
=
next_num
elif
is_string_like
(
num
):
figLabel
=
num
allLabels
=
get_figlabels
()
if
figLabel
not
in
allLabels
:
if
figLabel
==
'all'
:
warnings
.
warn
(
"close('all') closes all existing figures"
)
num
=
next_num
else
:
inum
=
allLabels
.
index
(
figLabel
)
num
=
allnums
[
inum
]
else
:
num
=
int
(
num
)
# crude validation of num argument
figManager
=
_pylab_helpers
.
Gcf
.
get_fig_manager
(
num
)
if
figManager
is
None
:
max_open_warning
=
rcParams
[
'figure.max_open_warning'
]
if
(
max_open_warning
>=
1
and
len
(
allnums
)
>=
max_open_warning
):
warnings
.
warn
(
"More than %d figures have been opened. Figures "
"created through the pyplot interface "
"(`matplotlib.pyplot.figure`) are retained until "
"explicitly closed and may consume too much memory. "
"(To control this warning, see the rcParam "
"`figure.max_open_warning`)."
%
max_open_warning
,
RuntimeWarning
)
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
)
if
figLabel
:
figManager
.
set_window_title
(
figLabel
)
figManager
.
canvas
.
figure
.
set_label
(
figLabel
)
# 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
)
fig
=
figManager
.
canvas
.
figure
fig
.
number
=
num
# make sure backends (inline) that we don't ship that expect this
# to be called in plotting commands to make the figure call show
# still work. There is probably a better way to do this in the
# FigureManager base class.
if
matplotlib
.
is_interactive
():
draw_if_interactive
()
if
_INSTALL_FIG_OBSERVER
:
fig
.
stale_callback
=
_auto_draw_if_interactive
return
figManager
.
canvas
.
figure
def
_auto_draw_if_interactive
(
fig
,
val
):
"""
This is an internal helper function for making sure that auto-redrawing
works as intended in the plain python repl.
Parameters
----------
fig : Figure
A figure object which is assumed to be associated with a canvas
"""
if
val
and
matplotlib
.
is_interactive
()
and
not
fig
.
canvas
.
is_saving
():
fig
.
canvas
.
draw_idle
()
def
gcf
():
"Get a reference to the current figure."
figManager
=
_pylab_helpers
.
Gcf
.
get_active
()
if
figManager
is
not
None
:
return
figManager
.
canvas
.
figure
else
:
return
figure
()
def
fignum_exists
(
num
):
return
_pylab_helpers
.
Gcf
.
has_fignum
(
num
)
or
num
in
get_figlabels
()
def
get_fignums
():
"""Return a list of existing figure numbers."""
fignums
=
list
(
six
.
iterkeys
(
_pylab_helpers
.
Gcf
.
figs
))
fignums
.
sort
()
return
fignums
def
get_figlabels
():
"Return a list of existing figure labels."
figManagers
=
_pylab_helpers
.
Gcf
.
get_all_fig_managers
()
figManagers
.
sort
(
key
=
lambda
m
:
m
.
num
)
return
[
m
.
canvas
.
figure
.
get_label
()
for
m
in
figManagers
]
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(h)`` where *h* is a :class:`Figure` instance, closes that figure
``close(num)`` closes figure number *num*
``close(name)`` where *name* is a string, closes figure with that label
``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
,
six
.
integer_types
):
_pylab_helpers
.
Gcf
.
destroy
(
arg
)
elif
hasattr
(
arg
,
'int'
):
# if we are dealing with a type UUID, we
# can use its integer representation
_pylab_helpers
.
Gcf
.
destroy
(
arg
.
int
)
elif
is_string_like
(
arg
):
allLabels
=
get_figlabels
()
if
arg
in
allLabels
:
num
=
get_fignums
()[
allLabels
.
index
(
arg
)]
_pylab_helpers
.
Gcf
.
destroy
(
num
)
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
()
def
draw
():
"""Redraw the current figure.
This is used in interactive mode to update a figure that has been
altered, but not automatically re-drawn. This should be only rarely
needed, but there may be ways to modify the state of a figure with
out marking it as `stale`. Please report these cases as bugs.
A more object-oriented alternative, given any
:class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
was created using a :mod:`~matplotlib.pyplot` function, is::
fig.canvas.draw_idle()
"""
get_current_fig_manager
().
canvas
.
draw_idle
()
@
docstring
.
copy_dedent
(
Figure
.
savefig
)
def
savefig
(
*
args
,
**
kwargs
):
fig
=
gcf
()
res
=
fig
.
savefig
(
*
args
,
**
kwargs
)
fig
.
canvas
.
draw_idle
()
# need this if 'transparent=True' to reset colors
return
res
@
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
):
return
gcf
().
text
(
*
args
,
**
kwargs
)
@
docstring
.
copy_dedent
(
Figure
.
suptitle
)
def
suptitle
(
*
args
,
**
kwargs
):
return
gcf
().
suptitle
(
*
args
,
**
kwargs
)
@
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
#sci(ret) # JDH figimage should not set current image -- it is not mappable, etc
return
gcf
().
figimage
(
*
args
,
**
kwargs
)
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`
"""
return
gcf
().
legend
(
handles
,
labels
,
loc
,
**
kwargs
)
## 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
):
"""
Call a function with hold(True).
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 to the figure.
The axes is added 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 Description
======= ============== ==============================================
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?
aspect [str | num] ['equal', 'auto'] or a number. If a number
the ratio of x-unit/y-unit in screen-space.
Also see
:meth:`~matplotlib.axes.Axes.set_aspect`.
======= ============== ==============================================
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
)
return
a
def
delaxes
(
*
args
):
"""
Remove an axes 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
)
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
):
"""
Get the current :class:`~matplotlib.axes.Axes` instance on the
current figure matching the given keyword args, or create one.
Examples
---------
To get the current polar axes on the current figure::
plt.gca(projection='polar')
If the current axes doesn't exist, or isn't a polar one, the appropriate
axes will be created and then returned.
See Also
--------
matplotlib.figure.Figure.gca : The figure's gca method.
"""
return
gcf
().
gca
(
**
kwargs
)
# More ways of creating axes:
def
subplot
(
*
args
,
**
kwargs
):
"""
Return a subplot axes positioned by the given grid definition.
Typical call signature::
subplot(nrows, ncols, plot_number)
Where *nrows* and *ncols* are used to notionally split the figure
into ``nrows * ncols`` sub-axes, and *plot_number* is used to identify
the particular subplot that this function is to create within the notional
grid. *plot_number* starts at 1, increments across rows first and has a
maximum of ``nrows * ncols``.
In the case when *nrows*, *ncols* and *plot_number* are all less than 10,
a convenience exists, such that the a 3 digit number can be given instead,
where the hundreds represent *nrows*, the tens represent *ncols* and the
units represent *plot_number*. For instance::
subplot(211)
produces a subaxes in a figure which represents the top plot (i.e. the
first) in a 2 row by 1 column notional grid (no grid actually exists,
but conceptually this is how the returned subplot has been positioned).
.. note::
Creating a new subplot with a position which is entirely inside a
pre-existing axes will trigger the larger axes to be deleted::
import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
plt.subplot(211)
plt.plot(range(12))
plt.subplot(212, axisbg='y') # creates 2nd subplot with yellow background
If you do not want this behavior, use the
:meth:`~matplotlib.figure.Figure.add_subplot` method or the
:func:`~matplotlib.pyplot.axes` function instead.
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 :mod:`matplotlib.projections`.
.. seealso::
:func:`~matplotlib.pyplot.axes`
For additional information on :func:`axes` and
:func:`subplot` keyword arguments.
:file:`examples/pie_and_polar_charts/polar_scatter_demo.py`
For an example
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL