/
categorical.py
4193 lines (3320 loc) · 146 KB
/
categorical.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 textwrap import dedent
from numbers import Number
import warnings
from colorsys import rgb_to_hls
from functools import partial
import numpy as np
import pandas as pd
try:
from scipy.stats import gaussian_kde
_no_scipy = False
except ImportError:
from .external.kde import gaussian_kde
_no_scipy = True
import matplotlib as mpl
from matplotlib.collections import PatchCollection
import matplotlib.patches as Patches
import matplotlib.pyplot as plt
from seaborn._oldcore import (
variable_type,
infer_orient,
categorical_order,
)
from seaborn.relational import _RelationalPlotter
from seaborn import utils
from seaborn.utils import remove_na, _normal_quantile_func, _draw_figure, _default_color
from seaborn.algorithms import bootstrap
from seaborn.palettes import color_palette, husl_palette, light_palette, dark_palette
from seaborn.axisgrid import FacetGrid, _facet_docs
__all__ = [
"catplot", "factorplot",
"stripplot", "swarmplot",
"boxplot", "violinplot", "boxenplot",
"pointplot", "barplot", "countplot",
]
# Subclassing _RelationalPlotter for the legend machinery,
# but probably should move that more centrally
class _CategoricalPlotterNew(_RelationalPlotter):
semantics = "x", "y", "hue", "units"
wide_structure = {"x": "@columns", "y": "@values", "hue": "@columns"}
flat_structure = {"x": "@index", "y": "@values"}
_legend_func = "scatter"
_legend_attributes = ["color"]
def __init__(
self,
data=None,
variables={},
order=None,
orient=None,
require_numeric=False,
legend="auto",
):
super().__init__(data=data, variables=variables)
# This method takes care of some bookkeeping that is necessary because the
# original categorical plots (prior to the 2021 refactor) had some rules that
# don't fit exactly into the logic of _core. It may be wise to have a second
# round of refactoring that moves the logic deeper, but this will keep things
# relatively sensible for now.
# The concept of an "orientation" is important to the original categorical
# plots, but there's no provision for it in _core, so we need to do it here.
# Note that it could be useful for the other functions in at least two ways
# (orienting a univariate distribution plot from long-form data and selecting
# the aggregation axis in lineplot), so we may want to eventually refactor it.
self.orient = infer_orient(
x=self.plot_data.get("x", None),
y=self.plot_data.get("y", None),
orient=orient,
require_numeric=require_numeric,
)
self.legend = legend
# Short-circuit in the case of an empty plot
if not self.has_xy_data:
return
# For wide data, orient determines assignment to x/y differently from the
# wide_structure rules in _core. If we do decide to make orient part of the
# _core variable assignment, we'll want to figure out how to express that.
if self.input_format == "wide" and self.orient == "h":
self.plot_data = self.plot_data.rename(columns={"x": "y", "y": "x"})
orig_x, orig_y = self.variables["x"], self.variables["y"]
self.variables.update({"x": orig_y, "y": orig_x})
orig_x_type, orig_y_type = self.var_types["x"], self.var_types["y"]
self.var_types.update({"x": orig_y_type, "y": orig_x_type})
# Categorical plots can be "univariate" in which case they get an anonymous
# category label on the opposite axis. Note: this duplicates code in the core
# scale_categorical function. We need to do it here because of the next line.
if self.cat_axis not in self.variables:
self.variables[self.cat_axis] = None
self.var_types[self.cat_axis] = "categorical"
self.plot_data[self.cat_axis] = ""
# Categorical variables have discrete levels that we need to track
cat_levels = categorical_order(self.plot_data[self.cat_axis], order)
self.var_levels[self.cat_axis] = cat_levels
def _hue_backcompat(self, color, palette, hue_order, force_hue=False):
"""Implement backwards compatibility for hue parametrization.
Note: the force_hue parameter is used so that functions can be shown to
pass existing tests during refactoring and then tested for new behavior.
It can be removed after completion of the work.
"""
# The original categorical functions applied a palette to the categorical axis
# by default. We want to require an explicit hue mapping, to be more consistent
# with how things work elsewhere now. I don't think there's any good way to
# do this gently -- because it's triggered by the default value of hue=None,
# users would always get a warning, unless we introduce some sentinel "default"
# argument for this change. That's possible, but asking users to set `hue=None`
# on every call is annoying.
# We are keeping the logic for implementing the old behavior in with the current
# system so that (a) we can punt on that decision and (b) we can ensure that
# refactored code passes old tests.
default_behavior = color is None or palette is not None
if force_hue and "hue" not in self.variables and default_behavior:
self._redundant_hue = True
self.plot_data["hue"] = self.plot_data[self.cat_axis]
self.variables["hue"] = self.variables[self.cat_axis]
self.var_types["hue"] = "categorical"
hue_order = self.var_levels[self.cat_axis]
# Because we convert the categorical axis variable to string,
# we need to update a dictionary palette too
if isinstance(palette, dict):
palette = {str(k): v for k, v in palette.items()}
else:
self._redundant_hue = False
# Previously, categorical plots had a trick where color= could seed the palette.
# Because that's an explicit parameterization, we are going to give it one
# release cycle with a warning before removing.
if "hue" in self.variables and palette is None and color is not None:
if not isinstance(color, str):
color = mpl.colors.to_hex(color)
palette = f"dark:{color}"
msg = (
"Setting a gradient palette using color= is deprecated and will be "
f"removed in version 0.13. Set `palette='{palette}'` for same effect."
)
warnings.warn(msg, FutureWarning)
return palette, hue_order
@property
def cat_axis(self):
return {"v": "x", "h": "y"}[self.orient]
def _get_gray(self, colors):
"""Get a grayscale value that looks good with color."""
if not len(colors):
return None
unique_colors = np.unique(colors, axis=0)
light_vals = [rgb_to_hls(*rgb[:3])[1] for rgb in unique_colors]
lum = min(light_vals) * .6
return (lum, lum, lum)
def _adjust_cat_axis(self, ax, axis):
"""Set ticks and limits for a categorical variable."""
# Note: in theory, this could happen in _attach for all categorical axes
# But two reasons not to do that:
# - If it happens before plotting, autoscaling messes up the plot limits
# - It would change existing plots from other seaborn functions
if self.var_types[axis] != "categorical":
return
# If both x/y data are empty, the correct way to set up the plot is
# somewhat undefined; because we don't add null category data to the plot in
# this case we don't *have* a categorical axis (yet), so best to just bail.
if self.plot_data[axis].empty:
return
# We can infer the total number of categories (including those from previous
# plots that are not part of the plot we are currently making) from the number
# of ticks, which matplotlib sets up while doing unit conversion. This feels
# slightly risky, as if we are relying on something that may be a matplotlib
# implementation detail. But I cannot think of a better way to keep track of
# the state from previous categorical calls (see GH2516 for context)
n = len(getattr(ax, f"get_{axis}ticks")())
if axis == "x":
ax.xaxis.grid(False)
ax.set_xlim(-.5, n - .5, auto=None)
else:
ax.yaxis.grid(False)
# Note limits that correspond to previously-inverted y axis
ax.set_ylim(n - .5, -.5, auto=None)
@property
def _native_width(self):
"""Return unit of width separating categories on native numeric scale."""
unique_values = np.unique(self.comp_data[self.cat_axis])
if len(unique_values) > 1:
native_width = np.nanmin(np.diff(unique_values))
else:
native_width = 1
return native_width
def _nested_offsets(self, width, dodge):
"""Return offsets for each hue level for dodged plots."""
offsets = None
if "hue" in self.variables:
n_levels = len(self._hue_map.levels)
if dodge:
each_width = width / n_levels
offsets = np.linspace(0, width - each_width, n_levels)
offsets -= offsets.mean()
else:
offsets = np.zeros(n_levels)
return offsets
# Note that the plotting methods here aim (in most cases) to produce the
# exact same artists as the original (pre 0.12) version of the code, so
# there is some weirdness that might not otherwise be clean or make sense in
# this context, such as adding empty artists for combinations of variables
# with no observations
def plot_strips(
self,
jitter,
dodge,
color,
edgecolor,
plot_kws,
):
width = .8 * self._native_width
offsets = self._nested_offsets(width, dodge)
if jitter is True:
jlim = 0.1
else:
jlim = float(jitter)
if "hue" in self.variables and dodge:
jlim /= len(self._hue_map.levels)
jlim *= self._native_width
jitterer = partial(np.random.uniform, low=-jlim, high=+jlim)
iter_vars = [self.cat_axis]
if dodge:
iter_vars.append("hue")
ax = self.ax
dodge_move = jitter_move = 0
for sub_vars, sub_data in self.iter_data(iter_vars,
from_comp_data=True,
allow_empty=True):
if offsets is not None and (offsets != 0).any():
dodge_move = offsets[sub_data["hue"].map(self._hue_map.levels.index)]
jitter_move = jitterer(size=len(sub_data)) if len(sub_data) > 1 else 0
adjusted_data = sub_data[self.cat_axis] + dodge_move + jitter_move
sub_data.loc[:, self.cat_axis] = adjusted_data
for var in "xy":
if self._log_scaled(var):
sub_data[var] = np.power(10, sub_data[var])
ax = self._get_axes(sub_vars)
points = ax.scatter(sub_data["x"], sub_data["y"], color=color, **plot_kws)
if "hue" in self.variables:
points.set_facecolors(self._hue_map(sub_data["hue"]))
if edgecolor == "gray": # XXX TODO change to "auto"
points.set_edgecolors(self._get_gray(points.get_facecolors()))
else:
points.set_edgecolors(edgecolor)
# Finalize the axes details
if self.legend == "auto":
show_legend = not self._redundant_hue and self.input_format != "wide"
else:
show_legend = bool(self.legend)
if show_legend:
self.add_legend_data(ax)
handles, _ = ax.get_legend_handles_labels()
if handles:
ax.legend(title=self.legend_title)
def plot_swarms(
self,
dodge,
color,
edgecolor,
warn_thresh,
plot_kws,
):
width = .8 * self._native_width
offsets = self._nested_offsets(width, dodge)
iter_vars = [self.cat_axis]
if dodge:
iter_vars.append("hue")
ax = self.ax
point_collections = {}
dodge_move = 0
for sub_vars, sub_data in self.iter_data(iter_vars,
from_comp_data=True,
allow_empty=True):
if offsets is not None:
dodge_move = offsets[sub_data["hue"].map(self._hue_map.levels.index)]
if not sub_data.empty:
sub_data.loc[:, self.cat_axis] = sub_data[self.cat_axis] + dodge_move
for var in "xy":
if self._log_scaled(var):
sub_data[var] = np.power(10, sub_data[var])
ax = self._get_axes(sub_vars)
points = ax.scatter(sub_data["x"], sub_data["y"], color=color, **plot_kws)
if "hue" in self.variables:
points.set_facecolors(self._hue_map(sub_data["hue"]))
if edgecolor == "gray": # XXX TODO change to "auto"
points.set_edgecolors(self._get_gray(points.get_facecolors()))
else:
points.set_edgecolors(edgecolor)
if not sub_data.empty:
point_collections[sub_data[self.cat_axis].iloc[0]] = points
beeswarm = Beeswarm(
width=width, orient=self.orient, warn_thresh=warn_thresh,
)
for center, points in point_collections.items():
if points.get_offsets().shape[0] > 1:
def draw(points, renderer, *, center=center):
beeswarm(points, center)
ax = points.axes
if self.orient == "h":
scalex = False
scaley = ax.get_autoscaley_on()
else:
scalex = ax.get_autoscalex_on()
scaley = False
# This prevents us from undoing the nice categorical axis limits
# set in _adjust_cat_axis, because that method currently leave
# the autoscale flag in its original setting. It may be better
# to disable autoscaling there to avoid needing to do this.
fixed_scale = self.var_types[self.cat_axis] == "categorical"
ax.update_datalim(points.get_datalim(ax.transData))
if not fixed_scale and (scalex or scaley):
ax.autoscale_view(scalex=scalex, scaley=scaley)
super(points.__class__, points).draw(renderer)
points.draw = draw.__get__(points)
_draw_figure(ax.figure)
# Finalize the axes details
if self.legend == "auto":
show_legend = not self._redundant_hue and self.input_format != "wide"
else:
show_legend = bool(self.legend)
if show_legend:
self.add_legend_data(ax)
handles, _ = ax.get_legend_handles_labels()
if handles:
ax.legend(title=self.legend_title)
class _CategoricalFacetPlotter(_CategoricalPlotterNew):
semantics = _CategoricalPlotterNew.semantics + ("col", "row")
class _CategoricalPlotter:
width = .8
default_palette = "light"
require_numeric = True
def establish_variables(self, x=None, y=None, hue=None, data=None,
orient=None, order=None, hue_order=None,
units=None):
"""Convert input specification into a common representation."""
# Option 1:
# We are plotting a wide-form dataset
# -----------------------------------
if x is None and y is None:
# Do a sanity check on the inputs
if hue is not None:
error = "Cannot use `hue` without `x` and `y`"
raise ValueError(error)
# No hue grouping with wide inputs
plot_hues = None
hue_title = None
hue_names = None
# No statistical units with wide inputs
plot_units = None
# We also won't get a axes labels here
value_label = None
group_label = None
# Option 1a:
# The input data is a Pandas DataFrame
# ------------------------------------
if isinstance(data, pd.DataFrame):
# Order the data correctly
if order is None:
order = []
# Reduce to just numeric columns
for col in data:
if variable_type(data[col]) == "numeric":
order.append(col)
plot_data = data[order]
group_names = order
group_label = data.columns.name
# Convert to a list of arrays, the common representation
iter_data = plot_data.iteritems()
plot_data = [np.asarray(s, float) for k, s in iter_data]
# Option 1b:
# The input data is an array or list
# ----------------------------------
else:
# We can't reorder the data
if order is not None:
error = "Input data must be a pandas object to reorder"
raise ValueError(error)
# The input data is an array
if hasattr(data, "shape"):
if len(data.shape) == 1:
if np.isscalar(data[0]):
plot_data = [data]
else:
plot_data = list(data)
elif len(data.shape) == 2:
nr, nc = data.shape
if nr == 1 or nc == 1:
plot_data = [data.ravel()]
else:
plot_data = [data[:, i] for i in range(nc)]
else:
error = ("Input `data` can have no "
"more than 2 dimensions")
raise ValueError(error)
# Check if `data` is None to let us bail out here (for testing)
elif data is None:
plot_data = [[]]
# The input data is a flat list
elif np.isscalar(data[0]):
plot_data = [data]
# The input data is a nested list
# This will catch some things that might fail later
# but exhaustive checks are hard
else:
plot_data = data
# Convert to a list of arrays, the common representation
plot_data = [np.asarray(d, float) for d in plot_data]
# The group names will just be numeric indices
group_names = list(range(len(plot_data)))
# Figure out the plotting orientation
orient = "h" if str(orient).startswith("h") else "v"
# Option 2:
# We are plotting a long-form dataset
# -----------------------------------
else:
# See if we need to get variables from `data`
if data is not None:
x = data.get(x, x)
y = data.get(y, y)
hue = data.get(hue, hue)
units = data.get(units, units)
# Validate the inputs
for var in [x, y, hue, units]:
if isinstance(var, str):
err = f"Could not interpret input '{var}'"
raise ValueError(err)
# Figure out the plotting orientation
orient = infer_orient(
x, y, orient, require_numeric=self.require_numeric
)
# Option 2a:
# We are plotting a single set of data
# ------------------------------------
if x is None or y is None:
# Determine where the data are
vals = y if x is None else x
# Put them into the common representation
plot_data = [np.asarray(vals)]
# Get a label for the value axis
if hasattr(vals, "name"):
value_label = vals.name
else:
value_label = None
# This plot will not have group labels or hue nesting
groups = None
group_label = None
group_names = []
plot_hues = None
hue_names = None
hue_title = None
plot_units = None
# Option 2b:
# We are grouping the data values by another variable
# ---------------------------------------------------
else:
# Determine which role each variable will play
if orient == "v":
vals, groups = y, x
else:
vals, groups = x, y
# Get the categorical axis label
group_label = None
if hasattr(groups, "name"):
group_label = groups.name
# Get the order on the categorical axis
group_names = categorical_order(groups, order)
# Group the numeric data
plot_data, value_label = self._group_longform(vals, groups,
group_names)
# Now handle the hue levels for nested ordering
if hue is None:
plot_hues = None
hue_title = None
hue_names = None
else:
# Get the order of the hue levels
hue_names = categorical_order(hue, hue_order)
# Group the hue data
plot_hues, hue_title = self._group_longform(hue, groups,
group_names)
# Now handle the units for nested observations
if units is None:
plot_units = None
else:
plot_units, _ = self._group_longform(units, groups,
group_names)
# Assign object attributes
# ------------------------
self.orient = orient
self.plot_data = plot_data
self.group_label = group_label
self.value_label = value_label
self.group_names = group_names
self.plot_hues = plot_hues
self.hue_title = hue_title
self.hue_names = hue_names
self.plot_units = plot_units
def _group_longform(self, vals, grouper, order):
"""Group a long-form variable by another with correct order."""
# Ensure that the groupby will work
if not isinstance(vals, pd.Series):
if isinstance(grouper, pd.Series):
index = grouper.index
else:
index = None
vals = pd.Series(vals, index=index)
# Group the val data
grouped_vals = vals.groupby(grouper)
out_data = []
for g in order:
try:
g_vals = grouped_vals.get_group(g)
except KeyError:
g_vals = np.array([])
out_data.append(g_vals)
# Get the vals axis label
label = vals.name
return out_data, label
def establish_colors(self, color, palette, saturation):
"""Get a list of colors for the main component of the plots."""
if self.hue_names is None:
n_colors = len(self.plot_data)
else:
n_colors = len(self.hue_names)
# Determine the main colors
if color is None and palette is None:
# Determine whether the current palette will have enough values
# If not, we'll default to the husl palette so each is distinct
current_palette = utils.get_color_cycle()
if n_colors <= len(current_palette):
colors = color_palette(n_colors=n_colors)
else:
colors = husl_palette(n_colors, l=.7) # noqa
elif palette is None:
# When passing a specific color, the interpretation depends
# on whether there is a hue variable or not.
# If so, we will make a blend palette so that the different
# levels have some amount of variation.
if self.hue_names is None:
colors = [color] * n_colors
else:
if self.default_palette == "light":
colors = light_palette(color, n_colors)
elif self.default_palette == "dark":
colors = dark_palette(color, n_colors)
else:
raise RuntimeError("No default palette specified")
else:
# Let `palette` be a dict mapping level to color
if isinstance(palette, dict):
if self.hue_names is None:
levels = self.group_names
else:
levels = self.hue_names
palette = [palette[l] for l in levels]
colors = color_palette(palette, n_colors)
# Desaturate a bit because these are patches
if saturation < 1:
colors = color_palette(colors, desat=saturation)
# Convert the colors to a common representations
rgb_colors = color_palette(colors)
# Determine the gray color to use for the lines framing the plot
light_vals = [rgb_to_hls(*c)[1] for c in rgb_colors]
lum = min(light_vals) * .6
gray = mpl.colors.rgb2hex((lum, lum, lum))
# Assign object attributes
self.colors = rgb_colors
self.gray = gray
@property
def hue_offsets(self):
"""A list of center positions for plots when hue nesting is used."""
n_levels = len(self.hue_names)
if self.dodge:
each_width = self.width / n_levels
offsets = np.linspace(0, self.width - each_width, n_levels)
offsets -= offsets.mean()
else:
offsets = np.zeros(n_levels)
return offsets
@property
def nested_width(self):
"""A float with the width of plot elements when hue nesting is used."""
if self.dodge:
width = self.width / len(self.hue_names) * .98
else:
width = self.width
return width
def annotate_axes(self, ax):
"""Add descriptive labels to an Axes object."""
if self.orient == "v":
xlabel, ylabel = self.group_label, self.value_label
else:
xlabel, ylabel = self.value_label, self.group_label
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
group_names = self.group_names
if not group_names:
group_names = ["" for _ in range(len(self.plot_data))]
if self.orient == "v":
ax.set_xticks(np.arange(len(self.plot_data)))
ax.set_xticklabels(group_names)
else:
ax.set_yticks(np.arange(len(self.plot_data)))
ax.set_yticklabels(group_names)
if self.orient == "v":
ax.xaxis.grid(False)
ax.set_xlim(-.5, len(self.plot_data) - .5, auto=None)
else:
ax.yaxis.grid(False)
ax.set_ylim(-.5, len(self.plot_data) - .5, auto=None)
if self.hue_names is not None:
ax.legend(loc="best", title=self.hue_title)
def add_legend_data(self, ax, color, label):
"""Add a dummy patch object so we can get legend data."""
rect = plt.Rectangle([0, 0], 0, 0,
linewidth=self.linewidth / 2,
edgecolor=self.gray,
facecolor=color,
label=label)
ax.add_patch(rect)
class _BoxPlotter(_CategoricalPlotter):
def __init__(self, x, y, hue, data, order, hue_order,
orient, color, palette, saturation,
width, dodge, fliersize, linewidth):
self.establish_variables(x, y, hue, data, orient, order, hue_order)
self.establish_colors(color, palette, saturation)
self.dodge = dodge
self.width = width
self.fliersize = fliersize
if linewidth is None:
linewidth = mpl.rcParams["lines.linewidth"]
self.linewidth = linewidth
def draw_boxplot(self, ax, kws):
"""Use matplotlib to draw a boxplot on an Axes."""
vert = self.orient == "v"
props = {}
for obj in ["box", "whisker", "cap", "median", "flier"]:
props[obj] = kws.pop(obj + "props", {})
for i, group_data in enumerate(self.plot_data):
if self.plot_hues is None:
# Handle case where there is data at this level
if group_data.size == 0:
continue
# Draw a single box or a set of boxes
# with a single level of grouping
box_data = np.asarray(remove_na(group_data))
# Handle case where there is no non-null data
if box_data.size == 0:
continue
artist_dict = ax.boxplot(box_data,
vert=vert,
patch_artist=True,
positions=[i],
widths=self.width,
**kws)
color = self.colors[i]
self.restyle_boxplot(artist_dict, color, props)
else:
# Draw nested groups of boxes
offsets = self.hue_offsets
for j, hue_level in enumerate(self.hue_names):
# Add a legend for this hue level
if not i:
self.add_legend_data(ax, self.colors[j], hue_level)
# Handle case where there is data at this level
if group_data.size == 0:
continue
hue_mask = self.plot_hues[i] == hue_level
box_data = np.asarray(remove_na(group_data[hue_mask]))
# Handle case where there is no non-null data
if box_data.size == 0:
continue
center = i + offsets[j]
artist_dict = ax.boxplot(box_data,
vert=vert,
patch_artist=True,
positions=[center],
widths=self.nested_width,
**kws)
self.restyle_boxplot(artist_dict, self.colors[j], props)
# Add legend data, but just for one set of boxes
def restyle_boxplot(self, artist_dict, color, props):
"""Take a drawn matplotlib boxplot and make it look nice."""
for box in artist_dict["boxes"]:
box.update(dict(facecolor=color,
zorder=.9,
edgecolor=self.gray,
linewidth=self.linewidth))
box.update(props["box"])
for whisk in artist_dict["whiskers"]:
whisk.update(dict(color=self.gray,
linewidth=self.linewidth,
linestyle="-"))
whisk.update(props["whisker"])
for cap in artist_dict["caps"]:
cap.update(dict(color=self.gray,
linewidth=self.linewidth))
cap.update(props["cap"])
for med in artist_dict["medians"]:
med.update(dict(color=self.gray,
linewidth=self.linewidth))
med.update(props["median"])
for fly in artist_dict["fliers"]:
fly.update(dict(markerfacecolor=self.gray,
marker="d",
markeredgecolor=self.gray,
markersize=self.fliersize))
fly.update(props["flier"])
def plot(self, ax, boxplot_kws):
"""Make the plot."""
self.draw_boxplot(ax, boxplot_kws)
self.annotate_axes(ax)
if self.orient == "h":
ax.invert_yaxis()
class _ViolinPlotter(_CategoricalPlotter):
def __init__(self, x, y, hue, data, order, hue_order,
bw, cut, scale, scale_hue, gridsize,
width, inner, split, dodge, orient, linewidth,
color, palette, saturation):
self.establish_variables(x, y, hue, data, orient, order, hue_order)
self.establish_colors(color, palette, saturation)
self.estimate_densities(bw, cut, scale, scale_hue, gridsize)
self.gridsize = gridsize
self.width = width
self.dodge = dodge
if inner is not None:
if not any([inner.startswith("quart"),
inner.startswith("box"),
inner.startswith("stick"),
inner.startswith("point")]):
err = f"Inner style '{inner}' not recognized"
raise ValueError(err)
self.inner = inner
if split and self.hue_names is not None and len(self.hue_names) != 2:
msg = "There must be exactly two hue levels to use `split`.'"
raise ValueError(msg)
self.split = split
if linewidth is None:
linewidth = mpl.rcParams["lines.linewidth"]
self.linewidth = linewidth
def estimate_densities(self, bw, cut, scale, scale_hue, gridsize):
"""Find the support and density for all of the data."""
# Initialize data structures to keep track of plotting data
if self.hue_names is None:
support = []
density = []
counts = np.zeros(len(self.plot_data))
max_density = np.zeros(len(self.plot_data))
else:
support = [[] for _ in self.plot_data]
density = [[] for _ in self.plot_data]
size = len(self.group_names), len(self.hue_names)
counts = np.zeros(size)
max_density = np.zeros(size)
for i, group_data in enumerate(self.plot_data):
# Option 1: we have a single level of grouping
# --------------------------------------------
if self.plot_hues is None:
# Strip missing datapoints
kde_data = remove_na(group_data)
# Handle special case of no data at this level
if kde_data.size == 0:
support.append(np.array([]))
density.append(np.array([1.]))
counts[i] = 0
max_density[i] = 0
continue
# Handle special case of a single unique datapoint
elif np.unique(kde_data).size == 1:
support.append(np.unique(kde_data))
density.append(np.array([1.]))
counts[i] = 1
max_density[i] = 0
continue
# Fit the KDE and get the used bandwidth size
kde, bw_used = self.fit_kde(kde_data, bw)
# Determine the support grid and get the density over it
support_i = self.kde_support(kde_data, bw_used, cut, gridsize)
density_i = kde.evaluate(support_i)
# Update the data structures with these results
support.append(support_i)
density.append(density_i)
counts[i] = kde_data.size
max_density[i] = density_i.max()
# Option 2: we have nested grouping by a hue variable
# ---------------------------------------------------
else:
for j, hue_level in enumerate(self.hue_names):
# Handle special case of no data at this category level
if not group_data.size:
support[i].append(np.array([]))
density[i].append(np.array([1.]))
counts[i, j] = 0
max_density[i, j] = 0
continue
# Select out the observations for this hue level
hue_mask = self.plot_hues[i] == hue_level
# Strip missing datapoints
kde_data = remove_na(group_data[hue_mask])
# Handle special case of no data at this level
if kde_data.size == 0:
support[i].append(np.array([]))
density[i].append(np.array([1.]))
counts[i, j] = 0
max_density[i, j] = 0
continue
# Handle special case of a single unique datapoint
elif np.unique(kde_data).size == 1:
support[i].append(np.unique(kde_data))
density[i].append(np.array([1.]))
counts[i, j] = 1
max_density[i, j] = 0
continue
# Fit the KDE and get the used bandwidth size
kde, bw_used = self.fit_kde(kde_data, bw)
# Determine the support grid and get the density over it