/
contour.py
1902 lines (1610 loc) · 74.7 KB
/
contour.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
"""
Classes to support contour plotting and labelling for the Axes class.
"""
from contextlib import ExitStack
import functools
import math
from numbers import Integral
import numpy as np
from numpy import ma
import matplotlib as mpl
from matplotlib import _api, _docstring
from matplotlib.backend_bases import MouseButton
from matplotlib.lines import Line2D
from matplotlib.path import Path
from matplotlib.text import Text
import matplotlib.ticker as ticker
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.collections as mcoll
import matplotlib.font_manager as font_manager
import matplotlib.cbook as cbook
import matplotlib.patches as mpatches
import matplotlib.transforms as mtransforms
@_api.deprecated("3.7", alternative="Text.set_transform_rotates_text")
class ClabelText(Text):
"""
Unlike the ordinary text, the get_rotation returns an updated
angle in the pixel coordinate assuming that the input rotation is
an angle in data coordinate (or whatever transform set).
"""
def get_rotation(self):
new_angle, = self.get_transform().transform_angles(
[super().get_rotation()], [self.get_position()])
return new_angle
def _contour_labeler_event_handler(cs, inline, inline_spacing, event):
canvas = cs.axes.figure.canvas
is_button = event.name == "button_press_event"
is_key = event.name == "key_press_event"
# Quit (even if not in infinite mode; this is consistent with
# MATLAB and sometimes quite useful, but will require the user to
# test how many points were actually returned before using data).
if (is_button and event.button == MouseButton.MIDDLE
or is_key and event.key in ["escape", "enter"]):
canvas.stop_event_loop()
# Pop last click.
elif (is_button and event.button == MouseButton.RIGHT
or is_key and event.key in ["backspace", "delete"]):
# Unfortunately, if one is doing inline labels, then there is currently
# no way to fix the broken contour - once humpty-dumpty is broken, he
# can't be put back together. In inline mode, this does nothing.
if not inline:
cs.pop_label()
canvas.draw()
# Add new click.
elif (is_button and event.button == MouseButton.LEFT
# On macOS/gtk, some keys return None.
or is_key and event.key is not None):
if cs.axes.contains(event)[0]:
cs.add_label_near(event.x, event.y, transform=False,
inline=inline, inline_spacing=inline_spacing)
canvas.draw()
class ContourLabeler:
"""Mixin to provide labelling capability to `.ContourSet`."""
def clabel(self, levels=None, *,
fontsize=None, inline=True, inline_spacing=5, fmt=None,
colors=None, use_clabeltext=False, manual=False,
rightside_up=True, zorder=None):
"""
Label a contour plot.
Adds labels to line contours in this `.ContourSet` (which inherits from
this mixin class).
Parameters
----------
levels : array-like, optional
A list of level values, that should be labeled. The list must be
a subset of ``cs.levels``. If not given, all levels are labeled.
fontsize : str or float, default: :rc:`font.size`
Size in points or relative size e.g., 'smaller', 'x-large'.
See `.Text.set_size` for accepted string values.
colors : color or colors or None, default: None
The label colors:
- If *None*, the color of each label matches the color of
the corresponding contour.
- If one string color, e.g., *colors* = 'r' or *colors* =
'red', all labels will be plotted in this color.
- If a tuple of colors (string, float, RGB, etc), different labels
will be plotted in different colors in the order specified.
inline : bool, default: True
If ``True`` the underlying contour is removed where the label is
placed.
inline_spacing : float, default: 5
Space in pixels to leave on each side of label when placing inline.
This spacing will be exact for labels at locations where the
contour is straight, less so for labels on curved contours.
fmt : `.Formatter` or str or callable or dict, optional
How the levels are formatted:
- If a `.Formatter`, it is used to format all levels at once, using
its `.Formatter.format_ticks` method.
- If a str, it is interpreted as a %-style format string.
- If a callable, it is called with one level at a time and should
return the corresponding label.
- If a dict, it should directly map levels to labels.
The default is to use a standard `.ScalarFormatter`.
manual : bool or iterable, default: False
If ``True``, contour labels will be placed manually using
mouse clicks. Click the first button near a contour to
add a label, click the second button (or potentially both
mouse buttons at once) to finish adding labels. The third
button can be used to remove the last label added, but
only if labels are not inline. Alternatively, the keyboard
can be used to select label locations (enter to end label
placement, delete or backspace act like the third mouse button,
and any other key will select a label location).
*manual* can also be an iterable object of (x, y) tuples.
Contour labels will be created as if mouse is clicked at each
(x, y) position.
rightside_up : bool, default: True
If ``True``, label rotations will always be plus
or minus 90 degrees from level.
use_clabeltext : bool, default: False
If ``True``, use `.Text.set_transform_rotates_text` to ensure that
label rotation is updated whenever the axes aspect changes.
zorder : float or None, default: ``(2 + contour.get_zorder())``
zorder of the contour labels.
Returns
-------
labels
A list of `.Text` instances for the labels.
"""
# clabel basically takes the input arguments and uses them to
# add a list of "label specific" attributes to the ContourSet
# object. These attributes are all of the form label* and names
# should be fairly self explanatory.
#
# Once these attributes are set, clabel passes control to the
# labels method (case of automatic label placement) or
# `BlockingContourLabeler` (case of manual label placement).
if fmt is None:
fmt = ticker.ScalarFormatter(useOffset=False)
fmt.create_dummy_axis()
self.labelFmt = fmt
self._use_clabeltext = use_clabeltext
# Detect if manual selection is desired and remove from argument list.
self.labelManual = manual
self.rightside_up = rightside_up
self._clabel_zorder = 2 + self.get_zorder() if zorder is None else zorder
if levels is None:
levels = self.levels
indices = list(range(len(self.cvalues)))
else:
levlabs = list(levels)
indices, levels = [], []
for i, lev in enumerate(self.levels):
if lev in levlabs:
indices.append(i)
levels.append(lev)
if len(levels) < len(levlabs):
raise ValueError(f"Specified levels {levlabs} don't match "
f"available levels {self.levels}")
self.labelLevelList = levels
self.labelIndiceList = indices
self._label_font_props = font_manager.FontProperties(size=fontsize)
if colors is None:
self.labelMappable = self
self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
else:
cmap = mcolors.ListedColormap(colors, N=len(self.labelLevelList))
self.labelCValueList = list(range(len(self.labelLevelList)))
self.labelMappable = cm.ScalarMappable(cmap=cmap,
norm=mcolors.NoNorm())
self.labelXYs = []
if np.iterable(manual):
for x, y in manual:
self.add_label_near(x, y, inline, inline_spacing)
elif manual:
print('Select label locations manually using first mouse button.')
print('End manual selection with second mouse button.')
if not inline:
print('Remove last label by clicking third mouse button.')
mpl._blocking_input.blocking_input_loop(
self.axes.figure, ["button_press_event", "key_press_event"],
timeout=-1, handler=functools.partial(
_contour_labeler_event_handler,
self, inline, inline_spacing))
else:
self.labels(inline, inline_spacing)
return cbook.silent_list('text.Text', self.labelTexts)
@_api.deprecated("3.7", alternative="cs.labelTexts[0].get_font()")
@property
def labelFontProps(self):
return self._label_font_props
@_api.deprecated("3.7", alternative=(
"[cs.labelTexts[0].get_font().get_size()] * len(cs.labelLevelList)"))
@property
def labelFontSizeList(self):
return [self._label_font_props.get_size()] * len(self.labelLevelList)
@_api.deprecated("3.7", alternative="cs.labelTexts")
@property
def labelTextsList(self):
return cbook.silent_list('text.Text', self.labelTexts)
def print_label(self, linecontour, labelwidth):
"""Return whether a contour is long enough to hold a label."""
return (len(linecontour) > 10 * labelwidth
or (len(linecontour)
and (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()))
def too_close(self, x, y, lw):
"""Return whether a label is already near this location."""
thresh = (1.2 * lw) ** 2
return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
for loc in self.labelXYs)
def _get_nth_label_width(self, nth):
"""Return the width of the *nth* label, in pixels."""
fig = self.axes.figure
renderer = fig._get_renderer()
return (Text(0, 0,
self.get_text(self.labelLevelList[nth], self.labelFmt),
figure=fig, fontproperties=self._label_font_props)
.get_window_extent(renderer).width)
@_api.deprecated("3.7", alternative="Artist.set")
def set_label_props(self, label, text, color):
"""Set the label properties - color, fontsize, text."""
label.set_text(text)
label.set_color(color)
label.set_fontproperties(self._label_font_props)
label.set_clip_box(self.axes.bbox)
def get_text(self, lev, fmt):
"""Get the text of the label."""
if isinstance(lev, str):
return lev
elif isinstance(fmt, dict):
return fmt.get(lev, '%1.3f')
elif callable(getattr(fmt, "format_ticks", None)):
return fmt.format_ticks([*self.labelLevelList, lev])[-1]
elif callable(fmt):
return fmt(lev)
else:
return fmt % lev
def locate_label(self, linecontour, labelwidth):
"""
Find good place to draw a label (relatively flat part of the contour).
"""
ctr_size = len(linecontour)
n_blocks = int(np.ceil(ctr_size / labelwidth)) if labelwidth > 1 else 1
block_size = ctr_size if n_blocks == 1 else int(labelwidth)
# Split contour into blocks of length ``block_size``, filling the last
# block by cycling the contour start (per `np.resize` semantics). (Due
# to cycling, the index returned is taken modulo ctr_size.)
xx = np.resize(linecontour[:, 0], (n_blocks, block_size))
yy = np.resize(linecontour[:, 1], (n_blocks, block_size))
yfirst = yy[:, :1]
ylast = yy[:, -1:]
xfirst = xx[:, :1]
xlast = xx[:, -1:]
s = (yfirst - yy) * (xlast - xfirst) - (xfirst - xx) * (ylast - yfirst)
l = np.hypot(xlast - xfirst, ylast - yfirst)
# Ignore warning that divide by zero throws, as this is a valid option
with np.errstate(divide='ignore', invalid='ignore'):
distances = (abs(s) / l).sum(axis=-1)
# Labels are drawn in the middle of the block (``hbsize``) where the
# contour is the closest (per ``distances``) to a straight line, but
# not `too_close()` to a preexisting label.
hbsize = block_size // 2
adist = np.argsort(distances)
# If all candidates are `too_close()`, go back to the straightest part
# (``adist[0]``).
for idx in np.append(adist, adist[0]):
x, y = xx[idx, hbsize], yy[idx, hbsize]
if not self.too_close(x, y, labelwidth):
break
return x, y, (idx * block_size + hbsize) % ctr_size
def _split_path_and_get_label_rotation(self, path, idx, screen_pos, lw, spacing=5):
"""
Prepare for insertion of a label at index *idx* of *path*.
Parameters
----------
path : Path
The path where the label will be inserted, in data space.
idx : int
The vertex index after which the label will be inserted.
screen_pos : (float, float)
The position where the label will be inserted, in screen space.
lw : float
The label width, in screen space.
spacing : float
Extra spacing around the label, in screen space.
Returns
-------
path : Path
The path, broken so that the label can be drawn over it.
angle : float
The rotation of the label.
Notes
-----
Both tasks are done together to avoid calculating path lengths multiple times,
which is relatively costly.
The method used here involves computing the path length along the contour in
pixel coordinates and then looking (label width / 2) away from central point to
determine rotation and then to break contour if desired. The extra spacing is
taken into account when breaking the path, but not when computing the angle.
"""
if hasattr(self, "_old_style_split_collections"):
vis = False
for coll in self._old_style_split_collections:
vis |= coll.get_visible()
coll.remove()
self.set_visible(vis)
del self._old_style_split_collections # Invalidate them.
xys = path.vertices
codes = path.codes
# Insert a vertex at idx/pos (converting back to data space), if there isn't yet
# a vertex there. With infinite precision one could also always insert the
# extra vertex (it will get masked out by the label below anyways), but floating
# point inaccuracies (the point can have undergone a data->screen->data
# transform loop) can slightly shift the point and e.g. shift the angle computed
# below from exactly zero to nonzero.
pos = self.get_transform().inverted().transform(screen_pos)
if not np.allclose(pos, xys[idx]):
xys = np.insert(xys, idx, pos, axis=0)
codes = np.insert(codes, idx, Path.LINETO)
# Find the connected component where the label will be inserted. Note that a
# path always starts with a MOVETO, and we consider there's an implicit
# MOVETO (closing the last path) at the end.
movetos = (codes == Path.MOVETO).nonzero()[0]
start = movetos[movetos <= idx][-1]
try:
stop = movetos[movetos > idx][0]
except IndexError:
stop = len(codes)
# Restrict ourselves to the connected component.
cc_xys = xys[start:stop]
idx -= start
# If the path is closed, rotate it s.t. it starts at the label.
is_closed_path = codes[stop - 1] == Path.CLOSEPOLY
if is_closed_path:
cc_xys = np.concatenate([cc_xys[idx:-1], cc_xys[:idx+1]])
idx = 0
# Like np.interp, but additionally vectorized over fp.
def interp_vec(x, xp, fp): return [np.interp(x, xp, col) for col in fp.T]
# Use cumulative path lengths ("cpl") as curvilinear coordinate along contour.
screen_xys = self.get_transform().transform(cc_xys)
path_cpls = np.insert(
np.cumsum(np.hypot(*np.diff(screen_xys, axis=0).T)), 0, 0)
path_cpls -= path_cpls[idx]
# Use linear interpolation to get end coordinates of label.
target_cpls = np.array([-lw/2, lw/2])
if is_closed_path: # For closed paths, target from the other end.
target_cpls[0] += (path_cpls[-1] - path_cpls[0])
(sx0, sx1), (sy0, sy1) = interp_vec(target_cpls, path_cpls, screen_xys)
angle = np.rad2deg(np.arctan2(sy1 - sy0, sx1 - sx0)) # Screen space.
if self.rightside_up: # Fix angle so text is never upside-down
angle = (angle + 90) % 180 - 90
target_cpls += [-spacing, +spacing] # Expand range by spacing.
# Get indices near points of interest; use -1 as out of bounds marker.
i0, i1 = np.interp(target_cpls, path_cpls, range(len(path_cpls)),
left=-1, right=-1)
i0 = math.floor(i0)
i1 = math.ceil(i1)
(x0, x1), (y0, y1) = interp_vec(target_cpls, path_cpls, cc_xys)
# Actually break contours (dropping zero-len parts).
new_xy_blocks = []
new_code_blocks = []
if is_closed_path:
if i0 != -1 and i1 != -1:
# This is probably wrong in the case that the entire contour would
# be discarded, but ensures that a valid path is returned and is
# consistent with behavior of mpl <3.8
points = cc_xys[i1:i0+1]
new_xy_blocks.extend([[(x1, y1)], points, [(x0, y0)]])
nlines = len(points) + 1
new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * nlines])
else:
if i0 != -1:
new_xy_blocks.extend([cc_xys[:i0 + 1], [(x0, y0)]])
new_code_blocks.extend([[Path.MOVETO], [Path.LINETO] * (i0 + 1)])
if i1 != -1:
new_xy_blocks.extend([[(x1, y1)], cc_xys[i1:]])
new_code_blocks.extend([
[Path.MOVETO], [Path.LINETO] * (len(cc_xys) - i1)])
# Back to the full path.
xys = np.concatenate([xys[:start], *new_xy_blocks, xys[stop:]])
codes = np.concatenate([codes[:start], *new_code_blocks, codes[stop:]])
return angle, Path(xys, codes)
@_api.deprecated("3.8")
def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
"""
Calculate the appropriate label rotation given the linecontour
coordinates in screen units, the index of the label location and the
label width.
If *lc* is not None or empty, also break contours and compute
inlining.
*spacing* is the empty space to leave around the label, in pixels.
Both tasks are done together to avoid calculating path lengths
multiple times, which is relatively costly.
The method used here involves computing the path length along the
contour in pixel coordinates and then looking approximately (label
width / 2) away from central point to determine rotation and then to
break contour if desired.
"""
if lc is None:
lc = []
# Half the label width
hlw = lw / 2.0
# Check if closed and, if so, rotate contour so label is at edge
closed = _is_closed_polygon(slc)
if closed:
slc = np.concatenate([slc[ind:-1], slc[:ind + 1]])
if len(lc): # Rotate lc also if not empty
lc = np.concatenate([lc[ind:-1], lc[:ind + 1]])
ind = 0
# Calculate path lengths
pl = np.zeros(slc.shape[0], dtype=float)
dx = np.diff(slc, axis=0)
pl[1:] = np.cumsum(np.hypot(dx[:, 0], dx[:, 1]))
pl = pl - pl[ind]
# Use linear interpolation to get points around label
xi = np.array([-hlw, hlw])
if closed: # Look at end also for closed contours
dp = np.array([pl[-1], 0])
else:
dp = np.zeros_like(xi)
# Get angle of vector between the two ends of the label - must be
# calculated in pixel space for text rotation to work correctly.
(dx,), (dy,) = (np.diff(np.interp(dp + xi, pl, slc_col))
for slc_col in slc.T)
rotation = np.rad2deg(np.arctan2(dy, dx))
if self.rightside_up:
# Fix angle so text is never upside-down
rotation = (rotation + 90) % 180 - 90
# Break contour if desired
nlc = []
if len(lc):
# Expand range by spacing
xi = dp + xi + np.array([-spacing, spacing])
# Get (integer) indices near points of interest; use -1 as marker
# for out of bounds.
I = np.interp(xi, pl, np.arange(len(pl)), left=-1, right=-1)
I = [np.floor(I[0]).astype(int), np.ceil(I[1]).astype(int)]
if I[0] != -1:
xy1 = [np.interp(xi[0], pl, lc_col) for lc_col in lc.T]
if I[1] != -1:
xy2 = [np.interp(xi[1], pl, lc_col) for lc_col in lc.T]
# Actually break contours
if closed:
# This will remove contour if shorter than label
if all(i != -1 for i in I):
nlc.append(np.vstack([xy2, lc[I[1]:I[0]+1], xy1]))
else:
# These will remove pieces of contour if they have length zero
if I[0] != -1:
nlc.append(np.vstack([lc[:I[0]+1], xy1]))
if I[1] != -1:
nlc.append(np.vstack([xy2, lc[I[1]:]]))
# The current implementation removes contours completely
# covered by labels. Uncomment line below to keep
# original contour if this is the preferred behavior.
# if not len(nlc): nlc = [lc]
return rotation, nlc
def add_label(self, x, y, rotation, lev, cvalue):
"""Add contour label without `.Text.set_transform_rotates_text`."""
data_x, data_y = self.axes.transData.inverted().transform((x, y))
t = Text(
data_x, data_y,
text=self.get_text(lev, self.labelFmt),
rotation=rotation,
horizontalalignment='center', verticalalignment='center',
zorder=self._clabel_zorder,
color=self.labelMappable.to_rgba(cvalue, alpha=self.get_alpha()),
fontproperties=self._label_font_props,
clip_box=self.axes.bbox)
self.labelTexts.append(t)
self.labelCValues.append(cvalue)
self.labelXYs.append((x, y))
# Add label to plot here - useful for manual mode label selection
self.axes.add_artist(t)
def add_label_clabeltext(self, x, y, rotation, lev, cvalue):
"""Add contour label with `.Text.set_transform_rotates_text`."""
self.add_label(x, y, rotation, lev, cvalue)
# Grab the last added text, and reconfigure its rotation.
t = self.labelTexts[-1]
data_rotation, = self.axes.transData.inverted().transform_angles(
[rotation], [[x, y]])
t.set(rotation=data_rotation, transform_rotates_text=True)
def add_label_near(self, x, y, inline=True, inline_spacing=5,
transform=None):
"""
Add a label near the point ``(x, y)``.
Parameters
----------
x, y : float
The approximate location of the label.
inline : bool, default: True
If *True* remove the segment of the contour beneath the label.
inline_spacing : int, default: 5
Space in pixels to leave on each side of label when placing
inline. This spacing will be exact for labels at locations where
the contour is straight, less so for labels on curved contours.
transform : `.Transform` or `False`, default: ``self.axes.transData``
A transform applied to ``(x, y)`` before labeling. The default
causes ``(x, y)`` to be interpreted as data coordinates. `False`
is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
interpreted as display coordinates.
"""
if transform is None:
transform = self.axes.transData
if transform:
x, y = transform.transform((x, y))
idx_level_min, idx_vtx_min, proj = self._find_nearest_contour(
(x, y), self.labelIndiceList)
path = self._paths[idx_level_min]
level = self.labelIndiceList.index(idx_level_min)
label_width = self._get_nth_label_width(level)
rotation, path = self._split_path_and_get_label_rotation(
path, idx_vtx_min, proj, label_width, inline_spacing)
self.add_label(*proj, rotation, self.labelLevelList[idx_level_min],
self.labelCValueList[idx_level_min])
if inline:
self._paths[idx_level_min] = path
def pop_label(self, index=-1):
"""Defaults to removing last label, but any index can be supplied"""
self.labelCValues.pop(index)
t = self.labelTexts.pop(index)
t.remove()
def labels(self, inline, inline_spacing):
if self._use_clabeltext:
add_label = self.add_label_clabeltext
else:
add_label = self.add_label
for idx, (icon, lev, cvalue) in enumerate(zip(
self.labelIndiceList,
self.labelLevelList,
self.labelCValueList,
)):
trans = self.get_transform()
label_width = self._get_nth_label_width(idx)
additions = []
for subpath in self._paths[icon]._iter_connected_components():
screen_xys = trans.transform(subpath.vertices)
# Check if long enough for a label
if self.print_label(screen_xys, label_width):
x, y, idx = self.locate_label(screen_xys, label_width)
rotation, path = self._split_path_and_get_label_rotation(
subpath, idx, (x, y),
label_width, inline_spacing)
add_label(x, y, rotation, lev, cvalue) # Really add label.
if inline: # If inline, add new contours
additions.append(path)
else: # If not adding label, keep old path
additions.append(subpath)
# After looping over all segments on a contour, replace old path by new one
# if inlining.
if inline:
self._paths[icon] = Path.make_compound_path(*additions)
def remove(self):
super().remove()
for text in self.labelTexts:
text.remove()
def _is_closed_polygon(X):
"""
Return whether first and last object in a sequence are the same. These are
presumably coordinates on a polygonal curve, in which case this function
tests if that curve is closed.
"""
return np.allclose(X[0], X[-1], rtol=1e-10, atol=1e-13)
def _find_closest_point_on_path(xys, p):
"""
Parameters
----------
xys : (N, 2) array-like
Coordinates of vertices.
p : (float, float)
Coordinates of point.
Returns
-------
d2min : float
Minimum square distance of *p* to *xys*.
proj : (float, float)
Projection of *p* onto *xys*.
imin : (int, int)
Consecutive indices of vertices of segment in *xys* where *proj* is.
Segments are considered as including their end-points; i.e. if the
closest point on the path is a node in *xys* with index *i*, this
returns ``(i-1, i)``. For the special case where *xys* is a single
point, this returns ``(0, 0)``.
"""
if len(xys) == 1:
return (((p - xys[0]) ** 2).sum(), xys[0], (0, 0))
dxys = xys[1:] - xys[:-1] # Individual segment vectors.
norms = (dxys ** 2).sum(axis=1)
norms[norms == 0] = 1 # For zero-length segment, replace 0/0 by 0/1.
rel_projs = np.clip( # Project onto each segment in relative 0-1 coords.
((p - xys[:-1]) * dxys).sum(axis=1) / norms,
0, 1)[:, None]
projs = xys[:-1] + rel_projs * dxys # Projs. onto each segment, in (x, y).
d2s = ((projs - p) ** 2).sum(axis=1) # Squared distances.
imin = np.argmin(d2s)
return (d2s[imin], projs[imin], (imin, imin+1))
_docstring.interpd.update(contour_set_attributes=r"""
Attributes
----------
ax : `~matplotlib.axes.Axes`
The Axes object in which the contours are drawn.
collections : `.silent_list` of `.PathCollection`\s
The `.Artist`\s representing the contour. This is a list of
`.PathCollection`\s for both line and filled contours.
levels : array
The values of the contour levels.
layers : array
Same as levels for line contours; half-way between
levels for filled contours. See ``ContourSet._process_colors``.
""")
@_docstring.dedent_interpd
class ContourSet(ContourLabeler, mcoll.Collection):
"""
Store a set of contour lines or filled regions.
User-callable method: `~.Axes.clabel`
Parameters
----------
ax : `~matplotlib.axes.Axes`
levels : [level0, level1, ..., leveln]
A list of floating point numbers indicating the contour levels.
allsegs : [level0segs, level1segs, ...]
List of all the polygon segments for all the *levels*.
For contour lines ``len(allsegs) == len(levels)``, and for
filled contour regions ``len(allsegs) = len(levels)-1``. The lists
should look like ::
level0segs = [polygon0, polygon1, ...]
polygon0 = [[x0, y0], [x1, y1], ...]
allkinds : ``None`` or [level0kinds, level1kinds, ...]
Optional list of all the polygon vertex kinds (code types), as
described and used in Path. This is used to allow multiply-
connected paths such as holes within filled polygons.
If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
should look like ::
level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]
If *allkinds* is not ``None``, usually all polygons for a
particular contour level are grouped together so that
``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
**kwargs
Keyword arguments are as described in the docstring of
`~.Axes.contour`.
%(contour_set_attributes)s
"""
def __init__(self, ax, *args,
levels=None, filled=False, linewidths=None, linestyles=None,
hatches=(None,), alpha=None, origin=None, extent=None,
cmap=None, colors=None, norm=None, vmin=None, vmax=None,
extend='neither', antialiased=None, nchunk=0, locator=None,
transform=None, negative_linestyles=None, clip_path=None,
**kwargs):
"""
Draw contour lines or filled regions, depending on
whether keyword arg *filled* is ``False`` (default) or ``True``.
Call signature::
ContourSet(ax, levels, allsegs, [allkinds], **kwargs)
Parameters
----------
ax : `~matplotlib.axes.Axes`
The `~.axes.Axes` object to draw on.
levels : [level0, level1, ..., leveln]
A list of floating point numbers indicating the contour
levels.
allsegs : [level0segs, level1segs, ...]
List of all the polygon segments for all the *levels*.
For contour lines ``len(allsegs) == len(levels)``, and for
filled contour regions ``len(allsegs) = len(levels)-1``. The lists
should look like ::
level0segs = [polygon0, polygon1, ...]
polygon0 = [[x0, y0], [x1, y1], ...]
allkinds : [level0kinds, level1kinds, ...], optional
Optional list of all the polygon vertex kinds (code types), as
described and used in Path. This is used to allow multiply-
connected paths such as holes within filled polygons.
If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
should look like ::
level0kinds = [polygon0kinds, ...]
polygon0kinds = [vertexcode0, vertexcode1, ...]
If *allkinds* is not ``None``, usually all polygons for a
particular contour level are grouped together so that
``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.
**kwargs
Keyword arguments are as described in the docstring of
`~.Axes.contour`.
"""
if antialiased is None and filled:
# Eliminate artifacts; we are not stroking the boundaries.
antialiased = False
# The default for line contours will be taken from the
# LineCollection default, which uses :rc:`lines.antialiased`.
super().__init__(
antialiaseds=antialiased,
alpha=alpha,
clip_path=clip_path,
transform=transform,
)
self.axes = ax
self.levels = levels
self.filled = filled
self.hatches = hatches
self.origin = origin
self.extent = extent
self.colors = colors
self.extend = extend
self.nchunk = nchunk
self.locator = locator
if (isinstance(norm, mcolors.LogNorm)
or isinstance(self.locator, ticker.LogLocator)):
self.logscale = True
if norm is None:
norm = mcolors.LogNorm()
else:
self.logscale = False
_api.check_in_list([None, 'lower', 'upper', 'image'], origin=origin)
if self.extent is not None and len(self.extent) != 4:
raise ValueError(
"If given, 'extent' must be None or (x0, x1, y0, y1)")
if self.colors is not None and cmap is not None:
raise ValueError('Either colors or cmap must be None')
if self.origin == 'image':
self.origin = mpl.rcParams['image.origin']
self._orig_linestyles = linestyles # Only kept for user access.
self.negative_linestyles = negative_linestyles
# If negative_linestyles was not defined as a keyword argument, define
# negative_linestyles with rcParams
if self.negative_linestyles is None:
self.negative_linestyles = \
mpl.rcParams['contour.negative_linestyle']
kwargs = self._process_args(*args, **kwargs)
self._process_levels()
self._extend_min = self.extend in ['min', 'both']
self._extend_max = self.extend in ['max', 'both']
if self.colors is not None:
ncolors = len(self.levels)
if self.filled:
ncolors -= 1
i0 = 0
# Handle the case where colors are given for the extended
# parts of the contour.
use_set_under_over = False
# if we are extending the lower end, and we've been given enough
# colors then skip the first color in the resulting cmap. For the
# extend_max case we don't need to worry about passing more colors
# than ncolors as ListedColormap will clip.
total_levels = (ncolors +
int(self._extend_min) +
int(self._extend_max))
if (len(self.colors) == total_levels and
(self._extend_min or self._extend_max)):
use_set_under_over = True
if self._extend_min:
i0 = 1
cmap = mcolors.ListedColormap(self.colors[i0:None], N=ncolors)
if use_set_under_over:
if self._extend_min:
cmap.set_under(self.colors[0])
if self._extend_max:
cmap.set_over(self.colors[-1])
# label lists must be initialized here
self.labelTexts = []
self.labelCValues = []
self.set_cmap(cmap)
if norm is not None:
self.set_norm(norm)
with self.norm.callbacks.blocked(signal="changed"):
if vmin is not None:
self.norm.vmin = vmin
if vmax is not None:
self.norm.vmax = vmax
self.norm._changed()
self._process_colors()
if self._paths is None:
self._paths = self._make_paths_from_contour_generator()
if self.filled:
if linewidths is not None:
_api.warn_external('linewidths is ignored by contourf')
# Lower and upper contour levels.
lowers, uppers = self._get_lowers_and_uppers()
self.set(
edgecolor="none",
# Default zorder taken from Collection
zorder=kwargs.pop("zorder", 1),
)
else:
self.set(
facecolor="none",
linewidths=self._process_linewidths(linewidths),
linestyle=self._process_linestyles(linestyles),
# Default zorder taken from LineCollection, which is higher
# than for filled contours so that lines are displayed on top.
zorder=kwargs.pop("zorder", 2),
label="_nolegend_",
)
self.axes.add_collection(self, autolim=False)
self.sticky_edges.x[:] = [self._mins[0], self._maxs[0]]
self.sticky_edges.y[:] = [self._mins[1], self._maxs[1]]
self.axes.update_datalim([self._mins, self._maxs])
self.axes.autoscale_view(tight=True)
self.changed() # set the colors
if kwargs:
_api.warn_external(
'The following kwargs were not used by contour: ' +
", ".join(map(repr, kwargs))
)
allsegs = property(lambda self: [
[subp.vertices for subp in p._iter_connected_components()]
for p in self.get_paths()])
allkinds = property(lambda self: [
[subp.codes for subp in p._iter_connected_components()]
for p in self.get_paths()])
tcolors = _api.deprecated("3.8")(property(lambda self: [
(tuple(rgba),) for rgba in self.to_rgba(self.cvalues, self.alpha)]))
tlinewidths = _api.deprecated("3.8")(property(lambda self: [
(w,) for w in self.get_linewidths()]))
alpha = property(lambda self: self.get_alpha())
linestyles = property(lambda self: self._orig_linestyles)
@_api.deprecated("3.8", alternative="set_antialiased or get_antialiased",
addendum="Note that get_antialiased returns an array.")
@property
def antialiased(self):
return all(self.get_antialiased())
@antialiased.setter
def antialiased(self, aa):
self.set_antialiased(aa)
@_api.deprecated("3.8")
@property
def collections(self):
# On access, make oneself invisible and instead add the old-style collections
# (one PathCollection per level). We do not try to further split contours into
# connected components as we already lost track of what pairs of contours need
# to be considered as single units to draw filled regions with holes.
if not hasattr(self, "_old_style_split_collections"):
self.set_visible(False)
fcs = self.get_facecolor()
ecs = self.get_edgecolor()
lws = self.get_linewidth()
lss = self.get_linestyle()
self._old_style_split_collections = []
for idx, path in enumerate(self._paths):
pc = mcoll.PathCollection(
[path] if len(path.vertices) else [],
alpha=self.get_alpha(),
antialiaseds=self._antialiaseds[idx % len(self._antialiaseds)],
transform=self.get_transform(),
zorder=self.get_zorder(),
label="_nolegend_",
facecolor=fcs[idx] if len(fcs) else "none",
edgecolor=ecs[idx] if len(ecs) else "none",
linewidths=[lws[idx % len(lws)]],
linestyles=[lss[idx % len(lss)]],
)
if self.filled:
pc.set(hatch=self.hatches[idx % len(self.hatches)])
self._old_style_split_collections.append(pc)