-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
distributions.py
2531 lines (2060 loc) · 84.7 KB
/
distributions.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
"""Plotting functions for visualizing distributions."""
from numbers import Number
from functools import partial
import math
import textwrap
import warnings
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms as tx
from matplotlib.colors import to_rgba
from matplotlib.collections import LineCollection
from ._base import VectorPlotter
# We have moved univariate histogram computation over to the new Hist class,
# but still use the older Histogram for bivariate computation.
from ._statistics import ECDF, Histogram, KDE
from ._stats.counting import Hist
from .axisgrid import (
FacetGrid,
_facet_docs,
)
from .utils import (
remove_na,
_get_transform_functions,
_kde_support,
_normalize_kwargs,
_check_argument,
_assign_default_kwargs,
_default_color,
)
from .palettes import color_palette
from .external import husl
from .external.kde import gaussian_kde
from ._docstrings import (
DocstringComponents,
_core_docs,
)
__all__ = ["displot", "histplot", "kdeplot", "ecdfplot", "rugplot", "distplot"]
# ==================================================================================== #
# Module documentation
# ==================================================================================== #
_dist_params = dict(
multiple="""
multiple : {{"layer", "stack", "fill"}}
Method for drawing multiple elements when semantic mapping creates subsets.
Only relevant with univariate data.
""",
log_scale="""
log_scale : bool or number, or pair of bools or numbers
Set axis scale(s) to log. A single value sets the data axis for any numeric
axes in the plot. A pair of values sets each axis independently.
Numeric values are interpreted as the desired base (default 10).
When `None` or `False`, seaborn defers to the existing Axes scale.
""",
legend="""
legend : bool
If False, suppress the legend for semantic variables.
""",
cbar="""
cbar : bool
If True, add a colorbar to annotate the color mapping in a bivariate plot.
Note: Does not currently support plots with a ``hue`` variable well.
""",
cbar_ax="""
cbar_ax : :class:`matplotlib.axes.Axes`
Pre-existing axes for the colorbar.
""",
cbar_kws="""
cbar_kws : dict
Additional parameters passed to :meth:`matplotlib.figure.Figure.colorbar`.
""",
)
_param_docs = DocstringComponents.from_nested_components(
core=_core_docs["params"],
facets=DocstringComponents(_facet_docs),
dist=DocstringComponents(_dist_params),
kde=DocstringComponents.from_function_params(KDE.__init__),
hist=DocstringComponents.from_function_params(Histogram.__init__),
ecdf=DocstringComponents.from_function_params(ECDF.__init__),
)
# ==================================================================================== #
# Internal API
# ==================================================================================== #
class _DistributionPlotter(VectorPlotter):
wide_structure = {"x": "@values", "hue": "@columns"}
flat_structure = {"x": "@values"}
def __init__(
self,
data=None,
variables={},
):
super().__init__(data=data, variables=variables)
@property
def univariate(self):
"""Return True if only x or y are used."""
# TODO this could go down to core, but putting it here now.
# We'd want to be conceptually clear that univariate only applies
# to x/y and not to other semantics, which can exist.
# We haven't settled on a good conceptual name for x/y.
return bool({"x", "y"} - set(self.variables))
@property
def data_variable(self):
"""Return the variable with data for univariate plots."""
# TODO This could also be in core, but it should have a better name.
if not self.univariate:
raise AttributeError("This is not a univariate plot")
return {"x", "y"}.intersection(self.variables).pop()
@property
def has_xy_data(self):
"""Return True at least one of x or y is defined."""
# TODO see above points about where this should go
return bool({"x", "y"} & set(self.variables))
def _add_legend(
self,
ax_obj, artist, fill, element, multiple, alpha, artist_kws, legend_kws,
):
"""Add artists that reflect semantic mappings and put then in a legend."""
# TODO note that this doesn't handle numeric mappings like the relational plots
handles = []
labels = []
for level in self._hue_map.levels:
color = self._hue_map(level)
kws = self._artist_kws(
artist_kws, fill, element, multiple, color, alpha
)
# color gets added to the kws to workaround an issue with barplot's color
# cycle integration but it causes problems in this context where we are
# setting artist properties directly, so pop it off here
if "facecolor" in kws:
kws.pop("color", None)
handles.append(artist(**kws))
labels.append(level)
if isinstance(ax_obj, mpl.axes.Axes):
ax_obj.legend(handles, labels, title=self.variables["hue"], **legend_kws)
else: # i.e. a FacetGrid. TODO make this better
legend_data = dict(zip(labels, handles))
ax_obj.add_legend(
legend_data,
title=self.variables["hue"],
label_order=self.var_levels["hue"],
**legend_kws
)
def _artist_kws(self, kws, fill, element, multiple, color, alpha):
"""Handle differences between artists in filled/unfilled plots."""
kws = kws.copy()
if fill:
kws = _normalize_kwargs(kws, mpl.collections.PolyCollection)
kws.setdefault("facecolor", to_rgba(color, alpha))
if element == "bars":
# Make bar() interface with property cycle correctly
# https://github.com/matplotlib/matplotlib/issues/19385
kws["color"] = "none"
if multiple in ["stack", "fill"] or element == "bars":
kws.setdefault("edgecolor", mpl.rcParams["patch.edgecolor"])
else:
kws.setdefault("edgecolor", to_rgba(color, 1))
elif element == "bars":
kws["facecolor"] = "none"
kws["edgecolor"] = to_rgba(color, alpha)
else:
kws["color"] = to_rgba(color, alpha)
return kws
def _quantile_to_level(self, data, quantile):
"""Return data levels corresponding to quantile cuts of mass."""
isoprop = np.asarray(quantile)
values = np.ravel(data)
sorted_values = np.sort(values)[::-1]
normalized_values = np.cumsum(sorted_values) / values.sum()
idx = np.searchsorted(normalized_values, 1 - isoprop)
levels = np.take(sorted_values, idx, mode="clip")
return levels
def _cmap_from_color(self, color):
"""Return a sequential colormap given a color seed."""
# Like so much else here, this is broadly useful, but keeping it
# in this class to signify that I haven't thought overly hard about it...
r, g, b, _ = to_rgba(color)
h, s, _ = husl.rgb_to_husl(r, g, b)
xx = np.linspace(-1, 1, int(1.15 * 256))[:256]
ramp = np.zeros((256, 3))
ramp[:, 0] = h
ramp[:, 1] = s * np.cos(xx)
ramp[:, 2] = np.linspace(35, 80, 256)
colors = np.clip([husl.husl_to_rgb(*hsl) for hsl in ramp], 0, 1)
return mpl.colors.ListedColormap(colors[::-1])
def _default_discrete(self):
"""Find default values for discrete hist estimation based on variable type."""
if self.univariate:
discrete = self.var_types[self.data_variable] == "categorical"
else:
discrete_x = self.var_types["x"] == "categorical"
discrete_y = self.var_types["y"] == "categorical"
discrete = discrete_x, discrete_y
return discrete
def _resolve_multiple(self, curves, multiple):
"""Modify the density data structure to handle multiple densities."""
# Default baselines have all densities starting at 0
baselines = {k: np.zeros_like(v) for k, v in curves.items()}
# TODO we should have some central clearinghouse for checking if any
# "grouping" (terminnology?) semantics have been assigned
if "hue" not in self.variables:
return curves, baselines
if multiple in ("stack", "fill"):
# Setting stack or fill means that the curves share a
# support grid / set of bin edges, so we can make a dataframe
# Reverse the column order to plot from top to bottom
curves = pd.DataFrame(curves).iloc[:, ::-1]
# Find column groups that are nested within col/row variables
column_groups = {}
for i, keyd in enumerate(map(dict, curves.columns)):
facet_key = keyd.get("col", None), keyd.get("row", None)
column_groups.setdefault(facet_key, [])
column_groups[facet_key].append(i)
baselines = curves.copy()
for col_idxs in column_groups.values():
cols = curves.columns[col_idxs]
norm_constant = curves[cols].sum(axis="columns")
# Take the cumulative sum to stack
curves[cols] = curves[cols].cumsum(axis="columns")
# Normalize by row sum to fill
if multiple == "fill":
curves[cols] = curves[cols].div(norm_constant, axis="index")
# Define where each segment starts
baselines[cols] = curves[cols].shift(1, axis=1).fillna(0)
if multiple == "dodge":
# Account for the unique semantic (non-faceting) levels
# This will require rethiniking if we add other semantics!
hue_levels = self.var_levels["hue"]
n = len(hue_levels)
f_fwd, f_inv = self._get_scale_transforms(self.data_variable)
for key in curves:
level = dict(key)["hue"]
hist = curves[key].reset_index(name="heights")
level_idx = hue_levels.index(level)
a = f_fwd(hist["edges"])
b = f_fwd(hist["edges"] + hist["widths"])
w = (b - a) / n
new_min = f_inv(a + level_idx * w)
new_max = f_inv(a + (level_idx + 1) * w)
hist["widths"] = new_max - new_min
hist["edges"] = new_min
curves[key] = hist.set_index(["edges", "widths"])["heights"]
return curves, baselines
# -------------------------------------------------------------------------------- #
# Computation
# -------------------------------------------------------------------------------- #
def _compute_univariate_density(
self,
data_variable,
common_norm,
common_grid,
estimate_kws,
warn_singular=True,
):
# Initialize the estimator object
estimator = KDE(**estimate_kws)
if set(self.variables) - {"x", "y"}:
if common_grid:
all_observations = self.comp_data.dropna()
estimator.define_support(all_observations[data_variable])
else:
common_norm = False
all_data = self.plot_data.dropna()
if common_norm and "weights" in all_data:
whole_weight = all_data["weights"].sum()
else:
whole_weight = len(all_data)
densities = {}
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
# Extract the data points from this sub set and remove nulls
observations = sub_data[data_variable]
# Extract the weights for this subset of observations
if "weights" in self.variables:
weights = sub_data["weights"]
part_weight = weights.sum()
else:
weights = None
part_weight = len(sub_data)
# Estimate the density of observations at this level
variance = np.nan_to_num(observations.var())
singular = len(observations) < 2 or math.isclose(variance, 0)
try:
if not singular:
# Convoluted approach needed because numerical failures
# can manifest in a few different ways.
density, support = estimator(observations, weights=weights)
except np.linalg.LinAlgError:
singular = True
if singular:
msg = (
"Dataset has 0 variance; skipping density estimate. "
"Pass `warn_singular=False` to disable this warning."
)
if warn_singular:
warnings.warn(msg, UserWarning, stacklevel=4)
continue
# Invert the scaling of the support points
_, f_inv = self._get_scale_transforms(self.data_variable)
support = f_inv(support)
# Apply a scaling factor so that the integral over all subsets is 1
if common_norm:
density *= part_weight / whole_weight
# Store the density for this level
key = tuple(sub_vars.items())
densities[key] = pd.Series(density, index=support)
return densities
# -------------------------------------------------------------------------------- #
# Plotting
# -------------------------------------------------------------------------------- #
def plot_univariate_histogram(
self,
multiple,
element,
fill,
common_norm,
common_bins,
shrink,
kde,
kde_kws,
color,
legend,
line_kws,
estimate_kws,
**plot_kws,
):
# -- Default keyword dicts
kde_kws = {} if kde_kws is None else kde_kws.copy()
line_kws = {} if line_kws is None else line_kws.copy()
estimate_kws = {} if estimate_kws is None else estimate_kws.copy()
# -- Input checking
_check_argument("multiple", ["layer", "stack", "fill", "dodge"], multiple)
_check_argument("element", ["bars", "step", "poly"], element)
auto_bins_with_weights = (
"weights" in self.variables
and estimate_kws["bins"] == "auto"
and estimate_kws["binwidth"] is None
and not estimate_kws["discrete"]
)
if auto_bins_with_weights:
msg = (
"`bins` cannot be 'auto' when using weights. "
"Setting `bins=10`, but you will likely want to adjust."
)
warnings.warn(msg, UserWarning)
estimate_kws["bins"] = 10
# Simplify downstream code if we are not normalizing
if estimate_kws["stat"] == "count":
common_norm = False
orient = self.data_variable
# Now initialize the Histogram estimator
estimator = Hist(**estimate_kws)
histograms = {}
# Do pre-compute housekeeping related to multiple groups
all_data = self.comp_data.dropna()
all_weights = all_data.get("weights", None)
multiple_histograms = set(self.variables) - {"x", "y"}
if multiple_histograms:
if common_bins:
bin_kws = estimator._define_bin_params(all_data, orient, None)
else:
common_norm = False
if common_norm and all_weights is not None:
whole_weight = all_weights.sum()
else:
whole_weight = len(all_data)
# Estimate the smoothed kernel densities, for use later
if kde:
# TODO alternatively, clip at min/max bins?
kde_kws.setdefault("cut", 0)
kde_kws["cumulative"] = estimate_kws["cumulative"]
densities = self._compute_univariate_density(
self.data_variable,
common_norm,
common_bins,
kde_kws,
warn_singular=False,
)
# First pass through the data to compute the histograms
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
# Prepare the relevant data
key = tuple(sub_vars.items())
orient = self.data_variable
if "weights" in self.variables:
sub_data["weight"] = sub_data.pop("weights")
part_weight = sub_data["weight"].sum()
else:
part_weight = len(sub_data)
# Do the histogram computation
if not (multiple_histograms and common_bins):
bin_kws = estimator._define_bin_params(sub_data, orient, None)
res = estimator._normalize(estimator._eval(sub_data, orient, bin_kws))
heights = res[estimator.stat].to_numpy()
widths = res["space"].to_numpy()
edges = res[orient].to_numpy() - widths / 2
# Rescale the smoothed curve to match the histogram
if kde and key in densities:
density = densities[key]
if estimator.cumulative:
hist_norm = heights.max()
else:
hist_norm = (heights * widths).sum()
densities[key] *= hist_norm
# Convert edges back to original units for plotting
ax = self._get_axes(sub_vars)
_, inv = _get_transform_functions(ax, self.data_variable)
widths = inv(edges + widths) - inv(edges)
edges = inv(edges)
# Pack the histogram data and metadata together
edges = edges + (1 - shrink) / 2 * widths
widths *= shrink
index = pd.MultiIndex.from_arrays([
pd.Index(edges, name="edges"),
pd.Index(widths, name="widths"),
])
hist = pd.Series(heights, index=index, name="heights")
# Apply scaling to normalize across groups
if common_norm:
hist *= part_weight / whole_weight
# Store the finalized histogram data for future plotting
histograms[key] = hist
# Modify the histogram and density data to resolve multiple groups
histograms, baselines = self._resolve_multiple(histograms, multiple)
if kde:
densities, _ = self._resolve_multiple(
densities, None if multiple == "dodge" else multiple
)
# Set autoscaling-related meta
sticky_stat = (0, 1) if multiple == "fill" else (0, np.inf)
if multiple == "fill":
# Filled plots should not have any margins
bin_vals = histograms.index.to_frame()
edges = bin_vals["edges"]
widths = bin_vals["widths"]
sticky_data = (
edges.min(),
edges.max() + widths.loc[edges.idxmax()]
)
else:
sticky_data = []
# --- Handle default visual attributes
# Note: default linewidth is determined after plotting
# Default alpha should depend on other parameters
if fill:
# Note: will need to account for other grouping semantics if added
if "hue" in self.variables and multiple == "layer":
default_alpha = .5 if element == "bars" else .25
elif kde:
default_alpha = .5
else:
default_alpha = .75
else:
default_alpha = 1
alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter?
hist_artists = []
# Go back through the dataset and draw the plots
for sub_vars, _ in self.iter_data("hue", reverse=True):
key = tuple(sub_vars.items())
hist = histograms[key].rename("heights").reset_index()
bottom = np.asarray(baselines[key])
ax = self._get_axes(sub_vars)
# Define the matplotlib attributes that depend on semantic mapping
if "hue" in self.variables:
sub_color = self._hue_map(sub_vars["hue"])
else:
sub_color = color
artist_kws = self._artist_kws(
plot_kws, fill, element, multiple, sub_color, alpha
)
if element == "bars":
# Use matplotlib bar plotting
plot_func = ax.bar if self.data_variable == "x" else ax.barh
artists = plot_func(
hist["edges"],
hist["heights"] - bottom,
hist["widths"],
bottom,
align="edge",
**artist_kws,
)
for bar in artists:
if self.data_variable == "x":
bar.sticky_edges.x[:] = sticky_data
bar.sticky_edges.y[:] = sticky_stat
else:
bar.sticky_edges.x[:] = sticky_stat
bar.sticky_edges.y[:] = sticky_data
hist_artists.extend(artists)
else:
# Use either fill_between or plot to draw hull of histogram
if element == "step":
final = hist.iloc[-1]
x = np.append(hist["edges"], final["edges"] + final["widths"])
y = np.append(hist["heights"], final["heights"])
b = np.append(bottom, bottom[-1])
if self.data_variable == "x":
step = "post"
drawstyle = "steps-post"
else:
step = "post" # fillbetweenx handles mapping internally
drawstyle = "steps-pre"
elif element == "poly":
x = hist["edges"] + hist["widths"] / 2
y = hist["heights"]
b = bottom
step = None
drawstyle = None
if self.data_variable == "x":
if fill:
artist = ax.fill_between(x, b, y, step=step, **artist_kws)
else:
artist, = ax.plot(x, y, drawstyle=drawstyle, **artist_kws)
artist.sticky_edges.x[:] = sticky_data
artist.sticky_edges.y[:] = sticky_stat
else:
if fill:
artist = ax.fill_betweenx(x, b, y, step=step, **artist_kws)
else:
artist, = ax.plot(y, x, drawstyle=drawstyle, **artist_kws)
artist.sticky_edges.x[:] = sticky_stat
artist.sticky_edges.y[:] = sticky_data
hist_artists.append(artist)
if kde:
# Add in the density curves
try:
density = densities[key]
except KeyError:
continue
support = density.index
if "x" in self.variables:
line_args = support, density
sticky_x, sticky_y = None, (0, np.inf)
else:
line_args = density, support
sticky_x, sticky_y = (0, np.inf), None
line_kws["color"] = to_rgba(sub_color, 1)
line, = ax.plot(
*line_args, **line_kws,
)
if sticky_x is not None:
line.sticky_edges.x[:] = sticky_x
if sticky_y is not None:
line.sticky_edges.y[:] = sticky_y
if element == "bars" and "linewidth" not in plot_kws:
# Now we handle linewidth, which depends on the scaling of the plot
# We will base everything on the minimum bin width
hist_metadata = pd.concat([
# Use .items for generality over dict or df
h.index.to_frame() for _, h in histograms.items()
]).reset_index(drop=True)
thin_bar_idx = hist_metadata["widths"].idxmin()
binwidth = hist_metadata.loc[thin_bar_idx, "widths"]
left_edge = hist_metadata.loc[thin_bar_idx, "edges"]
# Set initial value
default_linewidth = math.inf
# Loop through subsets based only on facet variables
for sub_vars, _ in self.iter_data():
ax = self._get_axes(sub_vars)
# Needed in some cases to get valid transforms.
# Innocuous in other cases?
ax.autoscale_view()
# Convert binwidth from data coordinates to pixels
pts_x, pts_y = 72 / ax.figure.dpi * abs(
ax.transData.transform([left_edge + binwidth] * 2)
- ax.transData.transform([left_edge] * 2)
)
if self.data_variable == "x":
binwidth_points = pts_x
else:
binwidth_points = pts_y
# The relative size of the lines depends on the appearance
# This is a provisional value and may need more tweaking
default_linewidth = min(.1 * binwidth_points, default_linewidth)
# Set the attributes
for bar in hist_artists:
# Don't let the lines get too thick
max_linewidth = bar.get_linewidth()
if not fill:
max_linewidth *= 1.5
linewidth = min(default_linewidth, max_linewidth)
# If not filling, don't let lines disappear
if not fill:
min_linewidth = .5
linewidth = max(linewidth, min_linewidth)
bar.set_linewidth(linewidth)
# --- Finalize the plot ----
# Axis labels
ax = self.ax if self.ax is not None else self.facets.axes.flat[0]
default_x = default_y = ""
if self.data_variable == "x":
default_y = estimator.stat.capitalize()
if self.data_variable == "y":
default_x = estimator.stat.capitalize()
self._add_axis_labels(ax, default_x, default_y)
# Legend for semantic variables
if "hue" in self.variables and legend:
if fill or element == "bars":
artist = partial(mpl.patches.Patch)
else:
artist = partial(mpl.lines.Line2D, [], [])
ax_obj = self.ax if self.ax is not None else self.facets
self._add_legend(
ax_obj, artist, fill, element, multiple, alpha, plot_kws, {},
)
def plot_bivariate_histogram(
self,
common_bins, common_norm,
thresh, pthresh, pmax,
color, legend,
cbar, cbar_ax, cbar_kws,
estimate_kws,
**plot_kws,
):
# Default keyword dicts
cbar_kws = {} if cbar_kws is None else cbar_kws.copy()
# Now initialize the Histogram estimator
estimator = Histogram(**estimate_kws)
# Do pre-compute housekeeping related to multiple groups
if set(self.variables) - {"x", "y"}:
all_data = self.comp_data.dropna()
if common_bins:
estimator.define_bin_params(
all_data["x"],
all_data["y"],
all_data.get("weights", None),
)
else:
common_norm = False
# -- Determine colormap threshold and norm based on the full data
full_heights = []
for _, sub_data in self.iter_data(from_comp_data=True):
sub_heights, _ = estimator(
sub_data["x"], sub_data["y"], sub_data.get("weights", None)
)
full_heights.append(sub_heights)
common_color_norm = not set(self.variables) - {"x", "y"} or common_norm
if pthresh is not None and common_color_norm:
thresh = self._quantile_to_level(full_heights, pthresh)
plot_kws.setdefault("vmin", 0)
if common_color_norm:
if pmax is not None:
vmax = self._quantile_to_level(full_heights, pmax)
else:
vmax = plot_kws.pop("vmax", max(map(np.max, full_heights)))
else:
vmax = None
# Get a default color
# (We won't follow the color cycle here, as multiple plots are unlikely)
if color is None:
color = "C0"
# --- Loop over data (subsets) and draw the histograms
for sub_vars, sub_data in self.iter_data("hue", from_comp_data=True):
if sub_data.empty:
continue
# Do the histogram computation
heights, (x_edges, y_edges) = estimator(
sub_data["x"],
sub_data["y"],
weights=sub_data.get("weights", None),
)
# Get the axes for this plot
ax = self._get_axes(sub_vars)
# Invert the scale for the edges
_, inv_x = _get_transform_functions(ax, "x")
_, inv_y = _get_transform_functions(ax, "y")
x_edges = inv_x(x_edges)
y_edges = inv_y(y_edges)
# Apply scaling to normalize across groups
if estimator.stat != "count" and common_norm:
heights *= len(sub_data) / len(all_data)
# Define the specific kwargs for this artist
artist_kws = plot_kws.copy()
if "hue" in self.variables:
color = self._hue_map(sub_vars["hue"])
cmap = self._cmap_from_color(color)
artist_kws["cmap"] = cmap
else:
cmap = artist_kws.pop("cmap", None)
if isinstance(cmap, str):
cmap = color_palette(cmap, as_cmap=True)
elif cmap is None:
cmap = self._cmap_from_color(color)
artist_kws["cmap"] = cmap
# Set the upper norm on the colormap
if not common_color_norm and pmax is not None:
vmax = self._quantile_to_level(heights, pmax)
if vmax is not None:
artist_kws["vmax"] = vmax
# Make cells at or below the threshold transparent
if not common_color_norm and pthresh:
thresh = self._quantile_to_level(heights, pthresh)
if thresh is not None:
heights = np.ma.masked_less_equal(heights, thresh)
# pcolormesh is going to turn the grid off, but we want to keep it
# I'm not sure if there's a better way to get the grid state
x_grid = any([l.get_visible() for l in ax.xaxis.get_gridlines()])
y_grid = any([l.get_visible() for l in ax.yaxis.get_gridlines()])
mesh = ax.pcolormesh(
x_edges,
y_edges,
heights.T,
**artist_kws,
)
# pcolormesh sets sticky edges, but we only want them if not thresholding
if thresh is not None:
mesh.sticky_edges.x[:] = []
mesh.sticky_edges.y[:] = []
# Add an optional colorbar
# Note, we want to improve this. When hue is used, it will stack
# multiple colorbars with redundant ticks in an ugly way.
# But it's going to take some work to have multiple colorbars that
# share ticks nicely.
if cbar:
ax.figure.colorbar(mesh, cbar_ax, ax, **cbar_kws)
# Reset the grid state
if x_grid:
ax.grid(True, axis="x")
if y_grid:
ax.grid(True, axis="y")
# --- Finalize the plot
ax = self.ax if self.ax is not None else self.facets.axes.flat[0]
self._add_axis_labels(ax)
if "hue" in self.variables and legend:
# TODO if possible, I would like to move the contour
# intensity information into the legend too and label the
# iso proportions rather than the raw density values
artist_kws = {}
artist = partial(mpl.patches.Patch)
ax_obj = self.ax if self.ax is not None else self.facets
self._add_legend(
ax_obj, artist, True, False, "layer", 1, artist_kws, {},
)
def plot_univariate_density(
self,
multiple,
common_norm,
common_grid,
warn_singular,
fill,
color,
legend,
estimate_kws,
**plot_kws,
):
# Handle conditional defaults
if fill is None:
fill = multiple in ("stack", "fill")
# Preprocess the matplotlib keyword dictionaries
if fill:
artist = mpl.collections.PolyCollection
else:
artist = mpl.lines.Line2D
plot_kws = _normalize_kwargs(plot_kws, artist)
# Input checking
_check_argument("multiple", ["layer", "stack", "fill"], multiple)
# Always share the evaluation grid when stacking
subsets = bool(set(self.variables) - {"x", "y"})
if subsets and multiple in ("stack", "fill"):
common_grid = True
# Do the computation
densities = self._compute_univariate_density(
self.data_variable,
common_norm,
common_grid,
estimate_kws,
warn_singular,
)
# Adjust densities based on the `multiple` rule
densities, baselines = self._resolve_multiple(densities, multiple)
# Control the interaction with autoscaling by defining sticky_edges
# i.e. we don't want autoscale margins below the density curve
sticky_density = (0, 1) if multiple == "fill" else (0, np.inf)
if multiple == "fill":
# Filled plots should not have any margins
sticky_support = densities.index.min(), densities.index.max()
else:
sticky_support = []
if fill:
if multiple == "layer":
default_alpha = .25
else:
default_alpha = .75
else:
default_alpha = 1
alpha = plot_kws.pop("alpha", default_alpha) # TODO make parameter?
# Now iterate through the subsets and draw the densities
# We go backwards so stacked densities read from top-to-bottom
for sub_vars, _ in self.iter_data("hue", reverse=True):
# Extract the support grid and density curve for this level
key = tuple(sub_vars.items())
try:
density = densities[key]
except KeyError:
continue
support = density.index
fill_from = baselines[key]
ax = self._get_axes(sub_vars)
if "hue" in self.variables:
sub_color = self._hue_map(sub_vars["hue"])
else:
sub_color = color
artist_kws = self._artist_kws(
plot_kws, fill, False, multiple, sub_color, alpha
)
# Either plot a curve with observation values on the x axis
if "x" in self.variables:
if fill:
artist = ax.fill_between(support, fill_from, density, **artist_kws)
else:
artist, = ax.plot(support, density, **artist_kws)
artist.sticky_edges.x[:] = sticky_support
artist.sticky_edges.y[:] = sticky_density
# Or plot a curve with observation values on the y axis
else:
if fill:
artist = ax.fill_betweenx(support, fill_from, density, **artist_kws)
else: