-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
relational.py
1761 lines (1386 loc) · 61.8 KB
/
relational.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
from itertools import product
from textwrap import dedent
import warnings
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from .core import (_VectorPlotter, unique_dashes, unique_markers)
from .utils import (categorical_order, get_color_cycle, ci_to_errsize,
remove_na, locator_to_legend_entries,
ci as ci_func)
from .algorithms import bootstrap
from .palettes import (color_palette, cubehelix_palette,
_parse_cubehelix_args, QUAL_PALETTES)
from .axisgrid import FacetGrid, _facet_docs
from ._decorators import _deprecate_positional_args
__all__ = ["relplot", "scatterplot", "lineplot"]
class _RelationalPlotter(_VectorPlotter):
semantics = _VectorPlotter.semantics + ["hue", "size", "style", "units"]
wide_structure = {
"x": "index", "y": "values", "hue": "columns", "style": "columns",
}
# TODO where best to define default parameters?
sort = True
# Defaults for size semantic
# TODO this should match style of other defaults
_default_size_range = 0, 1
def categorical_to_palette(self, data, order, palette):
"""Determine colors when the hue variable is qualitative."""
# -- Identify the order and name of the levels
if order is None:
levels = categorical_order(data)
else:
levels = order
n_colors = len(levels)
# -- Identify the set of colors to use
if isinstance(palette, dict):
missing = set(levels) - set(palette)
if any(missing):
err = "The palette dictionary is missing keys: {}"
raise ValueError(err.format(missing))
else:
if palette is None:
if n_colors <= len(get_color_cycle()):
colors = color_palette(None, n_colors)
else:
colors = color_palette("husl", n_colors)
elif isinstance(palette, list):
if len(palette) != n_colors:
err = "The palette list has the wrong number of colors."
raise ValueError(err)
colors = palette
else:
colors = color_palette(palette, n_colors)
palette = dict(zip(levels, colors))
return levels, palette
def numeric_to_palette(self, data, order, palette, norm):
"""Determine colors when the hue variable is quantitative."""
levels = list(np.sort(remove_na(data.unique())))
# TODO do we want to do something complicated to ensure contrast
# at the extremes of the colormap against the background?
# Identify the colormap to use
palette = "ch:" if palette is None else palette
if isinstance(palette, mpl.colors.Colormap):
cmap = palette
elif str(palette).startswith("ch:"):
args, kwargs = _parse_cubehelix_args(palette)
cmap = cubehelix_palette(0, *args, as_cmap=True, **kwargs)
elif isinstance(palette, dict):
colors = [palette[k] for k in sorted(palette)]
cmap = mpl.colors.ListedColormap(colors)
else:
try:
cmap = mpl.cm.get_cmap(palette)
except (ValueError, TypeError):
err = "Palette {} not understood"
raise ValueError(err)
if norm is None:
norm = mpl.colors.Normalize()
elif isinstance(norm, tuple):
norm = mpl.colors.Normalize(*norm)
elif not isinstance(norm, mpl.colors.Normalize):
err = "``hue_norm`` must be None, tuple, or Normalize object."
raise ValueError(err)
if not norm.scaled():
norm(np.asarray(data.dropna()))
# TODO this should also use color_lookup, but that needs the
# class attributes that get set after using this function...
if not isinstance(palette, dict):
palette = dict(zip(levels, cmap(norm(levels))))
# palette = {l: cmap(norm([l, 1]))[0] for l in levels}
return levels, palette, cmap, norm
def color_lookup(self, key):
"""Return the color corresponding to the hue level."""
if self.hue_type == "numeric":
normed = self.hue_norm(key)
if np.ma.is_masked(normed):
normed = np.nan
return self.cmap(normed)
elif self.hue_type == "categorical":
return self.palette[key]
def size_lookup(self, key):
"""Return the size corresponding to the size level."""
if self.size_type == "numeric":
min_size, max_size = self.size_range
val = self.size_norm(key)
if np.ma.is_masked(val):
return 0
return min_size + val * (max_size - min_size)
elif self.size_type == "categorical":
return self.sizes[key]
def style_to_attributes(self, levels, style, defaults, name):
"""Convert a style argument to a dict of matplotlib attributes."""
if style is True:
attrdict = dict(zip(levels, defaults))
elif style and isinstance(style, dict):
attrdict = style
elif style:
attrdict = dict(zip(levels, style))
else:
attrdict = {}
if attrdict:
missing_levels = set(levels) - set(attrdict)
if any(missing_levels):
err = "These `style` levels are missing {}: {}"
raise ValueError(err.format(name, missing_levels))
return attrdict
def subset_data(self):
"""Return (x, y) data for each subset defined by semantics."""
data = self.plot_data
all_true = pd.Series(True, data.index)
iter_levels = product(self.hue_levels,
self.size_levels,
self.style_levels)
for hue, size, style in iter_levels:
hue_rows = all_true if hue is None else data["hue"] == hue
size_rows = all_true if size is None else data["size"] == size
style_rows = all_true if style is None else data["style"] == style
rows = hue_rows & size_rows & style_rows
data["units"] = data.units.fillna("")
subset_data = data.loc[rows, ["units", "x", "y"]].dropna()
if not len(subset_data):
continue
if self.sort:
subset_data = subset_data.sort_values(["units", "x", "y"])
if "units" not in self.variables:
subset_data = subset_data.drop("units", axis=1)
yield (hue, size, style), subset_data
def parse_hue(self, data, palette=None, order=None, norm=None):
"""Determine what colors to use given data characteristics."""
if self._empty_data(data):
# Set default values when not using a hue mapping
levels = [None]
limits = None
norm = None
palette = {}
var_type = None
cmap = None
else:
# Determine what kind of hue mapping we want
var_type = self._semantic_type(data)
# Override depending on the type of the palette argument
if palette in QUAL_PALETTES:
var_type = "categorical"
elif norm is not None:
var_type = "numeric"
elif isinstance(palette, (dict, list)):
var_type = "categorical"
# -- Option 1: categorical color palette
if var_type == "categorical":
cmap = None
limits = None
levels, palette = self.categorical_to_palette(
# List comprehension here is required to
# overcome differences in the way pandas
# externalizes numpy datetime64
list(data), order, palette
)
# -- Option 2: sequential color palette
elif var_type == "numeric":
data = pd.to_numeric(data)
levels, palette, cmap, norm = self.numeric_to_palette(
data, order, palette, norm
)
limits = norm.vmin, norm.vmax
self.hue_levels = levels
self.hue_norm = norm
self.hue_limits = limits
self.hue_type = var_type
self.palette = palette
self.cmap = cmap
# Update data as it may have changed dtype
# TODO This is messy! We need to rethink the order of operations
# to avoid changing the plot data after we have it.
self.plot_data["hue"] = data
def parse_size(self, data, sizes=None, order=None, norm=None):
"""Determine the linewidths given data characteristics."""
# TODO could break out two options like parse_hue does for clarity
if self._empty_data(data):
levels = [None]
limits = None
norm = None
sizes = {}
var_type = None
width_range = None
else:
var_type = self._semantic_type(data)
# Override depending on the type of the sizes argument
if norm is not None:
var_type = "numeric"
elif isinstance(sizes, (dict, list)):
var_type = "categorical"
if var_type == "categorical":
levels = categorical_order(data, order)
numbers = np.arange(1, 1 + len(levels))[::-1]
elif var_type == "numeric":
data = pd.to_numeric(data)
levels = numbers = np.sort(remove_na(data.unique()))
if isinstance(sizes, (dict, list)):
# Use literal size values
if isinstance(sizes, list):
if len(sizes) != len(levels):
err = "The `sizes` list has wrong number of levels"
raise ValueError(err)
sizes = dict(zip(levels, sizes))
missing = set(levels) - set(sizes)
if any(missing):
err = "Missing sizes for the following levels: {}"
raise ValueError(err.format(missing))
width_range = min(sizes.values()), max(sizes.values())
try:
limits = min(sizes.keys()), max(sizes.keys())
except TypeError:
limits = None
else:
# Infer the range of sizes to use
if sizes is None:
min_width, max_width = self._default_size_range
else:
try:
min_width, max_width = sizes
except (TypeError, ValueError):
err = "sizes argument {} not understood".format(sizes)
raise ValueError(err)
width_range = min_width, max_width
if norm is None:
norm = mpl.colors.Normalize()
elif isinstance(norm, tuple):
norm = mpl.colors.Normalize(*norm)
elif not isinstance(norm, mpl.colors.Normalize):
err = ("``size_norm`` must be None, tuple, "
"or Normalize object.")
raise ValueError(err)
norm.clip = True
if not norm.scaled():
norm(np.asarray(numbers))
limits = norm.vmin, norm.vmax
scl = norm(numbers)
widths = np.asarray(min_width + scl * (max_width - min_width))
if scl.mask.any():
widths[scl.mask] = 0
sizes = dict(zip(levels, widths))
# sizes = {l: min_width + norm(n) * (max_width - min_width)
# for l, n in zip(levels, numbers)}
if var_type == "categorical":
# Don't keep a reference to the norm, which will avoid
# downstream code from switching to numerical interpretation
norm = None
self.sizes = sizes
self.size_type = var_type
self.size_levels = levels
self.size_norm = norm
self.size_limits = limits
self.size_range = width_range
# Update data as it may have changed dtype
self.plot_data["size"] = data
def parse_style(self, data, markers=None, dashes=None, order=None):
"""Determine the markers and line dashes."""
if self._empty_data(data):
levels = [None]
dashes = {}
markers = {}
else:
if order is None:
# List comprehension here is required to
# overcome differences in the way pandas
# coerces numpy datatypes
levels = categorical_order(list(data))
else:
levels = order
markers = self.style_to_attributes(
levels, markers, unique_markers(len(levels)), "markers"
)
dashes = self.style_to_attributes(
levels, dashes, unique_dashes(len(levels)), "dashes"
)
paths = {}
filled_markers = []
for k, m in markers.items():
if not isinstance(m, mpl.markers.MarkerStyle):
m = mpl.markers.MarkerStyle(m)
paths[k] = m.get_path().transformed(m.get_transform())
filled_markers.append(m.is_filled())
# Mixture of filled and unfilled markers will show line art markers
# in the edge color, which defaults to white. This can be handled,
# but there would be additional complexity with specifying the
# weight of the line art markers without overwhelming the filled
# ones with the edges. So for now, we will disallow mixtures.
if any(filled_markers) and not all(filled_markers):
err = "Filled and line art markers cannot be mixed"
raise ValueError(err)
self.style_levels = levels
self.dashes = dashes
self.markers = markers
self.paths = paths
def _empty_data(self, data):
"""Test if a series is completely missing."""
return data.isnull().all()
def _semantic_type(self, data):
"""Determine if data should considered numeric or categorical."""
if self.input_format == "wide":
return "categorical"
elif isinstance(data, pd.Series) and data.dtype.name == "category":
return "categorical"
else:
try:
float_data = data.astype(np.float)
values = np.unique(float_data.dropna())
# TODO replace with isin when pinned np version >= 1.13
if np.all(np.in1d(values, np.array([0., 1.]))):
return "categorical"
return "numeric"
except (ValueError, TypeError):
return "categorical"
def label_axes(self, ax):
"""Set x and y labels with visibility that matches the ticklabels."""
if "x" in self.variables and self.variables["x"] is not None:
x_visible = any(t.get_visible() for t in ax.get_xticklabels())
ax.set_xlabel(self.variables["x"], visible=x_visible)
if "y" in self.variables and self.variables["y"] is not None:
y_visible = any(t.get_visible() for t in ax.get_yticklabels())
ax.set_ylabel(self.variables["y"], visible=y_visible)
def add_legend_data(self, ax):
"""Add labeled artists to represent the different plot semantics."""
verbosity = self.legend
if verbosity not in ["brief", "full"]:
err = "`legend` must be 'brief', 'full', or False"
raise ValueError(err)
legend_kwargs = {}
keys = []
title_kws = dict(color="w", s=0, linewidth=0, marker="", dashes="")
def update(var_name, val_name, **kws):
key = var_name, val_name
if key in legend_kwargs:
legend_kwargs[key].update(**kws)
else:
keys.append(key)
legend_kwargs[key] = dict(**kws)
# -- Add a legend for hue semantics
if verbosity == "brief" and self.hue_type == "numeric":
if isinstance(self.hue_norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=3)
else:
locator = mpl.ticker.MaxNLocator(nbins=3)
hue_levels, hue_formatted_levels = locator_to_legend_entries(
locator, self.hue_limits, self.plot_data["hue"].dtype
)
else:
hue_levels = hue_formatted_levels = self.hue_levels
# Add the hue semantic subtitle
if "hue" in self.variables and self.variables["hue"] is not None:
update((self.variables["hue"], "title"),
self.variables["hue"], **title_kws)
# Add the hue semantic labels
for level, formatted_level in zip(hue_levels, hue_formatted_levels):
if level is not None:
color = self.color_lookup(level)
update(self.variables["hue"], formatted_level, color=color)
# -- Add a legend for size semantics
if verbosity == "brief" and self.size_type == "numeric":
if isinstance(self.size_norm, mpl.colors.LogNorm):
locator = mpl.ticker.LogLocator(numticks=3)
else:
locator = mpl.ticker.MaxNLocator(nbins=3)
size_levels, size_formatted_levels = locator_to_legend_entries(
locator, self.size_limits, self.plot_data["size"].dtype)
else:
size_levels = size_formatted_levels = self.size_levels
# Add the size semantic subtitle
if "size" in self.variables and self.variables["size"] is not None:
update((self.variables["size"], "title"),
self.variables["size"], **title_kws)
# Add the size semantic labels
for level, formatted_level in zip(size_levels, size_formatted_levels):
if level is not None:
size = self.size_lookup(level)
update(self.variables["size"],
formatted_level, linewidth=size, s=size)
# -- Add a legend for style semantics
# Add the style semantic title
if "style" in self.variables and self.variables["style"] is not None:
update((self.variables["style"], "title"),
self.variables["style"], **title_kws)
# Add the style semantic labels
for level in self.style_levels:
if level is not None:
update(self.variables["style"], level,
marker=self.markers.get(level, ""),
dashes=self.dashes.get(level, ""))
func = getattr(ax, self._legend_func)
legend_data = {}
legend_order = []
for key in keys:
_, label = key
kws = legend_kwargs[key]
kws.setdefault("color", ".2")
use_kws = {}
for attr in self._legend_attributes + ["visible"]:
if attr in kws:
use_kws[attr] = kws[attr]
artist = func([], [], label=label, **use_kws)
if self._legend_func == "plot":
artist = artist[0]
legend_data[key] = artist
legend_order.append(key)
self.legend_data = legend_data
self.legend_order = legend_order
class _LinePlotter(_RelationalPlotter):
_legend_attributes = ["color", "linewidth", "marker", "dashes"]
_legend_func = "plot"
def __init__(self,
x=None, y=None, hue=None, size=None, style=None, data=None,
palette=None, hue_order=None, hue_norm=None,
sizes=None, size_order=None, size_norm=None,
dashes=None, markers=None, style_order=None,
units=None, estimator=None, ci=None, n_boot=None, seed=None,
sort=True, err_style=None, err_kws=None, legend=None):
plot_data, variables = self.establish_variables(
data, x=x, y=y, hue=hue, size=size, style=style, units=units,
)
self._default_size_range = (
np.r_[.5, 2] * mpl.rcParams["lines.linewidth"]
)
self.parse_hue(plot_data["hue"], palette, hue_order, hue_norm)
self.parse_size(plot_data["size"], sizes, size_order, size_norm)
self.parse_style(plot_data["style"], markers, dashes, style_order)
self.units = units
self.estimator = estimator
self.ci = ci
self.n_boot = n_boot
self.seed = seed
self.sort = sort
self.err_style = err_style
self.err_kws = {} if err_kws is None else err_kws
self.legend = legend
def aggregate(self, vals, grouper, units=None):
"""Compute an estimate and confidence interval using grouper."""
func = self.estimator
ci = self.ci
n_boot = self.n_boot
seed = self.seed
# Define a "null" CI for when we only have one value
null_ci = pd.Series(index=["low", "high"], dtype=np.float)
# Function to bootstrap in the context of a pandas group by
def bootstrapped_cis(vals):
if len(vals) <= 1:
return null_ci
boots = bootstrap(vals, func=func, n_boot=n_boot, seed=seed)
cis = ci_func(boots, ci)
return pd.Series(cis, ["low", "high"])
# Group and get the aggregation estimate
grouped = vals.groupby(grouper, sort=self.sort)
est = grouped.agg(func)
# Exit early if we don't want a confidence interval
if ci is None:
return est.index, est, None
# Compute the error bar extents
if ci == "sd":
sd = grouped.std()
cis = pd.DataFrame(np.c_[est - sd, est + sd],
index=est.index,
columns=["low", "high"]).stack()
else:
cis = grouped.apply(bootstrapped_cis)
# Unpack the CIs into "wide" format for plotting
if cis.notnull().any():
cis = cis.unstack().reindex(est.index)
else:
cis = None
return est.index, est, cis
def plot(self, ax, kws):
"""Draw the plot onto an axes, passing matplotlib kwargs."""
# Draw a test plot, using the passed in kwargs. The goal here is to
# honor both (a) the current state of the plot cycler and (b) the
# specified kwargs on all the lines we will draw, overriding when
# relevant with the data semantics. Note that we won't cycle
# internally; in other words, if ``hue`` is not used, all elements will
# have the same color, but they will have the color that you would have
# gotten from the corresponding matplotlib function, and calling the
# function will advance the axes property cycle.
scout, = ax.plot([], [], **kws)
orig_color = kws.pop("color", scout.get_color())
orig_marker = kws.pop("marker", scout.get_marker())
orig_linewidth = kws.pop("linewidth",
kws.pop("lw", scout.get_linewidth()))
orig_dashes = kws.pop("dashes", "")
kws.setdefault("markeredgewidth", kws.pop("mew", .75))
kws.setdefault("markeredgecolor", kws.pop("mec", "w"))
scout.remove()
# Set default error kwargs
err_kws = self.err_kws.copy()
if self.err_style == "band":
err_kws.setdefault("alpha", .2)
elif self.err_style == "bars":
pass
elif self.err_style is not None:
err = "`err_style` must be 'band' or 'bars', not {}"
raise ValueError(err.format(self.err_style))
# Loop over the semantic subsets and draw a line for each
for semantics, data in self.subset_data():
hue, size, style = semantics
x, y, units = data["x"], data["y"], data.get("units", None)
if self.estimator is not None:
if self.units is not None:
err = "estimator must be None when specifying units"
raise ValueError(err)
x, y, y_ci = self.aggregate(y, x, units)
else:
y_ci = None
kws["color"] = self.palette.get(hue, orig_color)
kws["dashes"] = self.dashes.get(style, orig_dashes)
kws["marker"] = self.markers.get(style, orig_marker)
kws["linewidth"] = self.sizes.get(size, orig_linewidth)
line, = ax.plot([], [], **kws)
line_color = line.get_color()
line_alpha = line.get_alpha()
line_capstyle = line.get_solid_capstyle()
line.remove()
# --- Draw the main line
x, y = np.asarray(x), np.asarray(y)
if self.units is None:
line, = ax.plot(x, y, **kws)
else:
for u in units.unique():
rows = np.asarray(units == u)
ax.plot(x[rows], y[rows], **kws)
# --- Draw the confidence intervals
if y_ci is not None:
low, high = np.asarray(y_ci["low"]), np.asarray(y_ci["high"])
if self.err_style == "band":
ax.fill_between(x, low, high, color=line_color, **err_kws)
elif self.err_style == "bars":
y_err = ci_to_errsize((low, high), y)
ebars = ax.errorbar(x, y, y_err, linestyle="",
color=line_color, alpha=line_alpha,
**err_kws)
# Set the capstyle properly on the error bars
for obj in ebars.get_children():
try:
obj.set_capstyle(line_capstyle)
except AttributeError:
# Does not exist on mpl < 2.2
pass
# Finalize the axes details
self.label_axes(ax)
if self.legend:
self.add_legend_data(ax)
handles, _ = ax.get_legend_handles_labels()
if handles:
ax.legend()
class _ScatterPlotter(_RelationalPlotter):
_legend_attributes = ["color", "s", "marker"]
_legend_func = "scatter"
def __init__(self,
x=None, y=None, hue=None, size=None, style=None, data=None,
palette=None, hue_order=None, hue_norm=None,
sizes=None, size_order=None, size_norm=None,
dashes=None, markers=None, style_order=None,
x_bins=None, y_bins=None,
units=None, estimator=None, ci=None, n_boot=None,
alpha=None, x_jitter=None, y_jitter=None,
legend=None):
plot_data, variables = self.establish_variables(
data, x=x, y=y, hue=hue, size=size, style=style, units=units,
)
self._default_size_range = (
np.r_[.5, 2] * np.square(mpl.rcParams["lines.markersize"])
)
self.parse_hue(plot_data["hue"], palette, hue_order, hue_norm)
self.parse_size(plot_data["size"], sizes, size_order, size_norm)
self.parse_style(plot_data["style"], markers, None, style_order)
self.units = units
self.alpha = alpha
self.legend = legend
def plot(self, ax, kws):
# Draw a test plot, using the passed in kwargs. The goal here is to
# honor both (a) the current state of the plot cycler and (b) the
# specified kwargs on all the lines we will draw, overriding when
# relevant with the data semantics. Note that we won't cycle
# internally; in other words, if ``hue`` is not used, all elements will
# have the same color, but they will have the color that you would have
# gotten from the corresponding matplotlib function, and calling the
# function will advance the axes property cycle.
scout = ax.scatter([], [], **kws)
s = kws.pop("s", scout.get_sizes())
c = kws.pop("c", scout.get_facecolors())
scout.remove()
kws.pop("color", None) # TODO is this optimal?
# --- Determine the visual attributes of the plot
data = self.plot_data[list(self.variables)].dropna()
if not data.size:
return
# Define the vectors of x and y positions
x = data.get(["x"], np.full(len(data), np.nan))
y = data.get(["y"], np.full(len(data), np.nan))
# Define vectors of hue and size values
# There must be some reason this doesn't use data[var].map(attr_dict)
# But I do not remember what it is!
if self.palette:
c = [self.palette.get(val) for val in data["hue"]]
if self.sizes:
s = [self.sizes.get(val) for val in data["size"]]
# Set defaults for other visual attributres
kws.setdefault("linewidth", .08 * np.sqrt(np.percentile(s, 10)))
kws.setdefault("edgecolor", "w")
if self.markers:
# Use a representative marker so scatter sets the edgecolor
# properly for line art markers. We currently enforce either
# all or none line art so this works.
example_marker = list(self.markers.values())[0]
kws.setdefault("marker", example_marker)
# TODO this makes it impossible to vary alpha with hue which might
# otherwise be useful? Should we just pass None?
kws["alpha"] = 1 if self.alpha == "auto" else self.alpha
# Draw the scatter plot
args = np.asarray(x), np.asarray(y), np.asarray(s), np.asarray(c)
points = ax.scatter(*args, **kws)
# Update the paths to get different marker shapes.
# This has to be done here because ax.scatter allows varying sizes
# and colors but only a single marker shape per call.
if self.paths:
p = [self.paths.get(val) for val in data["style"]]
points.set_paths(p)
# Finalize the axes details
self.label_axes(ax)
if self.legend:
self.add_legend_data(ax)
handles, _ = ax.get_legend_handles_labels()
if handles:
ax.legend()
_relational_docs = dict(
# --- Introductory prose
main_api_narrative=dedent("""\
The relationship between ``x`` and ``y`` can be shown for different subsets
of the data using the ``hue``, ``size``, and ``style`` parameters. These
parameters control what visual semantics are used to identify the different
subsets. It is possible to show up to three dimensions independently by
using all three semantic types, but this style of plot can be hard to
interpret and is often ineffective. Using redundant semantics (i.e. both
``hue`` and ``style`` for the same variable) can be helpful for making
graphics more accessible.
See the :ref:`tutorial <relational_tutorial>` for more information.\
"""),
relational_semantic_narrative=dedent("""\
The default treatment of the ``hue`` (and to a lesser extent, ``size``)
semantic, if present, depends on whether the variable is inferred to
represent "numeric" or "categorical" data. In particular, numeric variables
are represented with a sequential colormap by default, and the legend
entries show regular "ticks" with values that may or may not exist in the
data. This behavior can be controlled through various parameters, as
described and illustrated below.\
"""),
# --- Shared function parameters
data_vars=dedent("""\
x, y : names of variables in ``data`` or vector data, optional
Input data variables; must be numeric. Can pass data directly or
reference columns in ``data``.\
"""),
data=dedent("""\
data : DataFrame, array, or list of arrays, optional
Input data structure. If ``x`` and ``y`` are specified as names, this
should be a "long-form" DataFrame containing those columns. Otherwise
it is treated as "wide-form" data and grouping variables are ignored.
See the examples for the various ways this parameter can be specified
and the different effects of each.\
"""),
palette=dedent("""\
palette : string, list, dict, or matplotlib colormap
An object that determines how colors are chosen when ``hue`` is used.
It can be the name of a seaborn palette or matplotlib colormap, a list
of colors (anything matplotlib understands), a dict mapping levels
of the ``hue`` variable to colors, or a matplotlib colormap object.\
"""),
hue_order=dedent("""\
hue_order : list, optional
Specified order for the appearance of the ``hue`` variable levels,
otherwise they are determined from the data. Not relevant when the
``hue`` variable is numeric.\
"""),
hue_norm=dedent("""\
hue_norm : tuple or Normalize object, optional
Normalization in data units for colormap applied to the ``hue``
variable when it is numeric. Not relevant if it is categorical.\
"""),
sizes=dedent("""\
sizes : list, dict, or tuple, optional
An object that determines how sizes are chosen when ``size`` is used.
It can always be a list of size values or a dict mapping levels of the
``size`` variable to sizes. When ``size`` is numeric, it can also be
a tuple specifying the minimum and maximum size to use such that other
values are normalized within this range.\
"""),
size_order=dedent("""\
size_order : list, optional
Specified order for appearance of the ``size`` variable levels,
otherwise they are determined from the data. Not relevant when the
``size`` variable is numeric.\
"""),
size_norm=dedent("""\
size_norm : tuple or Normalize object, optional
Normalization in data units for scaling plot objects when the
``size`` variable is numeric.\
"""),
markers=dedent("""\
markers : boolean, list, or dictionary, optional
Object determining how to draw the markers for different levels of the
``style`` variable. Setting to ``True`` will use default markers, or
you can pass a list of markers or a dictionary mapping levels of the
``style`` variable to markers. Setting to ``False`` will draw
marker-less lines. Markers are specified as in matplotlib.\
"""),
style_order=dedent("""\
style_order : list, optional
Specified order for appearance of the ``style`` variable levels
otherwise they are determined from the data. Not relevant when the
``style`` variable is numeric.\
"""),
units=dedent("""\
units : {long_form_var}
Grouping variable identifying sampling units. When used, a separate
line will be drawn for each unit with appropriate semantics, but no
legend entry will be added. Useful for showing distribution of
experimental replicates when exact identities are not needed.
"""),
estimator=dedent("""\
estimator : name of pandas method or callable or None, optional
Method for aggregating across multiple observations of the ``y``
variable at the same ``x`` level. If ``None``, all observations will
be drawn.\
"""),
ci=dedent("""\
ci : int or "sd" or None, optional
Size of the confidence interval to draw when aggregating with an
estimator. "sd" means to draw the standard deviation of the data.
Setting to ``None`` will skip bootstrapping.\
"""),
n_boot=dedent("""\
n_boot : int, optional
Number of bootstraps to use for computing the confidence interval.\
"""),
seed=dedent("""\
seed : int, numpy.random.Generator, or numpy.random.RandomState, optional
Seed or random number generator for reproducible bootstrapping.\
"""),
legend=dedent("""\
legend : "brief", "full", or False, optional
How to draw the legend. If "brief", numeric ``hue`` and ``size``
variables will be represented with a sample of evenly spaced values.
If "full", every group will get an entry in the legend. If ``False``,
no legend data is added and no legend is drawn.\
"""),
ax_in=dedent("""\
ax : matplotlib Axes, optional
Axes object to draw the plot onto, otherwise uses the current Axes.\
"""),
ax_out=dedent("""\
ax : matplotlib Axes
Returns the Axes object with the plot drawn onto it.\
"""),
# --- Repeated phrases
long_form_var="name of variables in ``data`` or vector data, optional",
)
_relational_docs.update(_facet_docs)
@_deprecate_positional_args
def lineplot(
x=None, y=None, *,
hue=None, size=None, style=None,
data=None,
palette=None, hue_order=None, hue_norm=None,
sizes=None, size_order=None, size_norm=None,
dashes=True, markers=None, style_order=None,
units=None, estimator="mean", ci=95, n_boot=1000, seed=None,
sort=True, err_style="band", err_kws=None,
legend="brief", ax=None, **kwargs
):
p = _LinePlotter(
x=x, y=y, hue=hue, size=size, style=style, data=data,
palette=palette, hue_order=hue_order, hue_norm=hue_norm,
sizes=sizes, size_order=size_order, size_norm=size_norm,
dashes=dashes, markers=markers, style_order=style_order,
units=units, estimator=estimator, ci=ci, n_boot=n_boot, seed=seed,
sort=sort, err_style=err_style, err_kws=err_kws, legend=legend,
)
if ax is None:
ax = plt.gca()
p.plot(ax, kwargs)
return ax