forked from matplotlib/matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaxes.py
More file actions
5697 lines (4530 loc) · 198 KB
/
axes.py
File metadata and controls
5697 lines (4530 loc) · 198 KB
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
from __future__ import division, generators
import math, warnings, new
import numpy as npy
import matplotlib.numerix.npyma as ma
import matplotlib
rcParams = matplotlib.rcParams
from matplotlib import artist as martist
from matplotlib import axis as maxis
from matplotlib import cbook
from matplotlib import collections as mcoll
from matplotlib import colors as mcolors
from matplotlib import contour as mcontour
from matplotlib import dates as mdates
from matplotlib import font_manager
from matplotlib import image as mimage
from matplotlib import legend as mlegend
from matplotlib import lines as mlines
from matplotlib import mlab
from matplotlib import patches as mpatches
from matplotlib import quiver as mquiver
from matplotlib import scale as mscale
from matplotlib import table as mtable
from matplotlib import text as mtext
from matplotlib import ticker as mticker
from matplotlib import transforms as mtransforms
iterable = cbook.iterable
is_string_like = cbook.is_string_like
def delete_masked_points(*args):
"""
Find all masked points in a set of arguments, and return
the arguments with only the unmasked points remaining.
The overall mask is calculated from any masks that are present.
If a mask is found, any argument that does not have the same
dimensions is left unchanged; therefore the argument list may
include arguments that can take string or array values, for
example.
Array arguments must have the same length; masked arguments must
be one-dimensional.
Written as a helper for scatter, but may be more generally
useful.
"""
masks = [ma.getmaskarray(x) for x in args if hasattr(x, 'mask')]
if len(masks) == 0:
return args
mask = reduce(ma.mask_or, masks)
margs = []
for x in args:
if (not is_string_like(x)
and iterable(x)
and len(x) == len(mask)):
if (hasattr(x, 'get_compressed_copy')):
compressed_x = x.get_compressed_copy(mask)
else:
compressed_x = ma.masked_array(x, mask=mask).compressed()
margs.append(compressed_x)
else:
margs.append(x)
return margs
def _process_plot_format(fmt):
"""
Process a matlab(TM) style color/line style format string. Return a
linestyle, color tuple as a result of the processing. Default
values are ('-', 'b'). Example format strings include
'ko' : black circles
'.b' : blue dots
'r--' : red dashed lines
See Line2D.lineStyles and GraphicsContext.colors for all possible
styles and color format string.
"""
linestyle = None
marker = None
color = None
# Is fmt just a colorspec?
try:
color = mcolors.colorConverter.to_rgb(fmt)
return linestyle, marker, color # Yes.
except ValueError:
pass # No, not just a color.
# handle the multi char special cases and strip them from the
# string
if fmt.find('--')>=0:
linestyle = '--'
fmt = fmt.replace('--', '')
if fmt.find('-.')>=0:
linestyle = '-.'
fmt = fmt.replace('-.', '')
if fmt.find(' ')>=0:
linestyle = 'None'
fmt = fmt.replace(' ', '')
chars = [c for c in fmt]
for c in chars:
if mlines.lineStyles.has_key(c):
if linestyle is not None:
raise ValueError(
'Illegal format string "%s"; two linestyle symbols' % fmt)
linestyle = c
elif mlines.lineMarkers.has_key(c):
if marker is not None:
raise ValueError(
'Illegal format string "%s"; two marker symbols' % fmt)
marker = c
elif mcolors.colorConverter.colors.has_key(c):
if color is not None:
raise ValueError(
'Illegal format string "%s"; two color symbols' % fmt)
color = c
else:
raise ValueError(
'Unrecognized character %c in format string' % c)
if linestyle is None and marker is None:
linestyle = rcParams['lines.linestyle']
if linestyle is None:
linestyle = 'None'
if marker is None:
marker = 'None'
return linestyle, marker, color
class _process_plot_var_args:
"""
Process variable length arguments to the plot command, so that
plot commands like the following are supported
plot(t, s)
plot(t1, s1, t2, s2)
plot(t1, s1, 'ko', t2, s2)
plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
an arbitrary number of x, y, fmt are allowed
"""
def __init__(self, axes, command='plot'):
self.axes = axes
self.command = command
self._clear_color_cycle()
def _clear_color_cycle(self):
self.colors = ['b','g','r','c','m','y','k']
# if the default line color is a color format string, move it up
# in the que
try: ind = self.colors.index(rcParams['lines.color'])
except ValueError:
self.firstColor = rcParams['lines.color']
else:
self.colors[0], self.colors[ind] = self.colors[ind], self.colors[0]
self.firstColor = self.colors[0]
self.Ncolors = len(self.colors)
self.count = 0
def _get_next_cycle_color(self):
if self.count==0:
color = self.firstColor
else:
color = self.colors[int(self.count % self.Ncolors)]
self.count += 1
return color
def __call__(self, *args, **kwargs):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
xunits = kwargs.pop( 'xunits', self.axes.xaxis.units)
yunits = kwargs.pop( 'yunits', self.axes.yaxis.units)
if xunits!=self.axes.xaxis.units:
self.axes.xaxis.set_units(xunits)
if yunits!=self.axes.yaxis.units:
self.axes.yaxis.set_units(yunits)
ret = self._grab_next_args(*args, **kwargs)
return ret
def set_lineprops(self, line, **kwargs):
assert self.command == 'plot', 'set_lineprops only works with "plot"'
for key, val in kwargs.items():
funcName = "set_%s"%key
if not hasattr(line,funcName):
raise TypeError, 'There is no line property "%s"'%key
func = getattr(line,funcName)
func(val)
def set_patchprops(self, fill_poly, **kwargs):
assert self.command == 'fill', 'set_patchprops only works with "fill"'
for key, val in kwargs.items():
funcName = "set_%s"%key
if not hasattr(fill_poly,funcName):
raise TypeError, 'There is no patch property "%s"'%key
func = getattr(fill_poly,funcName)
func(val)
def _xy_from_y(self, y):
if self.axes.yaxis is not None:
b = self.axes.yaxis.update_units(y)
if b: return npy.arange(len(y)), y, False
y = ma.asarray(y)
if len(y.shape) == 1:
y = y[:,npy.newaxis]
nr, nc = y.shape
x = npy.arange(nr)
if len(x.shape) == 1:
x = x[:,npy.newaxis]
return x,y, True
def _xy_from_xy(self, x, y):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
bx = self.axes.xaxis.update_units(x)
by = self.axes.yaxis.update_units(y)
# right now multicol is not supported if either x or y are
# unit enabled but this can be fixed..
if bx or by: return x, y, False
x = ma.asarray(x)
y = ma.asarray(y)
if len(x.shape) == 1:
x = x[:,npy.newaxis]
if len(y.shape) == 1:
y = y[:,npy.newaxis]
nrx, ncx = x.shape
nry, ncy = y.shape
assert nrx == nry, 'Dimensions of x and y are incompatible'
if ncx == ncy:
return x, y, True
if ncx == 1:
x = npy.repeat(x, ncy, axis=1)
if ncy == 1:
y = npy.repeat(y, ncx, axis=1)
assert x.shape == y.shape, 'Dimensions of x and y are incompatible'
return x, y, True
def _plot_1_arg(self, y, **kwargs):
assert self.command == 'plot', 'fill needs at least 2 arguments'
ret = []
x, y, multicol = self._xy_from_y(y)
if multicol:
for j in range(y.shape[1]):
color = self._get_next_cycle_color()
seg = mlines.Line2D(x, y[:,j],
color = color,
axes=self.axes,
)
self.set_lineprops(seg, **kwargs)
ret.append(seg)
else:
color = self._get_next_cycle_color()
seg = mlines.Line2D(x, y,
color = color,
axes=self.axes,
)
self.set_lineprops(seg, **kwargs)
ret.append(seg)
return ret
def _plot_2_args(self, tup2, **kwargs):
ret = []
if is_string_like(tup2[1]):
assert self.command == 'plot', 'fill needs at least 2 non-string arguments'
y, fmt = tup2
x, y, multicol = self._xy_from_y(y)
linestyle, marker, color = _process_plot_format(fmt)
def makeline(x, y):
_color = color
if _color is None:
_color = self._get_next_cycle_color()
seg = mlines.Line2D(x, y,
color=_color,
linestyle=linestyle, marker=marker,
axes=self.axes,
)
self.set_lineprops(seg, **kwargs)
ret.append(seg)
if multicol:
for j in range(y.shape[1]):
makeline(x[:,j], y[:,j])
else:
makeline(x, y)
return ret
else:
x, y = tup2
x, y, multicol = self._xy_from_xy(x, y)
def makeline(x, y):
color = self._get_next_cycle_color()
seg = mlines.Line2D(x, y,
color=color,
axes=self.axes,
)
self.set_lineprops(seg, **kwargs)
ret.append(seg)
def makefill(x, y):
facecolor = self._get_next_cycle_color()
seg = mpatches.Polygon(zip(x, y),
facecolor = facecolor,
fill=True,
)
self.set_patchprops(seg, **kwargs)
ret.append(seg)
if self.command == 'plot': func = makeline
else: func = makefill
if multicol:
for j in range(y.shape[1]):
func(x[:,j], y[:,j])
else:
func(x, y)
return ret
def _plot_3_args(self, tup3, **kwargs):
ret = []
x, y, fmt = tup3
x, y, multicol = self._xy_from_xy(x, y)
linestyle, marker, color = _process_plot_format(fmt)
def makeline(x, y):
_color = color
if _color is None:
_color = self._get_next_cycle_color()
seg = mlines.Line2D(x, y,
color=_color,
linestyle=linestyle, marker=marker,
axes=self.axes,
)
self.set_lineprops(seg, **kwargs)
ret.append(seg)
def makefill(x, y):
facecolor = color
seg = mpatches.Polygon(zip(x, y),
facecolor = facecolor,
fill=True,
)
self.set_patchprops(seg, **kwargs)
ret.append(seg)
if self.command == 'plot': func = makeline
else: func = makefill
if multicol:
for j in range(y.shape[1]):
func(x[:,j], y[:,j])
else:
func(x, y)
return ret
def _grab_next_args(self, *args, **kwargs):
remaining = args
while 1:
if len(remaining)==0: return
if len(remaining)==1:
for seg in self._plot_1_arg(remaining[0], **kwargs):
yield seg
remaining = []
continue
if len(remaining)==2:
for seg in self._plot_2_args(remaining, **kwargs):
yield seg
remaining = []
continue
if len(remaining)==3:
if not is_string_like(remaining[2]):
raise ValueError, 'third arg must be a format string'
for seg in self._plot_3_args(remaining, **kwargs):
yield seg
remaining=[]
continue
if is_string_like(remaining[2]):
for seg in self._plot_3_args(remaining[:3], **kwargs):
yield seg
remaining=remaining[3:]
else:
for seg in self._plot_2_args(remaining[:2], **kwargs):
yield seg
remaining=remaining[2:]
class Axes(martist.Artist):
"""
The Axes contains most of the figure elements: Axis, Tick, Line2D,
Text, Polygon etc, and sets the coordinate system
The Axes instance supports callbacks through a callbacks attribute
which is a cbook.CallbackRegistry instance. The events you can
connect to are 'xlim_changed' and 'ylim_changed' and the callback
will be called with func(ax) where ax is the Axes instance
"""
name = "rectilinear"
_shared_x_axes = cbook.Grouper()
_shared_y_axes = cbook.Grouper()
def __str__(self):
return "Axes(%g,%g;%gx%g)" % tuple(self._position.bounds)
def __init__(self, fig, rect,
axisbg = None, # defaults to rc axes.facecolor
frameon = True,
sharex=None, # use Axes instance's xaxis info
sharey=None, # use Axes instance's yaxis info
label='',
**kwargs
):
"""
Build an Axes instance in Figure with
rect=[left, bottom, width,height in Figure coords
adjustable: ['box' | 'datalim']
alpha: the alpha transparency
anchor: ['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W']
aspect: ['auto' | 'equal' | aspect_ratio]
autoscale_on: boolean - whether or not to autoscale the viewlim
axis_bgcolor: any matplotlib color - see help(colors)
axisbelow: draw the grids and ticks below the other artists
cursor_props: a (float, color) tuple
figure: a Figure instance
frame_on: a boolean - draw the axes frame
label: the axes label
navigate: True|False
navigate_mode: the navigation toolbar button status: 'PAN', 'ZOOM', or None
position: [left, bottom, width,height in Figure coords
sharex: an Axes instance to share the x-axis with
sharey: an Axes instance to share the y-axis with
title: the title string
visible: a boolean - whether the axes is visible
xlabel: the xlabel
xlim: (xmin, xmax) view limits
xscale: [%(scale)s]
xticklabels: sequence of strings
xticks: sequence of floats
ylabel: the ylabel strings
ylim: (ymin, ymax) view limits
yscale: [%(scale)s]
yticklabels: sequence of strings
yticks: sequence of floats
""" % {'scale': ' | '.join([repr(x) for x in mscale.get_scale_names()])}
martist.Artist.__init__(self)
if isinstance(rect, mtransforms.Bbox):
self._position = rect
else:
self._position = mtransforms.Bbox.from_bounds(*rect)
self._originalPosition = self._position.frozen()
self.set_axes(self)
self.set_aspect('auto')
self.set_adjustable('box')
self.set_anchor('C')
self._sharex = sharex
self._sharey = sharey
if sharex is not None:
self._shared_x_axes.join(self, sharex)
if sharey is not None:
self._shared_y_axes.join(self, sharey)
self.set_label(label)
self.set_figure(fig)
# this call may differ for non-sep axes, eg polar
self._init_axis()
if axisbg is None: axisbg = rcParams['axes.facecolor']
self._axisbg = axisbg
self._frameon = frameon
self._axisbelow = rcParams['axes.axisbelow']
self._hold = rcParams['axes.hold']
self._connected = {} # a dict from events to (id, func)
self.cla()
# funcs used to format x and y - fall back on major formatters
self.fmt_xdata = None
self.fmt_ydata = None
self.set_cursor_props((1,'k')) # set the cursor properties for axes
self._cachedRenderer = None
self.set_navigate(True)
self.set_navigate_mode(None)
if len(kwargs): martist.setp(self, **kwargs)
if self.xaxis is not None:
self._xcid = self.xaxis.callbacks.connect('units finalize', self.relim)
if self.yaxis is not None:
self._ycid = self.yaxis.callbacks.connect('units finalize', self.relim)
def get_window_extent(self, *args, **kwargs):
'get the axes bounding box in display space; args and kwargs are empty'
return self.bbox
def _init_axis(self):
"move this out of __init__ because non-separable axes don't use it"
self.xaxis = maxis.XAxis(self)
self.yaxis = maxis.YAxis(self)
self._update_transScale()
def set_figure(self, fig):
"""
Set the Axes figure
ACCEPTS: a Figure instance
"""
martist.Artist.set_figure(self, fig)
self.bbox = mtransforms.TransformedBbox(self._position, fig.transFigure)
#these will be updated later as data is added
self._set_lim_and_transforms()
def _set_lim_and_transforms(self):
"""
set the dataLim and viewLim BBox attributes and the
transScale, transData, transLimits and transAxes
transformations.
"""
self.dataLim = mtransforms.Bbox.unit()
self.viewLim = mtransforms.Bbox.unit()
self.transAxes = mtransforms.BboxTransformTo(self.bbox)
# Transforms the x and y axis separately by a scale factor
# It is assumed that this part will have non-linear components
self.transScale = mtransforms.TransformWrapper(mtransforms.IdentityTransform())
# An affine transformation on the data, generally to limit the
# range of the axes
self.transLimits = mtransforms.BboxTransformFrom(
mtransforms.TransformedBbox(self.viewLim, self.transScale))
# The parentheses are important for efficiency here -- they
# group the last two (which are usually affines) separately
# from the first (which, with log-scaling can be non-affine).
self.transData = self.transScale + (self.transLimits + self.transAxes)
self._xaxis_transform = mtransforms.blended_transform_factory(
self.axes.transData, self.axes.transAxes)
self._yaxis_transform = mtransforms.blended_transform_factory(
self.axes.transAxes, self.axes.transData)
def get_xaxis_transform(self):
"""
Get the transformation used for drawing x-axis labels, ticks
and gridlines. The x-direction is in data coordinates and the
y-direction is in axis coordinates.
This transformation is primarily used by the Axis class, and
is meant to be overridden by new kinds of projections that may
need to place axis elements in different locations.
"""
return self._xaxis_transform
def get_xaxis_text1_transform(self, pad_pixels):
"""
Get the transformation used for drawing x-axis labels, which
will add the given number of pad_pixels between the axes and
the label. The x-direction is in data coordinates and the
y-direction is in axis coordinates. Returns a 3-tuple of the
form:
(transform, valign, halign)
where valign and halign are requested alignments for the text.
This transformation is primarily used by the Axis class, and
is meant to be overridden by new kinds of projections that may
need to place axis elements in different locations.
"""
return (self._xaxis_transform +
mtransforms.Affine2D().translate(0, -1 * pad_pixels),
"top", "center")
def get_xaxis_text2_transform(self, pad_pixels):
"""
Get the transformation used for drawing the secondary x-axis
labels, which will add the given number of pad_pixels between
the axes and the label. The x-direction is in data
coordinates and the y-direction is in axis coordinates.
Returns a 3-tuple of the form:
(transform, valign, halign)
where valign and halign are requested alignments for the text.
This transformation is primarily used by the Axis class, and
is meant to be overridden by new kinds of projections that may
need to place axis elements in different locations.
"""
return (self._xaxis_transform +
mtransforms.Affine2D().translate(0, pad_pixels),
"bottom", "center")
def get_yaxis_transform(self):
"""
Get the transformation used for drawing y-axis labels, ticks
and gridlines. The x-direction is in axis coordinates and the
y-direction is in data coordinates.
This transformation is primarily used by the Axis class, and
is meant to be overridden by new kinds of projections that may
need to place axis elements in different locations.
"""
return self._yaxis_transform
def get_yaxis_text1_transform(self, pad_pixels):
"""
Get the transformation used for drawing y-axis labels, which
will add the given number of pad_pixels between the axes and
the label. The x-direction is in axis coordinates and the
y-direction is in data coordinates. Returns a 3-tuple of the
form:
(transform, valign, halign)
where valign and halign are requested alignments for the text.
This transformation is primarily used by the Axis class, and
is meant to be overridden by new kinds of projections that may
need to place axis elements in different locations.
"""
return (self._yaxis_transform +
mtransforms.Affine2D().translate(-1 * pad_pixels, 0),
"center", "right")
def get_yaxis_text2_transform(self, pad_pixels):
"""
Get the transformation used for drawing the secondary y-axis
labels, which will add the given number of pad_pixels between
the axes and the label. The x-direction is in axis
coordinates and the y-direction is in data coordinates.
Returns a 3-tuple of the form:
(transform, valign, halign)
where valign and halign are requested alignments for the text.
This transformation is primarily used by the Axis class, and
is meant to be overridden by new kinds of projections that may
need to place axis elements in different locations.
"""
return (self._yaxis_transform +
mtransforms.Affine2D().translate(pad_pixels, 0),
"center", "left")
def _update_transScale(self):
self.transScale.set(
mtransforms.blended_transform_factory(
self.xaxis.get_transform(), self.yaxis.get_transform()))
def get_position(self, original=False):
'Return the a copy of the axes rectangle as a Bbox'
if original:
return self._originalPosition.frozen()
else:
return self._position.frozen()
def set_position(self, pos, which='both'):
"""
Set the axes position with pos = [left, bottom, width, height]
in relative 0,1 coords
There are two position variables: one which is ultimately
used, but which may be modified by apply_aspect, and a second
which is the starting point for apply_aspect.
which = 'active' to change the first;
'original' to change the second;
'both' to change both
ACCEPTS: len(4) sequence of floats, or a Bbox object
"""
if not isinstance(pos, mtransforms.BboxBase):
pos = mtransforms.Bbox.from_bounds(*pos)
if which in ('both', 'active'):
self._position.set(pos)
if which in ('both', 'original'):
self._originalPosition.set(pos)
def _set_artist_props(self, a):
'set the boilerplate props for artists added to axes'
a.set_figure(self.figure)
if not a.is_transform_set():
a.set_transform(self.transData)
a.axes = self
def get_axes_patch(self):
"""
Returns the patch used to draw the background of the axes. It
is also used as the clipping path for any data elements on the
axes.
In the standard axes, this is a rectangle, but in other
projections it may not be.
Intended to be overridden by new projection types.
"""
return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0)
def cla(self):
'Clear the current axes'
self.xaxis.cla()
self.yaxis.cla()
self.set_xscale('linear')
self.set_yscale('linear')
self.ignore_existing_data_limits = True
self.callbacks = cbook.CallbackRegistry(('xlim_changed', 'ylim_changed'))
if self._sharex is not None:
self.xaxis.major = self._sharex.xaxis.major
self.xaxis.minor = self._sharex.xaxis.minor
if self._sharey is not None:
self.yaxis.major = self._sharey.yaxis.major
self.yaxis.minor = self._sharey.yaxis.minor
self._get_lines = _process_plot_var_args(self)
self._get_patches_for_fill = _process_plot_var_args(self, 'fill')
self._gridOn = rcParams['axes.grid']
self.lines = []
self.patches = []
self.texts = []
self.tables = []
self.artists = []
self.images = []
self.legend_ = None
self.collections = [] # collection.Collection instances
self._autoscaleon = True
self.grid(self._gridOn)
props = font_manager.FontProperties(size=rcParams['axes.titlesize'])
self.titleOffsetTrans = mtransforms.Affine2D().translate(0.0, 10.0)
self.title = mtext.Text(
x=0.5, y=1.0, text='',
fontproperties=props,
verticalalignment='bottom',
horizontalalignment='center',
)
self.title.set_transform(self.transAxes + self.titleOffsetTrans)
self.title.set_clip_box(None)
self._set_artist_props(self.title)
self.axesPatch = self.get_axes_patch()
self.axesPatch.set_figure(self.figure)
self.axesPatch.set_facecolor(self._axisbg)
self.axesPatch.set_edgecolor(rcParams['axes.edgecolor'])
self.axesPatch.set_linewidth(rcParams['axes.linewidth'])
self.axesPatch.set_transform(self.transAxes)
self.axesFrame = self.get_axes_patch()
self.axesFrame.set_figure(self.figure)
self.axesFrame.set_facecolor(None)
self.axesFrame.set_edgecolor(rcParams['axes.edgecolor'])
self.axesFrame.set_linewidth(rcParams['axes.linewidth'])
self.axesFrame.set_transform(self.transAxes)
self.axesFrame.set_zorder(2.5)
self.axison = True
self.xaxis.set_clip_path(self.axesPatch)
self.yaxis.set_clip_path(self.axesPatch)
self.titleOffsetTrans.clear()
def clear(self):
'clear the axes'
self.cla()
def ishold(self):
'return the HOLD status of the axes'
return self._hold
def hold(self, b=None):
"""
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
"""
if b is None: self._hold = not self._hold
else: self._hold = b
def get_aspect(self):
return self._aspect
def set_aspect(self, aspect, adjustable=None, anchor=None):
"""
aspect:
'auto' - automatic; fill position rectangle with data
'normal' - same as 'auto'; deprecated
'equal' - same scaling from data to plot units for x and y
num - a circle will be stretched such that the height
is num times the width. aspect=1 is the same as
aspect='equal'.
adjustable:
'box' - change physical size of axes
'datalim' - change xlim or ylim
anchor:
'C' - centered
'SW' - lower left corner
'S' - middle of bottom edge
'SE' - lower right corner
etc.
ACCEPTS: ['auto' | 'equal' | aspect_ratio]
"""
if aspect in ('normal', 'auto'):
self._aspect = 'auto'
elif aspect == 'equal':
self._aspect = 'equal'
else:
self._aspect = float(aspect) # raise ValueError if necessary
if adjustable is not None:
self.set_adjustable(adjustable)
if anchor is not None:
self.set_anchor(anchor)
def get_adjustable(self):
return self._adjustable
def set_adjustable(self, adjustable):
"""
ACCEPTS: ['box' | 'datalim']
"""
if adjustable in ('box', 'datalim'):
self._adjustable = adjustable
else:
raise ValueError('argument must be "box", or "datalim"')
def get_anchor(self):
return self._anchor
def set_anchor(self, anchor):
"""
ACCEPTS: ['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W']
"""
if anchor in mtransforms.Bbox.coefs.keys() or len(anchor) == 2:
self._anchor = anchor
else:
raise ValueError('argument must be among %s' %
', '.join(mtransforms.BBox.coefs.keys()))
def get_data_ratio(self):
"""
Returns the aspect ratio of the raw data.
This method is intended to be overridden by new projection
types.
"""
xmin,xmax = self.get_xbound()
xsize = max(math.fabs(xmax-xmin), 1e-30)
ymin,ymax = self.get_ybound()
ysize = max(math.fabs(ymax-ymin), 1e-30)
return ysize/xsize
def apply_aspect(self, position):
'''
Use self._aspect and self._adjustable to modify the
axes box or the view limits.
'''
aspect = self.get_aspect()
if aspect == 'auto':
self.set_position( position , 'active')
return
if aspect == 'equal':
A = 1
else:
A = aspect
#Ensure at drawing time that any Axes involved in axis-sharing
# does not have its position changed.
if self in self._shared_x_axes or self in self._shared_y_axes:
self._adjustable = 'datalim'
figW,figH = self.get_figure().get_size_inches()
fig_aspect = figH/figW
if self._adjustable == 'box':
box_aspect = A * self.get_data_ratio()
pb = position.frozen()
pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)
self.set_position(pb1.anchored(self.get_anchor(), pb), 'active')
return
xmin,xmax = self.get_xbound()
xsize = max(math.fabs(xmax-xmin), 1e-30)
ymin,ymax = self.get_ybound()
ysize = max(math.fabs(ymax-ymin), 1e-30)
l,b,w,h = position.bounds
box_aspect = fig_aspect * (h/w)
data_ratio = box_aspect / A
y_expander = (data_ratio*xsize/ysize - 1.0)
#print 'y_expander', y_expander
# If y_expander > 0, the dy/dx viewLim ratio needs to increase
if abs(y_expander) < 0.005:
#print 'good enough already'
return
dL = self.dataLim
xr = 1.05 * dL.width
yr = 1.05 * dL.height
xmarg = xsize - xr
ymarg = ysize - yr
Ysize = data_ratio * xsize
Xsize = ysize / data_ratio
Xmarg = Xsize - xr
Ymarg = Ysize - yr
xm = 0 # Setting these targets to, e.g., 0.05*xr does not seem to help.
ym = 0
#print 'xmin, xmax, ymin, ymax', xmin, xmax, ymin, ymax
#print 'xsize, Xsize, ysize, Ysize', xsize, Xsize, ysize, Ysize
changex = (self in self._shared_y_axes
and self not in self._shared_x_axes)
changey = (self in self._shared_x_axes
and self not in self._shared_y_axes)
if changex and changey:
warnings.warn("adjustable='datalim' cannot work with shared x and y axes")
return
if changex:
adjust_y = False
else:
#print 'xmarg, ymarg, Xmarg, Ymarg', xmarg, ymarg, Xmarg, Ymarg
if xmarg > xm and ymarg > ym:
adjy = ((Ymarg > 0 and y_expander < 0)
or (Xmarg < 0 and y_expander > 0))
else:
adjy = y_expander > 0
#print 'y_expander, adjy', y_expander, adjy
adjust_y = changey or adjy #(Ymarg > xmarg)
if adjust_y:
yc = 0.5*(ymin+ymax)
y0 = yc - Ysize/2.0
y1 = yc + Ysize/2.0
self.set_ybound((y0, y1))
#print 'New y0, y1:', y0, y1
#print 'New ysize, ysize/xsize', y1-y0, (y1-y0)/xsize
else:
xc = 0.5*(xmin+xmax)
x0 = xc - Xsize/2.0
x1 = xc + Xsize/2.0
self.set_xbound((x0, x1))
#print 'New x0, x1:', x0, x1
#print 'New xsize, ysize/xsize', x1-x0, ysize/(x1-x0)