forked from matplotlib/matplotlib
/
pyplot.py
2352 lines (1913 loc) · 66.6 KB
/
pyplot.py
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
import sys
import matplotlib
from matplotlib import _pylab_helpers
from matplotlib.cbook import dedent, silent_list, is_string_like, is_numlike
from matplotlib.figure import Figure, figaspect
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.image import imread as _imread
from matplotlib import rcParams, rcParamsDefault, get_backend
from matplotlib.artist import getp, get
from matplotlib.artist import setp as _setp
from matplotlib.axes import Axes
from matplotlib.projections import PolarAxes
from matplotlib import mlab # for csv2rec in plotfile
from matplotlib import cm
from matplotlib.cm import get_cmap
# 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
## Global ##
from matplotlib.backends import pylab_setup
new_figure_manager, draw_if_interactive, show = pylab_setup()
def switch_backend(newbackend):
"""
Swtich 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 PS 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)
reload(backends)
from backends import new_figure_manager, draw_if_interactive, show
def isinteractive():
"""
Return the interactive status
"""
return matplotlib.is_interactive()
def ioff():
'turn interactive mode off'
matplotlib.interactive(False)
def ion():
'turn interactive mode on'
matplotlib.interactive(True)
def rc(*args, **kwargs):
matplotlib.rc(*args, **kwargs)
if matplotlib.rc.__doc__ is not None:
rc.__doc__ = dedent(matplotlib.rc.__doc__)
def rcdefaults():
matplotlib.rcdefaults()
draw_if_interactive()
if matplotlib.rcdefaults.__doc__ is not None:
rcdefaults.__doc__ = dedent(matplotlib.rcdefaults.__doc__)
# The current "image" (ScalarMappable) is tracked here on a
# per-pylab-session basis:
def gci():
"""
get the current ScalarMappable instance (image or patch
collection), or None if no images or patch collections have been
defined. The commands imshow and figimage create images
instances, and the commands pcolor and scatter create patch
collection instances
"""
return gci._current
gci._current = None
def sci(im):
"""
Set the current image (the target of colormap commands like jet, hot or clim)
"""
gci._current = im
## Any Artist ##
# (getp is simply imported)
def setp(*args, **kwargs):
ret = _setp(*args, **kwargs)
draw_if_interactive()
return ret
if _setp.__doc__ is not None:
setp.__doc__ = _setp.__doc__
## 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
):
"""
figure(num = None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
Create a new figure and return a handle to it. 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 the handle 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.
kwargs:
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 gives the default values from the matplotlibrc file
FigureClass is a Figure or derived class that will be passed on to
new_figure_manager in the backends which allows you to hook custom
Figureclasses 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
figManager = _pylab_helpers.Gcf.get_fig_manager(num)
if figManager is None:
if get_backend()=='PS': dpi = 72
figManager = new_figure_manager(num, figsize=figsize,
dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor,
frameon=frameon,
FigureClass=FigureClass,
**kwargs)
_pylab_helpers.Gcf.set_active(figManager)
figManager.canvas.figure.number = num
draw_if_interactive()
return figManager.canvas.figure
def gcf():
"Return a handle to the current figure"
figManager = _pylab_helpers.Gcf.get_active()
if figManager is not None:
return figManager.canvas.figure
else:
return figure()
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
# note we check for __doc__ is not None since py2exe optimize removes
# the docstrings
def connect(s, func):
return get_current_fig_manager().canvas.mpl_connect(s, func)
if FigureCanvasBase.mpl_connect.__doc__ is not None:
connect.__doc__ = dedent(FigureCanvasBase.mpl_connect.__doc__)
def disconnect(cid):
return get_current_fig_manager().canvas.mpl_disconnect(cid)
if FigureCanvasBase.mpl_disconnect.__doc__ is not None:
disconnect.__doc__ = dedent(FigureCanvasBase.mpl_disconnect.__doc__)
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 figure handle(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':
for manager in _pylab_helpers.Gcf.get_all_fig_managers():
_pylab_helpers.Gcf.destroy(manager.num)
elif isinstance(arg, int):
_pylab_helpers.Gcf.destroy(arg)
elif isinstance(arg, Figure):
for manager in _pylab_helpers.Gcf.get_all_fig_managers():
if manager.canvas.figure==arg:
_pylab_helpers.Gcf.destroy(manager.num)
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'
get_current_fig_manager().canvas.draw()
def savefig(*args, **kwargs):
fig = gcf()
return fig.savefig(*args, **kwargs)
if Figure.savefig.__doc__ is not None:
savefig.__doc__ = dedent(Figure.savefig.__doc__)
# Putting things in figures
def figtext(*args, **kwargs):
ret = gcf().text(*args, **kwargs)
draw_if_interactive()
return ret
if Figure.text.__doc__ is not None:
figtext.__doc__ = dedent(Figure.text.__doc__)
def figimage(*args, **kwargs):
# allow callers to override the hold state by passing hold=True|False
ret = gcf().figimage(*args, **kwargs)
draw_if_interactive()
gci._current = ret
return ret
if Figure.figimage.__doc__ is not None:
figimage.__doc__ = dedent(Figure.figimage.__doc__) + """
Addition kwargs: hold = [True|False] overrides default hold state"""
def figlegend(handles, labels, loc, **kwargs):
"""
Place a legend in the figure. Labels are a sequence of
strings, handles is a sequence of line or patch instances, and
loc can be a string r an integer specifying the legend
location
USAGE:
legend( (line1, line2, line3),
('label1', 'label2', 'label3'),
'upper right')
See help(legend) for information about the location codes
A matplotlib.legend.Legend instance is returned
"""
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 hold is None (default), toggle the
hold state. Else set the hold state to boolean value b.
Eg
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
"""
gcf().hold(b)
gca().hold(b)
rc('axes', hold=b)
def ishold():
"""
Return the hold status of the current axes
"""
return gca().ishold()
def over(func, *args, **kwargs):
"""
Call func(*args, **kwargs) with hold(True) and then restore the hold state
"""
h = ishold()
hold(True)
func(*args, **kwargs)
hold(h)
## Axes ##
def axes(*args, **kwargs):
"""
Add an axes at positon 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 Axes instance is returned
kwargs:
axisbg=color : the axes background color
frameon=False : don't display the frame
sharex=otherax : the current axes shares xaxis attribute with otherax
sharey=otherax : the current axes shares yaxis attribute with otherax
polar=True|False : use a polar axes or not
Examples
examples/axes_demo.py places custom axes.
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 gca(**kwargs):
"""
Return the current axis instance. This can be used to control
axis properties either using set or the Axes methods.
Example:
plot(t,s)
set(gca(), 'xlim', [0,10]) # set the x axis limits
or
plot(t,s)
a = gca()
a.set_xlim([0,10]) # does the same
"""
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
The background color of the subplot can be specified via keyword
argument 'axisbg', which takes a color string or gdk.Color as value, as in
subplot(211, axisbg='y')
See help(axes) for additional information on axes and subplot
keyword arguments.
New subplots that overlap old will delete the old axes. If you do
not want this behavior, use fig.add_subplot or the axes command. Eg
from pylab import *
plot([1,2,3]) # implicitly creates subplot(111)
subplot(211) # overlaps, subplot(111) is killed
plot(rand(12), rand(12))
"""
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 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. See examples/two_scales.py
"""
if ax is None:
ax=gca()
draw_if_interactive()
return ax.twinx()
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()
draw_if_interactive()
return ax.twiny()
def subplots_adjust(*args, **kwargs):
"""
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
Tune the subplot layout via the 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 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 box(on=None):
"""
Turn the axes box on or off according to 'on'
If on is None, toggle state
"""
ax = gca()
if on is None:
on = not ax.get_frame_on()
ax.set_frame_on(on)
draw_if_interactive()
def title(s, *args, **kwargs):
"""
Set the title of the current axis to s
Default font override is:
override = {
'fontsize' : 'medium',
'verticalalignment' : 'bottom',
'horizontalalignment' : 'center'
}
See the text docstring for information of how override and the
optional args work
"""
l = gca().set_title(s, *args, **kwargs)
draw_if_interactive()
return l
## Axis ##
def axis(*v, **kwargs):
"""
Set/Get the axis properties::
v = axis() returns the current axes as v = [xmin, xmax, ymin, ymax]
axis(v) where v = [xmin, xmax, ymin, ymax] sets the min and max
of the x and y axes
axis('off') turns off the axis lines and labels
axis('equal') changes limits of x or y axis so that equal
increments of x and y have the same length; a circle
is circular.
axis('scaled') achieves the same result by changing the
dimensions of the plot box instead of the axis data
limits.
axis('tight') changes x and y axis limits such that all data is
shown. If all data is already shown, it will move it to the center
of the figure without modifying (xmax-xmin) or (ymax-ymin). Note
this is slightly different than in matlab.
axis('image') is 'scaled' with the axis limits equal to the
data limits.
axis('auto') or 'normal' (deprecated) restores default behavior;
axis limits are automatically scaled to make the data fit
comfortably within the plot box.
if len(*v)==0, you can pass in xmin, xmax, ymin, ymax as kwargs
selectively to alter just those limits w/o changing the others.
See help(xlim) and help(ylim) for more information
The xmin, xmax, ymin, ymax tuple is returned
"""
ax = gca()
v = ax.axis(*v, **kwargs)
draw_if_interactive()
return v
def xlabel(s, *args, **kwargs):
"""
Set the x axis label of the current axis to s
Default override is
override = {
'fontsize' : 'small',
'verticalalignment' : 'top',
'horizontalalignment' : 'center'
}
See the text docstring for information of how override and
the optional args work
"""
l = gca().set_xlabel(s, *args, **kwargs)
draw_if_interactive()
return l
def ylabel(s, *args, **kwargs):
"""
Set the y axis label of the current axis to s
Defaults override is
override = {
'fontsize' : 'small',
'verticalalignment' : 'center',
'horizontalalignment' : 'right',
'rotation'='vertical' : }
See the text docstring for information of how override and the
optional args work
"""
l = gca().set_ylabel(s, *args, **kwargs)
draw_if_interactive()
return l
def xlim(*args, **kwargs):
"""
Set/Get the xlimits of the current axes
xmin, xmax = xlim() : return the current xlim
xlim( (xmin, xmax) ) : set the xlim to xmin, xmax
xlim( xmin, xmax ) : set the xlim to xmin, xmax
If you do not specify args, you can pass the xmin and xmax as
kwargs, eg
xlim(xmax=3) # adjust the max leaving min unchanged
xlim(xmin=1) # adjust the min leaving max unchanged
The new axis limits are returned as a length 2 tuple
"""
ax = gca()
ret = ax.set_xlim(*args, **kwargs)
draw_if_interactive()
return ret
def ylim(*args, **kwargs):
"""
Set/Get the ylimits of the current axes
ymin, ymax = ylim() : return the current ylim
ylim( (ymin, ymax) ) : set the ylim to ymin, ymax
ylim( ymin, ymax ) : set the ylim to ymin, ymax
If you do not specify args, you can pass the ymin and ymax as
kwargs, eg
ylim(ymax=3) # adjust the max leaving min unchanged
ylim(ymin=1) # adjust the min leaving max unchanged
The new axis limits are returned as a length 2 tuple
"""
ax = gca()
ret = ax.set_ylim(*args, **kwargs)
draw_if_interactive()
return ret
def xticks(*args, **kwargs):
"""
Set/Get the xlimits of the current ticklocs, labels
# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = xticks()
# set the locations of the xticks
xticks( arange(6) )
# set the locations and labels of the xticks
xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )
The keyword args, if any, are text properties; see text for more
information on text properties.
"""
ax = gca()
if len(args)==0:
locs = ax.get_xticks()
labels = ax.get_xticklabels()
elif len(args)==1:
locs = ax.set_xticks(args[0])
labels = ax.get_xticklabels()
elif len(args)==2:
locs = ax.set_xticks(args[0])
labels = ax.set_xticklabels(args[1], **kwargs)
else: raise TypeError('Illegal number of arguments to xticks')
if len(kwargs):
for l in labels:
l.update(kwargs)
draw_if_interactive()
return locs, silent_list('Text xticklabel', labels)
def yticks(*args, **kwargs):
"""
Set/Get the ylimits of the current ticklocs, labels
# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = yticks()
# set the locations of the yticks
yticks( arange(6) )
# set the locations and labels of the yticks
yticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )
The keyword args, if any, are text properties; see text for more
information on text properties.
"""
ax = gca()
if len(args)==0:
locs = ax.get_yticks()
labels = ax.get_yticklabels()
elif len(args)==1:
locs = ax.set_yticks(args[0])
labels = ax.get_yticklabels()
elif len(args)==2:
locs = ax.set_yticks(args[0])
labels = ax.set_yticklabels(args[1], **kwargs)
else: raise TypeError('Illegal number of arguments to yticks')
if len(kwargs):
for l in labels:
l.update(kwargs)
draw_if_interactive()
return ( locs,
silent_list('Text yticklabel', labels)
)
def rgrids(*args, **kwargs):
"""
Set/Get the radial locations of the gridlines and ticklabels
With no args, simply return lines, labels where lines is an
array of radial gridlines (Line2D instances) and labels is an
array of tick labels (Text instances).
lines, labels = rgrids()
With arguments, the syntax is
lines, labels = RGRIDS(radii, labels=None, angle=22.5, **kwargs)
The labels will appear at radial distances radii at angle
labels, if not None, is a len(radii) list of strings of the
labels to use at each angle.
if labels is None, the self.rformatter will be used
Return value is a list of lines, labels where the lines are
matplotlib.Line2D instances and the labels are matplotlib.Text
instances. Note that on input the labels argument is a list of
strings, and on output it is a list of Text instances
Examples
# set the locations of the radial gridlines and labels
lines, labels = rgrids( (0.25, 0.5, 1.0) )
# set the locations and labels of the radial gridlines and labels
lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' )
"""
ax = gca()
if not isinstance(ax, PolarAxes):
raise RuntimeError('rgrids only defined for polar axes')
if len(args)==0:
lines = ax.rgridlines()
labels = ax.rgridlabels()
else:
lines, labels = ax.set_rgrids(*args, **kwargs)
draw_if_interactive()
return ( silent_list('Line2D rgridline', lines),
silent_list('Text rgridlabel', labels) )
def thetagrids(*args, **kwargs):
"""
Set/Get the theta locations of the gridlines and ticklabels
If no arguments are passed, return lines, labels where lines is an
array of radial gridlines (Line2D instances) and labels is an
array of tick labels (Text instances).
lines, labels = thetagrids()
Otherwise the syntax is
lines, labels = THETAGRIDS(angles, labels=None, fmt='%d', frac = 1.1)
set the angles at which to place the theta grids (these gridlines
are equal along the theta dimension). angles is in degrees
labels, if not None, is a len(angles) list of strings of the
labels to use at each angle.
if labels is None, the labels with be fmt%angle
frac is the fraction of the polar axes radius at which to place
the label (1 is the edge).Eg 1.05 isd outside the axes and 0.95
is inside the axes
Return value is a list of lines, labels where the lines are
matplotlib.Line2D instances and the labels are matplotlib.Text
instances. Note that on input the labels argument is a list of
strings, and on output it is a list of Text instances
Examples:
# set the locations of the radial gridlines and labels
lines, labels = thetagrids( range(45,360,90) )
# set the locations and labels of the radial gridlines and labels
lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )
"""
ax = gca()
if not isinstance(ax, PolarAxes):
raise RuntimeError('rgrids only defined for polar axes')
if len(args)==0:
lines = ax.thetagridlines()
labels = ax.thetagridlabels()
else:
lines, labels = ax.set_thetagrids(*args, **kwargs)
draw_if_interactive()
return (silent_list('Line2D thetagridline', lines),
silent_list('Text thetagridlabel', labels)
)
## Plotting Info ##
def plotting():
"""
Plotting commands
axes - Create a new axes
axis - Set or return the current axis limits
bar - make a bar chart
boxplot - make a box and whiskers chart
cla - clear current axes
clabel - label a contour plot
clf - clear a figure window
close - close a figure window
colorbar - add a colorbar to the current figure
cohere - make a plot of coherence
contour - make a contour plot
contourf - make a filled contour plot
csd - make a plot of cross spectral density
draw - force a redraw of the current figure
errorbar - make an errorbar graph
figlegend - add a legend to the figure
figimage - add an image to the figure, w/o resampling
figtext - add text in figure coords
figure - create or change active figure
fill - make filled polygons
gca - return the current axes
gcf - return the current figure
gci - get the current image, or None
get - get a handle graphics property
hist - make a histogram
hold - set the hold state on current axes
legend - add a legend to the axes
loglog - a log log plot
imread - load image file into array
imshow - plot image data
matshow - display a matrix in a new figure preserving aspect
pcolor - make a pseudocolor plot
plot - make a line plot
plotfile - plot data from a flat file
psd - make a plot of power spectral density
quiver - make a direction field (arrows) plot
rc - control the default params
savefig - save the current figure
scatter - make a scatter plot
set - set a handle graphics property
semilogx - log x axis
semilogy - log y axis
show - show the figures
specgram - a spectrogram plot
stem - make a stem plot
subplot - make a subplot (numrows, numcols, axesnum)
table - add a table to the axes
text - add some text at location x,y to the current axes
title - add a title to the current axes
xlabel - add an xlabel to the current axes
ylabel - add a ylabel to the current axes
autumn - set the default colormap to autumn
bone - set the default colormap to bone
cool - set the default colormap to cool
copper - set the default colormap to copper
flag - set the default colormap to flag
gray - set the default colormap to gray
hot - set the default colormap to hot
hsv - set the default colormap to hsv
jet - set the default colormap to jet
pink - set the default colormap to pink
prism - set the default colormap to prism
spring - set the default colormap to spring
summer - set the default colormap to summer
winter - set the default colormap to winter
spectral - set the default colormap to spectral
"""
pass
def get_plot_commands(): return ( 'axes', 'axis', 'bar', 'boxplot', 'cla', 'clf',
'close', 'colorbar', 'cohere', 'csd', 'draw', 'errorbar',
'figlegend', 'figtext', 'figimage', 'figure', 'fill', 'gca',
'gcf', 'gci', 'get', 'gray', 'barh', 'jet', 'hist', 'hold', 'imread',
'imshow', 'legend', 'loglog', 'quiver', 'rc', 'pcolor', 'pcolormesh', 'plot', 'psd',
'savefig', 'scatter', 'set', 'semilogx', 'semilogy', 'show',
'specgram', 'stem', 'subplot', 'table', 'text', 'title', 'xlabel',
'ylabel', 'pie', 'polar')
def colors():
"""
This is a do nothing function to provide you with help on how
matplotlib handles colors.
Commands which take color arguments can use several formats to