Debian Codegraph @

tests/test_categorical.py

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 import itertools
2 from functools import partial
3 import warnings
4
5 import numpy as np
6 import pandas as pd
7 import matplotlib as mpl
8 import matplotlib.pyplot as plt
9 from matplotlib.colors import same_color, to_rgb, to_rgba
10
11 import pytest
12 from pytest import approx
13 from numpy.testing import (
14 assert_array_equal,
15 assert_array_less,
16 assert_array_almost_equal,
17 )
18
19 from seaborn import categorical as cat
20
21 from seaborn._base import categorical_order
22 from seaborn._compat import get_colormap, get_legend_handles
23 from seaborn._testing import assert_plots_equal
24 from seaborn.categorical import (
25 _CategoricalPlotter,
26 Beeswarm,
27 BoxPlotContainer,
28 catplot,
29 barplot,
30 boxplot,
31 boxenplot,
32 countplot,
33 pointplot,
34 stripplot,
35 swarmplot,
36 violinplot,
37 )
38 from seaborn.palettes import color_palette
39 from seaborn.utils import _draw_figure, _version_predates, desaturate
40
41
42 PLOT_FUNCS = [
43 catplot,
44 barplot,
45 boxplot,
46 boxenplot,
47 pointplot,
48 stripplot,
49 swarmplot,
50 violinplot,
51 ]
52
53
54 class TestCategoricalPlotterNew:
55
56 @pytest.mark.parametrize(
57 "func,kwargs",
58 itertools.product(
59 PLOT_FUNCS,
60 [
61 {"x": "x", "y": "a"},
62 {"x": "a", "y": "y"},
63 {"x": "y"},
64 {"y": "x"},
65 ],
66 ),
67 )
68 def test_axis_labels(self, long_df, func, kwargs):
69
70 func(data=long_df, **kwargs)
71
72 ax = plt.gca()
73 for axis in "xy":
74 val = kwargs.get(axis, "")
75 label_func = getattr(ax, f"get_{axis}label")
76 assert label_func() == val
77
78 @pytest.mark.parametrize("func", PLOT_FUNCS)
79 def test_empty(self, func):
80
81 func()
82 ax = plt.gca()
83 assert not ax.collections
84 assert not ax.patches
85 assert not ax.lines
86
87 func(x=[], y=[])
88 ax = plt.gca()
89 assert not ax.collections
90 assert not ax.patches
91 assert not ax.lines
92
93 def test_redundant_hue_backcompat(self, long_df):
94
95 p = _CategoricalPlotter(
96 data=long_df,
97 variables={"x": "s", "y": "y"},
98 )
99
100 color = None
101 palette = dict(zip(long_df["s"].unique(), color_palette()))
102 hue_order = None
103
104 palette, _ = p._hue_backcompat(color, palette, hue_order, force_hue=True)
105
106 assert p.variables["hue"] == "s"
107 assert_array_equal(p.plot_data["hue"], p.plot_data["x"])
108 assert all(isinstance(k, str) for k in palette)
109
110
111 class SharedAxesLevelTests:
112
113 def orient_indices(self, orient):
114 pos_idx = ["x", "y"].index(orient)
115 val_idx = ["y", "x"].index(orient)
116 return pos_idx, val_idx
117
118 @pytest.fixture
119 def common_kws(self):
120 return {}
121
122 @pytest.mark.parametrize("orient", ["x", "y"])
123 def test_labels_long(self, long_df, orient):
124
125 depend = {"x": "y", "y": "x"}[orient]
126 kws = {orient: "a", depend: "y", "hue": "b"}
127
128 ax = self.func(long_df, **kws)
129
130 # To populate texts; only needed on older matplotlibs
131 _draw_figure(ax.figure)
132
133 assert getattr(ax, f"get_{orient}label")() == kws[orient]
134 assert getattr(ax, f"get_{depend}label")() == kws[depend]
135
136 get_ori_labels = getattr(ax, f"get_{orient}ticklabels")
137 ori_labels = [t.get_text() for t in get_ori_labels()]
138 ori_levels = categorical_order(long_df[kws[orient]])
139 assert ori_labels == ori_levels
140
141 legend = ax.get_legend()
142 assert legend.get_title().get_text() == kws["hue"]
143
144 hue_labels = [t.get_text() for t in legend.texts]
145 hue_levels = categorical_order(long_df[kws["hue"]])
146 assert hue_labels == hue_levels
147
148 def test_labels_wide(self, wide_df):
149
150 wide_df = wide_df.rename_axis("cols", axis=1)
151 ax = self.func(wide_df)
152
153 # To populate texts; only needed on older matplotlibs
154 _draw_figure(ax.figure)
155
156 assert ax.get_xlabel() == wide_df.columns.name
157 labels = [t.get_text() for t in ax.get_xticklabels()]
158 for label, level in zip(labels, wide_df.columns):
159 assert label == level
160
161 def test_labels_hue_order(self, long_df):
162
163 hue_var = "b"
164 hue_order = categorical_order(long_df[hue_var])[::-1]
165 ax = self.func(long_df, x="a", y="y", hue=hue_var, hue_order=hue_order)
166 legend = ax.get_legend()
167 hue_labels = [t.get_text() for t in legend.texts]
168 assert hue_labels == hue_order
169
170 def test_color(self, long_df, common_kws):
171 common_kws.update(data=long_df, x="a", y="y")
172
173 ax = plt.figure().subplots()
174 self.func(ax=ax, **common_kws)
175 assert self.get_last_color(ax) == to_rgba("C0")
176
177 ax = plt.figure().subplots()
178 self.func(ax=ax, **common_kws)
179 self.func(ax=ax, **common_kws)
180 assert self.get_last_color(ax) == to_rgba("C1")
181
182 ax = plt.figure().subplots()
183 self.func(color="C2", ax=ax, **common_kws)
184 assert self.get_last_color(ax) == to_rgba("C2")
185
186 ax = plt.figure().subplots()
187 self.func(color="C3", ax=ax, **common_kws)
188 assert self.get_last_color(ax) == to_rgba("C3")
189
190 def test_two_calls(self):
191
192 ax = plt.figure().subplots()
193 self.func(x=["a", "b", "c"], y=[1, 2, 3], ax=ax)
194 self.func(x=["e", "f"], y=[4, 5], ax=ax)
195 assert ax.get_xlim() == (-.5, 4.5)
196
197 def test_redundant_hue_legend(self, long_df):
198
199 ax = self.func(long_df, x="a", y="y", hue="a")
200 assert ax.get_legend() is None
201 ax.clear()
202
203 self.func(long_df, x="a", y="y", hue="a", legend=True)
204 assert ax.get_legend() is not None
205
206 @pytest.mark.parametrize("orient", ["x", "y"])
207 def test_log_scale(self, long_df, orient):
208
209 depvar = {"x": "y", "y": "x"}[orient]
210 variables = {orient: "a", depvar: "z"}
211 ax = self.func(long_df, **variables, log_scale=True)
212 assert getattr(ax, f"get_{orient}scale")() == "linear"
213 assert getattr(ax, f"get_{depvar}scale")() == "log"
214
215
216 class SharedScatterTests(SharedAxesLevelTests):
217 """Tests functionality common to stripplot and swarmplot."""
218
219 def get_last_color(self, ax):
220
221 colors = ax.collections[-1].get_facecolors()
222 unique_colors = np.unique(colors, axis=0)
223 assert len(unique_colors) == 1
224 return to_rgba(unique_colors.squeeze())
225
226 # ------------------------------------------------------------------------------
227
228 def test_color(self, long_df, common_kws):
229
230 super().test_color(long_df, common_kws)
231
232 ax = plt.figure().subplots()
233 self.func(data=long_df, x="a", y="y", facecolor="C4", ax=ax)
234 assert self.get_last_color(ax) == to_rgba("C4")
235
236 ax = plt.figure().subplots()
237 self.func(data=long_df, x="a", y="y", fc="C5", ax=ax)
238 assert self.get_last_color(ax) == to_rgba("C5")
239
240 def test_supplied_color_array(self, long_df):
241
242 cmap = get_colormap("Blues")
243 norm = mpl.colors.Normalize()
244 colors = cmap(norm(long_df["y"].to_numpy()))
245
246 keys = ["c", "fc", "facecolor", "facecolors"]
247
248 for key in keys:
249
250 ax = plt.figure().subplots()
251 self.func(x=long_df["y"], **{key: colors})
252 _draw_figure(ax.figure)
253 assert_array_equal(ax.collections[0].get_facecolors(), colors)
254
255 ax = plt.figure().subplots()
256 self.func(x=long_df["y"], c=long_df["y"], cmap=cmap)
257 _draw_figure(ax.figure)
258 assert_array_equal(ax.collections[0].get_facecolors(), colors)
259
260 def test_unfilled_marker(self, long_df):
261
262 with warnings.catch_warnings():
263 warnings.simplefilter("error", UserWarning)
264 ax = self.func(long_df, x="y", y="a", marker="x", color="r")
265 for points in ax.collections:
266 assert same_color(points.get_facecolors().squeeze(), "r")
267 assert same_color(points.get_edgecolors().squeeze(), "r")
268
269 @pytest.mark.parametrize(
270 "orient,data_type", [
271 ("h", "dataframe"), ("h", "dict"),
272 ("v", "dataframe"), ("v", "dict"),
273 ("y", "dataframe"), ("y", "dict"),
274 ("x", "dataframe"), ("x", "dict"),
275 ]
276 )
277 def test_wide(self, wide_df, orient, data_type):
278
279 if data_type == "dict":
280 wide_df = {k: v.to_numpy() for k, v in wide_df.items()}
281
282 ax = self.func(data=wide_df, orient=orient, color="C0")
283 _draw_figure(ax.figure)
284
285 cat_idx = 0 if orient in "vx" else 1
286 val_idx = int(not cat_idx)
287
288 axis_objs = ax.xaxis, ax.yaxis
289 cat_axis = axis_objs[cat_idx]
290
291 for i, label in enumerate(cat_axis.get_majorticklabels()):
292
293 key = label.get_text()
294 points = ax.collections[i]
295 point_pos = points.get_offsets().T
296 val_pos = point_pos[val_idx]
297 cat_pos = point_pos[cat_idx]
298
299 assert_array_equal(cat_pos.round(), i)
300 assert_array_equal(val_pos, wide_df[key])
301
302 for point_color in points.get_facecolors():
303 assert tuple(point_color) == to_rgba("C0")
304
305 @pytest.mark.parametrize("orient", ["h", "v"])
306 def test_flat(self, flat_series, orient):
307
308 ax = self.func(data=flat_series, orient=orient)
309 _draw_figure(ax.figure)
310
311 cat_idx = ["v", "h"].index(orient)
312 val_idx = int(not cat_idx)
313
314 points = ax.collections[0]
315 pos = points.get_offsets().T
316
317 assert_array_equal(pos[cat_idx].round(), np.zeros(len(flat_series)))
318 assert_array_equal(pos[val_idx], flat_series)
319
320 @pytest.mark.parametrize(
321 "variables,orient",
322 [
323 # Order matters for assigning to x/y
324 ({"cat": "a", "val": "y", "hue": None}, None),
325 ({"val": "y", "cat": "a", "hue": None}, None),
326 ({"cat": "a", "val": "y", "hue": "a"}, None),
327 ({"val": "y", "cat": "a", "hue": "a"}, None),
328 ({"cat": "a", "val": "y", "hue": "b"}, None),
329 ({"val": "y", "cat": "a", "hue": "x"}, None),
330 ({"cat": "s", "val": "y", "hue": None}, None),
331 ({"val": "y", "cat": "s", "hue": None}, "h"),
332 ({"cat": "a", "val": "b", "hue": None}, None),
333 ({"val": "a", "cat": "b", "hue": None}, "h"),
334 ({"cat": "a", "val": "t", "hue": None}, None),
335 ({"val": "t", "cat": "a", "hue": None}, None),
336 ({"cat": "d", "val": "y", "hue": None}, None),
337 ({"val": "y", "cat": "d", "hue": None}, None),
338 ({"cat": "a_cat", "val": "y", "hue": None}, None),
339 ({"val": "y", "cat": "s_cat", "hue": None}, None),
340 ],
341 )
342 def test_positions(self, long_df, variables, orient):
343
344 cat_var = variables["cat"]
345 val_var = variables["val"]
346 hue_var = variables["hue"]
347 var_names = list(variables.values())
348 x_var, y_var, *_ = var_names
349
350 ax = self.func(
351 data=long_df, x=x_var, y=y_var, hue=hue_var, orient=orient,
352 )
353
354 _draw_figure(ax.figure)
355
356 cat_idx = var_names.index(cat_var)
357 val_idx = var_names.index(val_var)
358
359 axis_objs = ax.xaxis, ax.yaxis
360 cat_axis = axis_objs[cat_idx]
361 val_axis = axis_objs[val_idx]
362
363 cat_data = long_df[cat_var]
364 cat_levels = categorical_order(cat_data)
365
366 for i, label in enumerate(cat_levels):
367
368 vals = long_df.loc[cat_data == label, val_var]
369
370 points = ax.collections[i].get_offsets().T
371 cat_pos = points[var_names.index(cat_var)]
372 val_pos = points[var_names.index(val_var)]
373
374 assert_array_equal(val_pos, val_axis.convert_units(vals))
375 assert_array_equal(cat_pos.round(), i)
376 assert 0 <= np.ptp(cat_pos) <= .8
377
378 label = pd.Index([label]).astype(str)[0]
379 assert cat_axis.get_majorticklabels()[i].get_text() == label
380
381 @pytest.mark.parametrize(
382 "variables",
383 [
384 # Order matters for assigning to x/y
385 {"cat": "a", "val": "y", "hue": "b"},
386 {"val": "y", "cat": "a", "hue": "c"},
387 {"cat": "a", "val": "y", "hue": "f"},
388 ],
389 )
390 def test_positions_dodged(self, long_df, variables):
391
392 cat_var = variables["cat"]
393 val_var = variables["val"]
394 hue_var = variables["hue"]
395 var_names = list(variables.values())
396 x_var, y_var, *_ = var_names
397
398 ax = self.func(
399 data=long_df, x=x_var, y=y_var, hue=hue_var, dodge=True,
400 )
401
402 cat_vals = categorical_order(long_df[cat_var])
403 hue_vals = categorical_order(long_df[hue_var])
404
405 n_hue = len(hue_vals)
406 offsets = np.linspace(0, .8, n_hue + 1)[:-1]
407 offsets -= offsets.mean()
408 nest_width = .8 / n_hue
409
410 for i, cat_val in enumerate(cat_vals):
411 for j, hue_val in enumerate(hue_vals):
412 rows = (long_df[cat_var] == cat_val) & (long_df[hue_var] == hue_val)
413 vals = long_df.loc[rows, val_var]
414
415 points = ax.collections[n_hue * i + j].get_offsets().T
416 cat_pos = points[var_names.index(cat_var)]
417 val_pos = points[var_names.index(val_var)]
418
419 if pd.api.types.is_datetime64_any_dtype(vals):
420 vals = mpl.dates.date2num(vals)
421
422 assert_array_equal(val_pos, vals)
423
424 assert_array_equal(cat_pos.round(), i)
425 assert_array_equal((cat_pos - (i + offsets[j])).round() / nest_width, 0)
426 assert 0 <= np.ptp(cat_pos) <= nest_width
427
428 @pytest.mark.parametrize("cat_var", ["a", "s", "d"])
429 def test_positions_unfixed(self, long_df, cat_var):
430
431 long_df = long_df.sort_values(cat_var)
432
433 kws = dict(size=.001)
434 if "stripplot" in str(self.func): # can't use __name__ with partial
435 kws["jitter"] = False
436
437 ax = self.func(data=long_df, x=cat_var, y="y", native_scale=True, **kws)
438
439 for i, (cat_level, cat_data) in enumerate(long_df.groupby(cat_var)):
440
441 points = ax.collections[i].get_offsets().T
442 cat_pos = points[0]
443 val_pos = points[1]
444
445 assert_array_equal(val_pos, cat_data["y"])
446
447 comp_level = np.squeeze(ax.xaxis.convert_units(cat_level)).item()
448 assert_array_equal(cat_pos.round(), comp_level)
449
450 @pytest.mark.parametrize(
451 "x_type,order",
452 [
453 (str, None),
454 (str, ["a", "b", "c"]),
455 (str, ["c", "a"]),
456 (str, ["a", "b", "c", "d"]),
457 (int, None),
458 (int, [3, 1, 2]),
459 (int, [3, 1]),
460 (int, [1, 2, 3, 4]),
461 (int, ["3", "1", "2"]),
462 ]
463 )
464 def test_order(self, x_type, order):
465
466 if x_type is str:
467 x = ["b", "a", "c"]
468 else:
469 x = [2, 1, 3]
470 y = [1, 2, 3]
471
472 ax = self.func(x=x, y=y, order=order)
473 _draw_figure(ax.figure)
474
475 if order is None:
476 order = x
477 if x_type is int:
478 order = np.sort(order)
479
480 assert len(ax.collections) == len(order)
481 tick_labels = ax.xaxis.get_majorticklabels()
482
483 assert ax.get_xlim()[1] == (len(order) - .5)
484
485 for i, points in enumerate(ax.collections):
486 cat = order[i]
487 assert tick_labels[i].get_text() == str(cat)
488
489 positions = points.get_offsets()
490 if x_type(cat) in x:
491 val = y[x.index(x_type(cat))]
492 assert positions[0, 1] == val
493 else:
494 assert not positions.size
495
496 @pytest.mark.parametrize("hue_var", ["a", "b"])
497 def test_hue_categorical(self, long_df, hue_var):
498
499 cat_var = "b"
500
501 hue_levels = categorical_order(long_df[hue_var])
502 cat_levels = categorical_order(long_df[cat_var])
503
504 pal_name = "muted"
505 palette = dict(zip(hue_levels, color_palette(pal_name)))
506 ax = self.func(data=long_df, x=cat_var, y="y", hue=hue_var, palette=pal_name)
507
508 for i, level in enumerate(cat_levels):
509
510 sub_df = long_df[long_df[cat_var] == level]
511 point_hues = sub_df[hue_var]
512
513 points = ax.collections[i]
514 point_colors = points.get_facecolors()
515
516 assert len(point_hues) == len(point_colors)
517
518 for hue, color in zip(point_hues, point_colors):
519 assert tuple(color) == to_rgba(palette[hue])
520
521 @pytest.mark.parametrize("hue_var", ["a", "b"])
522 def test_hue_dodged(self, long_df, hue_var):
523
524 ax = self.func(data=long_df, x="y", y="a", hue=hue_var, dodge=True)
525 colors = color_palette(n_colors=long_df[hue_var].nunique())
526 collections = iter(ax.collections)
527
528 # Slightly awkward logic to handle challenges of how the artists work.
529 # e.g. there are empty scatter collections but the because facecolors
530 # for the empty collections will return the default scatter color
531 while colors:
532 points = next(collections)
533 if points.get_offsets().any():
534 face_color = tuple(points.get_facecolors()[0])
535 expected_color = to_rgba(colors.pop(0))
536 assert face_color == expected_color
537
538 @pytest.mark.parametrize(
539 "val_var,val_col,hue_col",
540 list(itertools.product(["x", "y"], ["b", "y", "t"], [None, "a"])),
541 )
542 def test_single(self, long_df, val_var, val_col, hue_col):
543
544 var_kws = {val_var: val_col, "hue": hue_col}
545 ax = self.func(data=long_df, **var_kws)
546 _draw_figure(ax.figure)
547
548 axis_vars = ["x", "y"]
549 val_idx = axis_vars.index(val_var)
550 cat_idx = int(not val_idx)
551 cat_var = axis_vars[cat_idx]
552
553 cat_axis = getattr(ax, f"{cat_var}axis")
554 val_axis = getattr(ax, f"{val_var}axis")
555
556 points = ax.collections[0]
557 point_pos = points.get_offsets().T
558 cat_pos = point_pos[cat_idx]
559 val_pos = point_pos[val_idx]
560
561 assert_array_equal(cat_pos.round(), 0)
562 assert cat_pos.max() <= .4
563 assert cat_pos.min() >= -.4
564
565 num_vals = val_axis.convert_units(long_df[val_col])
566 assert_array_equal(val_pos, num_vals)
567
568 if hue_col is not None:
569 palette = dict(zip(
570 categorical_order(long_df[hue_col]), color_palette()
571 ))
572
573 facecolors = points.get_facecolors()
574 for i, color in enumerate(facecolors):
575 if hue_col is None:
576 assert tuple(color) == to_rgba("C0")
577 else:
578 hue_level = long_df.loc[i, hue_col]
579 expected_color = palette[hue_level]
580 assert tuple(color) == to_rgba(expected_color)
581
582 ticklabels = cat_axis.get_majorticklabels()
583 assert len(ticklabels) == 1
584 assert not ticklabels[0].get_text()
585
586 def test_attributes(self, long_df):
587
588 kwargs = dict(
589 size=2,
590 linewidth=1,
591 edgecolor="C2",
592 )
593
594 ax = self.func(x=long_df["y"], **kwargs)
595 points, = ax.collections
596
597 assert points.get_sizes().item() == kwargs["size"] ** 2
598 assert points.get_linewidths().item() == kwargs["linewidth"]
599 assert tuple(points.get_edgecolors().squeeze()) == to_rgba(kwargs["edgecolor"])
600
601 def test_three_points(self):
602
603 x = np.arange(3)
604 ax = self.func(x=x)
605 for point_color in ax.collections[0].get_facecolor():
606 assert tuple(point_color) == to_rgba("C0")
607
608 def test_legend_categorical(self, long_df):
609
610 ax = self.func(data=long_df, x="y", y="a", hue="b")
611 legend_texts = [t.get_text() for t in ax.legend_.texts]
612 expected = categorical_order(long_df["b"])
613 assert legend_texts == expected
614
615 def test_legend_numeric(self, long_df):
616
617 ax = self.func(data=long_df, x="y", y="a", hue="z")
618 vals = [float(t.get_text()) for t in ax.legend_.texts]
619 assert (vals[1] - vals[0]) == approx(vals[2] - vals[1])
620
621 def test_legend_attributes(self, long_df):
622
623 kws = {"edgecolor": "r", "linewidth": 1}
624 ax = self.func(data=long_df, x="x", y="y", hue="a", **kws)
625 for pt in get_legend_handles(ax.get_legend()):
626 assert same_color(pt.get_markeredgecolor(), kws["edgecolor"])
627 assert pt.get_markeredgewidth() == kws["linewidth"]
628
629 def test_legend_disabled(self, long_df):
630
631 ax = self.func(data=long_df, x="y", y="a", hue="b", legend=False)
632 assert ax.legend_ is None
633
634 def test_palette_from_color_deprecation(self, long_df):
635
636 color = (.9, .4, .5)
637 hex_color = mpl.colors.to_hex(color)
638
639 hue_var = "a"
640 n_hue = long_df[hue_var].nunique()
641 palette = color_palette(f"dark:{hex_color}", n_hue)
642
643 with pytest.warns(FutureWarning, match="Setting a gradient palette"):
644 ax = self.func(data=long_df, x="z", hue=hue_var, color=color)
645
646 points = ax.collections[0]
647 for point_color in points.get_facecolors():
648 assert to_rgb(point_color) in palette
649
650 def test_palette_with_hue_deprecation(self, long_df):
651 palette = "Blues"
652 with pytest.warns(FutureWarning, match="Passing `palette` without"):
653 ax = self.func(data=long_df, x="a", y=long_df["y"], palette=palette)
654 strips = ax.collections
655 colors = color_palette(palette, len(strips))
656 for strip, color in zip(strips, colors):
657 assert same_color(strip.get_facecolor()[0], color)
658
659 def test_log_scale(self):
660
661 x = [1, 10, 100, 1000]
662
663 ax = plt.figure().subplots()
664 ax.set_xscale("log")
665 self.func(x=x)
666 vals = ax.collections[0].get_offsets()[:, 0]
667 assert_array_equal(x, vals)
668
669 y = [1, 2, 3, 4]
670
671 ax = plt.figure().subplots()
672 ax.set_xscale("log")
673 self.func(x=x, y=y, native_scale=True)
674 for i, point in enumerate(ax.collections):
675 val = point.get_offsets()[0, 0]
676 assert val == approx(x[i])
677
678 x = y = np.ones(100)
679
680 ax = plt.figure().subplots()
681 ax.set_yscale("log")
682 self.func(x=x, y=y, orient="h", native_scale=True)
683 cat_points = ax.collections[0].get_offsets().copy()[:, 1]
684 assert np.ptp(np.log10(cat_points)) <= .8
685
686 @pytest.mark.parametrize(
687 "kwargs",
688 [
689 dict(data="wide"),
690 dict(data="wide", orient="h"),
691 dict(data="long", x="x", color="C3"),
692 dict(data="long", y="y", hue="a", jitter=False),
693 dict(data="long", x="a", y="y", hue="z", edgecolor="w", linewidth=.5),
694 dict(data="long", x="a", y="y", hue="z", edgecolor="auto", linewidth=.5),
695 dict(data="long", x="a_cat", y="y", hue="z"),
696 dict(data="long", x="y", y="s", hue="c", orient="h", dodge=True),
697 dict(data="long", x="s", y="y", hue="c", native_scale=True),
698 ]
699 )
700 def test_vs_catplot(self, long_df, wide_df, kwargs):
701
702 kwargs = kwargs.copy()
703 if kwargs["data"] == "long":
704 kwargs["data"] = long_df
705 elif kwargs["data"] == "wide":
706 kwargs["data"] = wide_df
707
708 try:
709 name = self.func.__name__[:-4]
710 except AttributeError:
711 name = self.func.func.__name__[:-4]
712 if name == "swarm":
713 kwargs.pop("jitter", None)
714
715 np.random.seed(0) # for jitter
716 ax = self.func(**kwargs)
717
718 np.random.seed(0)
719 g = catplot(**kwargs, kind=name)
720
721 assert_plots_equal(ax, g.ax)
722
723 def test_empty_palette(self):
724 self.func(x=[], y=[], hue=[], palette=[])
725
726
727 class SharedAggTests(SharedAxesLevelTests):
728
729 def test_labels_flat(self):
730
731 ind = pd.Index(["a", "b", "c"], name="x")
732 ser = pd.Series([1, 2, 3], ind, name="y")
733
734 ax = self.func(ser)
735
736 # To populate texts; only needed on older matplotlibs
737 _draw_figure(ax.figure)
738
739 assert ax.get_xlabel() == ind.name
740 assert ax.get_ylabel() == ser.name
741 labels = [t.get_text() for t in ax.get_xticklabels()]
742 for label, level in zip(labels, ind):
743 assert label == level
744
745
746 class SharedPatchArtistTests:
747
748 @pytest.mark.parametrize("fill", [True, False])
749 def test_legend_fill(self, long_df, fill):
750
751 palette = color_palette()
752 ax = self.func(
753 long_df, x="x", y="y", hue="a",
754 saturation=1, linecolor="k", fill=fill,
755 )
756 for i, patch in enumerate(get_legend_handles(ax.get_legend())):
757 fc = patch.get_facecolor()
758 ec = patch.get_edgecolor()
759 if fill:
760 assert same_color(fc, palette[i])
761 assert same_color(ec, "k")
762 else:
763 assert fc == (0, 0, 0, 0)
764 assert same_color(ec, palette[i])
765
766 def test_legend_attributes(self, long_df):
767
768 ax = self.func(long_df, x="x", y="y", hue="a", linewidth=3)
769 for patch in get_legend_handles(ax.get_legend()):
770 assert patch.get_linewidth() == 3
771
772
773 class TestStripPlot(SharedScatterTests):
774
775 func = staticmethod(stripplot)
776
777 def test_jitter_unfixed(self, long_df):
778
779 ax1, ax2 = plt.figure().subplots(2)
780 kws = dict(data=long_df, x="y", orient="h", native_scale=True)
781
782 np.random.seed(0)
783 stripplot(**kws, y="s", ax=ax1)
784
785 np.random.seed(0)
786 stripplot(**kws, y=long_df["s"] * 2, ax=ax2)
787
788 p1 = ax1.collections[0].get_offsets()[1]
789 p2 = ax2.collections[0].get_offsets()[1]
790
791 assert p2.std() > p1.std()
792
793 @pytest.mark.parametrize(
794 "orient,jitter",
795 itertools.product(["v", "h"], [True, .1]),
796 )
797 def test_jitter(self, long_df, orient, jitter):
798
799 cat_var, val_var = "a", "y"
800 if orient == "x":
801 x_var, y_var = cat_var, val_var
802 cat_idx, val_idx = 0, 1
803 else:
804 x_var, y_var = val_var, cat_var
805 cat_idx, val_idx = 1, 0
806
807 cat_vals = categorical_order(long_df[cat_var])
808
809 ax = stripplot(
810 data=long_df, x=x_var, y=y_var, jitter=jitter,
811 )
812
813 if jitter is True:
814 jitter_range = .4
815 else:
816 jitter_range = 2 * jitter
817
818 for i, level in enumerate(cat_vals):
819
820 vals = long_df.loc[long_df[cat_var] == level, val_var]
821 points = ax.collections[i].get_offsets().T
822 cat_points = points[cat_idx]
823 val_points = points[val_idx]
824
825 assert_array_equal(val_points, vals)
826 assert np.std(cat_points) > 0
827 assert np.ptp(cat_points) <= jitter_range
828
829
830 class TestSwarmPlot(SharedScatterTests):
831
832 func = staticmethod(partial(swarmplot, warn_thresh=1))
833
834
835 class TestBoxPlot(SharedAxesLevelTests, SharedPatchArtistTests):
836
837 func = staticmethod(boxplot)
838
839 @pytest.fixture
840 def common_kws(self):
841 return {"saturation": 1}
842
843 def get_last_color(self, ax):
844
845 colors = [b.get_facecolor() for b in ax.containers[-1].boxes]
846 unique_colors = np.unique(colors, axis=0)
847 assert len(unique_colors) == 1
848 return to_rgba(unique_colors.squeeze())
849
850 def get_box_verts(self, box):
851
852 path = box.get_path()
853 visible_codes = [mpl.path.Path.MOVETO, mpl.path.Path.LINETO]
854 visible = np.isin(path.codes, visible_codes)
855 return path.vertices[visible].T
856
857 def check_box(self, bxp, data, orient, pos, width=0.8):
858
859 pos_idx, val_idx = self.orient_indices(orient)
860
861 p25, p50, p75 = np.percentile(data, [25, 50, 75])
862
863 box = self.get_box_verts(bxp.box)
864 assert box[val_idx].min() == approx(p25, 1e-3)
865 assert box[val_idx].max() == approx(p75, 1e-3)
866 assert box[pos_idx].min() == approx(pos - width / 2)
867 assert box[pos_idx].max() == approx(pos + width / 2)
868
869 med = bxp.median.get_xydata().T
870 assert np.allclose(med[val_idx], (p50, p50), rtol=1e-3)
871 assert np.allclose(med[pos_idx], (pos - width / 2, pos + width / 2))
872
873 def check_whiskers(self, bxp, data, orient, pos, capsize=0.4, whis=1.5):
874
875 pos_idx, val_idx = self.orient_indices(orient)
876
877 whis_lo = bxp.whiskers[0].get_xydata().T
878 whis_hi = bxp.whiskers[1].get_xydata().T
879 caps_lo = bxp.caps[0].get_xydata().T
880 caps_hi = bxp.caps[1].get_xydata().T
881 fliers = bxp.fliers.get_xydata().T
882
883 p25, p75 = np.percentile(data, [25, 75])
884 iqr = p75 - p25
885
886 adj_lo = data[data >= (p25 - iqr * whis)].min()
887 adj_hi = data[data <= (p75 + iqr * whis)].max()
888
889 assert whis_lo[val_idx].max() == approx(p25, 1e-3)
890 assert whis_lo[val_idx].min() == approx(adj_lo)
891 assert np.allclose(whis_lo[pos_idx], (pos, pos))
892 assert np.allclose(caps_lo[val_idx], (adj_lo, adj_lo))
893 assert np.allclose(caps_lo[pos_idx], (pos - capsize / 2, pos + capsize / 2))
894
895 assert whis_hi[val_idx].min() == approx(p75, 1e-3)
896 assert whis_hi[val_idx].max() == approx(adj_hi)
897 assert np.allclose(whis_hi[pos_idx], (pos, pos))
898 assert np.allclose(caps_hi[val_idx], (adj_hi, adj_hi))
899 assert np.allclose(caps_hi[pos_idx], (pos - capsize / 2, pos + capsize / 2))
900
901 flier_data = data[(data < adj_lo) | (data > adj_hi)]
902 assert sorted(fliers[val_idx]) == sorted(flier_data)
903 assert np.allclose(fliers[pos_idx], pos)
904
905 @pytest.mark.parametrize("orient,col", [("x", "y"), ("y", "z")])
906 def test_single_var(self, long_df, orient, col):
907
908 var = {"x": "y", "y": "x"}[orient]
909 ax = boxplot(long_df, **{var: col})
910 bxp = ax.containers[0][0]
911 self.check_box(bxp, long_df[col], orient, 0)
912 self.check_whiskers(bxp, long_df[col], orient, 0)
913
914 @pytest.mark.parametrize("orient,col", [(None, "x"), ("x", "y"), ("y", "z")])
915 def test_vector_data(self, long_df, orient, col):
916
917 ax = boxplot(long_df[col], orient=orient)
918 orient = "x" if orient is None else orient
919 bxp = ax.containers[0][0]
920 self.check_box(bxp, long_df[col], orient, 0)
921 self.check_whiskers(bxp, long_df[col], orient, 0)
922
923 @pytest.mark.parametrize("orient", ["h", "v"])
924 def test_wide_data(self, wide_df, orient):
925
926 orient = {"h": "y", "v": "x"}[orient]
927 ax = boxplot(wide_df, orient=orient, color="C0")
928 for i, bxp in enumerate(ax.containers):
929 col = wide_df.columns[i]
930 self.check_box(bxp[i], wide_df[col], orient, i)
931 self.check_whiskers(bxp[i], wide_df[col], orient, i)
932
933 @pytest.mark.parametrize("orient", ["x", "y"])
934 def test_grouped(self, long_df, orient):
935
936 value = {"x": "y", "y": "x"}[orient]
937 ax = boxplot(long_df, **{orient: "a", value: "z"})
938 bxp, = ax.containers
939 levels = categorical_order(long_df["a"])
940 for i, level in enumerate(levels):
941 data = long_df.loc[long_df["a"] == level, "z"]
942 self.check_box(bxp[i], data, orient, i)
943 self.check_whiskers(bxp[i], data, orient, i)
944
945 @pytest.mark.parametrize("orient", ["x", "y"])
946 def test_hue_grouped(self, long_df, orient):
947
948 value = {"x": "y", "y": "x"}[orient]
949 ax = boxplot(long_df, hue="c", **{orient: "a", value: "z"})
950 for i, hue_level in enumerate(categorical_order(long_df["c"])):
951 bxp = ax.containers[i]
952 for j, level in enumerate(categorical_order(long_df["a"])):
953 rows = (long_df["a"] == level) & (long_df["c"] == hue_level)
954 data = long_df.loc[rows, "z"]
955 pos = j + [-.2, +.2][i]
956 width, capsize = 0.4, 0.2
957 self.check_box(bxp[j], data, orient, pos, width)
958 self.check_whiskers(bxp[j], data, orient, pos, capsize)
959
960 def test_hue_not_dodged(self, long_df):
961
962 levels = categorical_order(long_df["b"])
963 hue = long_df["b"].isin(levels[:2])
964 ax = boxplot(long_df, x="b", y="z", hue=hue)
965 bxps = ax.containers
966 for i, level in enumerate(levels):
967 idx = int(i < 2)
968 data = long_df.loc[long_df["b"] == level, "z"]
969 self.check_box(bxps[idx][i % 2], data, "x", i)
970 self.check_whiskers(bxps[idx][i % 2], data, "x", i)
971
972 def test_dodge_native_scale(self, long_df):
973
974 centers = categorical_order(long_df["s"])
975 hue_levels = categorical_order(long_df["c"])
976 spacing = min(np.diff(centers))
977 width = 0.8 * spacing / len(hue_levels)
978 offset = width / len(hue_levels)
979 ax = boxplot(long_df, x="s", y="z", hue="c", native_scale=True)
980 for i, hue_level in enumerate(hue_levels):
981 bxp = ax.containers[i]
982 for j, center in enumerate(centers):
983 rows = (long_df["s"] == center) & (long_df["c"] == hue_level)
984 data = long_df.loc[rows, "z"]
985 pos = center + [-offset, +offset][i]
986 self.check_box(bxp[j], data, "x", pos, width)
987 self.check_whiskers(bxp[j], data, "x", pos, width / 2)
988
989 def test_dodge_native_scale_log(self, long_df):
990
991 pos = 10 ** long_df["s"]
992 ax = mpl.figure.Figure().subplots()
993 ax.set_xscale("log")
994 boxplot(long_df, x=pos, y="z", hue="c", native_scale=True, ax=ax)
995 widths = []
996 for bxp in ax.containers:
997 for box in bxp.boxes:
998 coords = np.log10(box.get_path().vertices.T[0])
999 widths.append(np.ptp(coords))
1000 assert np.std(widths) == approx(0)
1001
1002 def test_dodge_without_hue(self, long_df):
1003
1004 ax = boxplot(long_df, x="a", y="y", dodge=True)
1005 bxp, = ax.containers
1006 levels = categorical_order(long_df["a"])
1007 for i, level in enumerate(levels):
1008 data = long_df.loc[long_df["a"] == level, "y"]
1009 self.check_box(bxp[i], data, "x", i)
1010 self.check_whiskers(bxp[i], data, "x", i)
1011
1012 @pytest.mark.parametrize("orient", ["x", "y"])
1013 def test_log_data_scale(self, long_df, orient):
1014
1015 var = {"x": "y", "y": "x"}[orient]
1016 s = long_df["z"]
1017 ax = mpl.figure.Figure().subplots()
1018 getattr(ax, f"set_{var}scale")("log")
1019 boxplot(**{var: s}, whis=np.inf, ax=ax)
1020 bxp = ax.containers[0][0]
1021 self.check_box(bxp, s, orient, 0)
1022 self.check_whiskers(bxp, s, orient, 0, whis=np.inf)
1023
1024 def test_color(self, long_df):
1025
1026 color = "#123456"
1027 ax = boxplot(long_df, x="a", y="y", color=color, saturation=1)
1028 for box in ax.containers[0].boxes:
1029 assert same_color(box.get_facecolor(), color)
1030
1031 def test_wide_data_multicolored(self, wide_df):
1032
1033 ax = boxplot(wide_df)
1034 assert len(ax.containers) == wide_df.shape[1]
1035
1036 def test_wide_data_single_color(self, wide_df):
1037
1038 ax = boxplot(wide_df, color="C1", saturation=1)
1039 assert len(ax.containers) == 1
1040 for box in ax.containers[0].boxes:
1041 assert same_color(box.get_facecolor(), "C1")
1042
1043 def test_hue_colors(self, long_df):
1044
1045 ax = boxplot(long_df, x="a", y="y", hue="b", saturation=1)
1046 for i, bxp in enumerate(ax.containers):
1047 for box in bxp.boxes:
1048 assert same_color(box.get_facecolor(), f"C{i}")
1049
1050 def test_linecolor(self, long_df):
1051
1052 color = "#778815"
1053 ax = boxplot(long_df, x="a", y="y", linecolor=color)
1054 bxp = ax.containers[0]
1055 for line in [*bxp.medians, *bxp.whiskers, *bxp.caps]:
1056 assert same_color(line.get_color(), color)
1057 for box in bxp.boxes:
1058 assert same_color(box.get_edgecolor(), color)
1059 for flier in bxp.fliers:
1060 assert same_color(flier.get_markeredgecolor(), color)
1061
1062 def test_linecolor_gray_warning(self, long_df):
1063
1064 with pytest.warns(FutureWarning, match="Use \"auto\" to set automatic"):
1065 boxplot(long_df, x="y", linecolor="gray")
1066
1067 def test_saturation(self, long_df):
1068
1069 color = "#8912b0"
1070 ax = boxplot(long_df["x"], color=color, saturation=.5)
1071 box = ax.containers[0].boxes[0]
1072 assert np.allclose(box.get_facecolor()[:3], desaturate(color, 0.5))
1073
1074 def test_linewidth(self, long_df):
1075
1076 width = 5
1077 ax = boxplot(long_df, x="a", y="y", linewidth=width)
1078 bxp = ax.containers[0]
1079 for line in [*bxp.boxes, *bxp.medians, *bxp.whiskers, *bxp.caps]:
1080 assert line.get_linewidth() == width
1081
1082 def test_fill(self, long_df):
1083
1084 color = "#459900"
1085 ax = boxplot(x=long_df["z"], fill=False, color=color)
1086 bxp = ax.containers[0]
1087 assert isinstance(bxp.boxes[0], mpl.lines.Line2D)
1088 for line in [*bxp.boxes, *bxp.medians, *bxp.whiskers, *bxp.caps]:
1089 assert same_color(line.get_color(), color)
1090
1091 @pytest.mark.parametrize("notch_param", ["notch", "shownotches"])
1092 def test_notch(self, long_df, notch_param):
1093
1094 ax = boxplot(x=long_df["z"], **{notch_param: True})
1095 verts = ax.containers[0].boxes[0].get_path().vertices
1096 assert len(verts) == 12
1097
1098 def test_whis(self, long_df):
1099
1100 data = long_df["z"]
1101 ax = boxplot(x=data, whis=2)
1102 bxp = ax.containers[0][0]
1103 self.check_whiskers(bxp, data, "y", 0, whis=2)
1104
1105 def test_gap(self, long_df):
1106
1107 ax = boxplot(long_df, x="a", y="z", hue="c", gap=.1)
1108 for i, hue_level in enumerate(categorical_order(long_df["c"])):
1109 bxp = ax.containers[i]
1110 for j, level in enumerate(categorical_order(long_df["a"])):
1111 rows = (long_df["a"] == level) & (long_df["c"] == hue_level)
1112 data = long_df.loc[rows, "z"]
1113 pos = j + [-.2, +.2][i]
1114 width = 0.9 * 0.4
1115 self.check_box(bxp[j], data, "x", pos, width)
1116
1117 def test_prop_dicts(self, long_df):
1118
1119 prop_dicts = dict(
1120 boxprops=dict(linewidth=3),
1121 medianprops=dict(color=".1"),
1122 whiskerprops=dict(linestyle="--"),
1123 capprops=dict(solid_capstyle="butt"),
1124 flierprops=dict(marker="s"),
1125 )
1126 attr_map = dict(box="boxes", flier="fliers")
1127 ax = boxplot(long_df, x="a", y="z", hue="c", **prop_dicts)
1128 for bxp in ax.containers:
1129 for element in ["box", "median", "whisker", "cap", "flier"]:
1130 attr = attr_map.get(element, f"{element}s")
1131 for artist in getattr(bxp, attr):
1132 for k, v in prop_dicts[f"{element}props"].items():
1133 assert plt.getp(artist, k) == v
1134
1135 def test_showfliers(self, long_df):
1136
1137 ax = boxplot(long_df["x"], showfliers=False)
1138 assert not ax.containers[0].fliers
1139
1140 @pytest.mark.parametrize(
1141 "kwargs",
1142 [
1143 dict(data="wide"),
1144 dict(data="wide", orient="h"),
1145 dict(data="flat"),
1146 dict(data="long", x="a", y="y"),
1147 dict(data=None, x="a", y="y"),
1148 dict(data="long", x="a", y="y", hue="a"),
1149 dict(data=None, x="a", y="y", hue="a"),
1150 dict(data="long", x="a", y="y", hue="b"),
1151 dict(data=None, x="s", y="y", hue="a"),
1152 dict(data="long", x="a", y="y", hue="s"),
1153 dict(data="null", x="a", y="y", hue="a"),
1154 dict(data="long", x="s", y="y", hue="a", native_scale=True),
1155 dict(data="long", x="d", y="y", hue="a", native_scale=True),
1156 dict(data="null", x="a", y="y", hue="b", fill=False, gap=.2),
1157 dict(data="null", x="a", y="y", whis=1, showfliers=False),
1158 dict(data="null", x="a", y="y", linecolor="r", linewidth=5),
1159 dict(data="null", x="a", y="y", shownotches=True, showcaps=False),
1160 ]
1161 )
1162 def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
1163
1164 if kwargs["data"] == "long":
1165 kwargs["data"] = long_df
1166 elif kwargs["data"] == "wide":
1167 kwargs["data"] = wide_df
1168 elif kwargs["data"] == "flat":
1169 kwargs["data"] = flat_series
1170 elif kwargs["data"] == "null":
1171 kwargs["data"] = null_df
1172 elif kwargs["data"] is None:
1173 for var in ["x", "y", "hue"]:
1174 if var in kwargs:
1175 kwargs[var] = long_df[kwargs[var]]
1176
1177 ax = boxplot(**kwargs)
1178 g = catplot(**kwargs, kind="box")
1179
1180 assert_plots_equal(ax, g.ax)
1181
1182
1183 class TestBoxenPlot(SharedAxesLevelTests, SharedPatchArtistTests):
1184
1185 func = staticmethod(boxenplot)
1186
1187 @pytest.fixture
1188 def common_kws(self):
1189 return {"saturation": 1}
1190
1191 def get_last_color(self, ax):
1192
1193 fcs = ax.collections[-2].get_facecolors()
1194 return to_rgba(fcs[len(fcs) // 2])
1195
1196 def get_box_width(self, path, orient="x"):
1197
1198 verts = path.vertices.T
1199 idx = ["y", "x"].index(orient)
1200 return np.ptp(verts[idx])
1201
1202 def check_boxen(self, patches, data, orient, pos, width=0.8):
1203
1204 pos_idx, val_idx = self.orient_indices(orient)
1205 verts = np.stack([v.vertices for v in patches.get_paths()], 1).T
1206
1207 assert verts[pos_idx].min().round(4) >= np.round(pos - width / 2, 4)
1208 assert verts[pos_idx].max().round(4) <= np.round(pos + width / 2, 4)
1209 assert np.in1d(
1210 np.percentile(data, [25, 75]).round(4), verts[val_idx].round(4).flat
1211 ).all()
1212 assert_array_equal(verts[val_idx, 1:, 0], verts[val_idx, :-1, 2])
1213
1214 @pytest.mark.parametrize("orient,col", [("x", "y"), ("y", "z")])
1215 def test_single_var(self, long_df, orient, col):
1216
1217 var = {"x": "y", "y": "x"}[orient]
1218 ax = boxenplot(long_df, **{var: col})
1219 patches = ax.collections[0]
1220 self.check_boxen(patches, long_df[col], orient, 0)
1221
1222 @pytest.mark.parametrize("orient,col", [(None, "x"), ("x", "y"), ("y", "z")])
1223 def test_vector_data(self, long_df, orient, col):
1224
1225 orient = "x" if orient is None else orient
1226 ax = boxenplot(long_df[col], orient=orient)
1227 patches = ax.collections[0]
1228 self.check_boxen(patches, long_df[col], orient, 0)
1229
1230 @pytest.mark.parametrize("orient", ["h", "v"])
1231 def test_wide_data(self, wide_df, orient):
1232
1233 orient = {"h": "y", "v": "x"}[orient]
1234 ax = boxenplot(wide_df, orient=orient)
1235 collections = ax.findobj(mpl.collections.PatchCollection)
1236 for i, patches in enumerate(collections):
1237 col = wide_df.columns[i]
1238 self.check_boxen(patches, wide_df[col], orient, i)
1239
1240 @pytest.mark.parametrize("orient", ["x", "y"])
1241 def test_grouped(self, long_df, orient):
1242
1243 value = {"x": "y", "y": "x"}[orient]
1244 ax = boxenplot(long_df, **{orient: "a", value: "z"})
1245 levels = categorical_order(long_df["a"])
1246 collections = ax.findobj(mpl.collections.PatchCollection)
1247 for i, level in enumerate(levels):
1248 data = long_df.loc[long_df["a"] == level, "z"]
1249 self.check_boxen(collections[i], data, orient, i)
1250
1251 @pytest.mark.parametrize("orient", ["x", "y"])
1252 def test_hue_grouped(self, long_df, orient):
1253
1254 value = {"x": "y", "y": "x"}[orient]
1255 ax = boxenplot(long_df, hue="c", **{orient: "a", value: "z"})
1256 collections = iter(ax.findobj(mpl.collections.PatchCollection))
1257 for i, level in enumerate(categorical_order(long_df["a"])):
1258 for j, hue_level in enumerate(categorical_order(long_df["c"])):
1259 rows = (long_df["a"] == level) & (long_df["c"] == hue_level)
1260 data = long_df.loc[rows, "z"]
1261 pos = i + [-.2, +.2][j]
1262 width = 0.4
1263 self.check_boxen(next(collections), data, orient, pos, width)
1264
1265 def test_dodge_native_scale(self, long_df):
1266
1267 centers = categorical_order(long_df["s"])
1268 hue_levels = categorical_order(long_df["c"])
1269 spacing = min(np.diff(centers))
1270 width = 0.8 * spacing / len(hue_levels)
1271 offset = width / len(hue_levels)
1272 ax = boxenplot(long_df, x="s", y="z", hue="c", native_scale=True)
1273 collections = iter(ax.findobj(mpl.collections.PatchCollection))
1274 for center in centers:
1275 for i, hue_level in enumerate(hue_levels):
1276 rows = (long_df["s"] == center) & (long_df["c"] == hue_level)
1277 data = long_df.loc[rows, "z"]
1278 pos = center + [-offset, +offset][i]
1279 self.check_boxen(next(collections), data, "x", pos, width)
1280
1281 def test_color(self, long_df):
1282
1283 color = "#123456"
1284 ax = boxenplot(long_df, x="a", y="y", color=color, saturation=1)
1285 collections = ax.findobj(mpl.collections.PatchCollection)
1286 for patches in collections:
1287 fcs = patches.get_facecolors()
1288 assert same_color(fcs[len(fcs) // 2], color)
1289
1290 def test_hue_colors(self, long_df):
1291
1292 ax = boxenplot(long_df, x="a", y="y", hue="b", saturation=1)
1293 n_levels = long_df["b"].nunique()
1294 collections = ax.findobj(mpl.collections.PatchCollection)
1295 for i, patches in enumerate(collections):
1296 fcs = patches.get_facecolors()
1297 assert same_color(fcs[len(fcs) // 2], f"C{i % n_levels}")
1298
1299 def test_linecolor(self, long_df):
1300
1301 color = "#669913"
1302 ax = boxenplot(long_df, x="a", y="y", linecolor=color)
1303 for patches in ax.findobj(mpl.collections.PatchCollection):
1304 assert same_color(patches.get_edgecolor(), color)
1305
1306 def test_linewidth(self, long_df):
1307
1308 width = 5
1309 ax = boxenplot(long_df, x="a", y="y", linewidth=width)
1310 for patches in ax.findobj(mpl.collections.PatchCollection):
1311 assert patches.get_linewidth() == width
1312
1313 def test_saturation(self, long_df):
1314
1315 color = "#8912b0"
1316 ax = boxenplot(long_df["x"], color=color, saturation=.5)
1317 fcs = ax.collections[0].get_facecolors()
1318 assert np.allclose(fcs[len(fcs) // 2, :3], desaturate(color, 0.5))
1319
1320 def test_gap(self, long_df):
1321
1322 ax1, ax2 = mpl.figure.Figure().subplots(2)
1323 boxenplot(long_df, x="a", y="y", hue="s", ax=ax1)
1324 boxenplot(long_df, x="a", y="y", hue="s", gap=.2, ax=ax2)
1325 c1 = ax1.findobj(mpl.collections.PatchCollection)
1326 c2 = ax2.findobj(mpl.collections.PatchCollection)
1327 for p1, p2 in zip(c1, c2):
1328 w1 = np.ptp(p1.get_paths()[0].vertices[:, 0])
1329 w2 = np.ptp(p2.get_paths()[0].vertices[:, 0])
1330 assert (w2 / w1) == pytest.approx(0.8)
1331
1332 def test_fill(self, long_df):
1333
1334 ax = boxenplot(long_df, x="a", y="y", hue="s", fill=False)
1335 for c in ax.findobj(mpl.collections.PatchCollection):
1336 assert not c.get_facecolors().size
1337
1338 def test_k_depth_int(self, rng):
1339
1340 x = rng.normal(0, 1, 10_000)
1341 ax = boxenplot(x, k_depth=(k := 8))
1342 assert len(ax.collections[0].get_paths()) == (k * 2 - 1)
1343
1344 def test_k_depth_full(self, rng):
1345
1346 x = rng.normal(0, 1, 10_000)
1347 ax = boxenplot(x=x, k_depth="full")
1348 paths = ax.collections[0].get_paths()
1349 assert len(paths) == 2 * int(np.log2(x.size)) + 1
1350 verts = np.concatenate([p.vertices for p in paths]).T
1351 assert verts[0].min() == x.min()
1352 assert verts[0].max() == x.max()
1353 assert not ax.collections[1].get_offsets().size
1354
1355 def test_trust_alpha(self, rng):
1356
1357 x = rng.normal(0, 1, 10_000)
1358 ax = boxenplot(x, k_depth="trustworthy", trust_alpha=.1)
1359 boxenplot(x, k_depth="trustworthy", trust_alpha=.001, ax=ax)
1360 cs = ax.findobj(mpl.collections.PatchCollection)
1361 assert len(cs[0].get_paths()) > len(cs[1].get_paths())
1362
1363 def test_outlier_prop(self, rng):
1364
1365 x = rng.normal(0, 1, 10_000)
1366 ax = boxenplot(x, k_depth="proportion", outlier_prop=.001)
1367 boxenplot(x, k_depth="proportion", outlier_prop=.1, ax=ax)
1368 cs = ax.findobj(mpl.collections.PatchCollection)
1369 assert len(cs[0].get_paths()) > len(cs[1].get_paths())
1370
1371 def test_exponential_width_method(self, rng):
1372
1373 x = rng.normal(0, 1, 10_000)
1374 ax = boxenplot(x=x, width_method="exponential")
1375 c = ax.findobj(mpl.collections.PatchCollection)[0]
1376 ws = [self.get_box_width(p) for p in c.get_paths()]
1377 assert (ws[1] / ws[0]) == pytest.approx(ws[2] / ws[1])
1378
1379 def test_linear_width_method(self, rng):
1380
1381 x = rng.normal(0, 1, 10_000)
1382 ax = boxenplot(x=x, width_method="linear")
1383 c = ax.findobj(mpl.collections.PatchCollection)[0]
1384 ws = [self.get_box_width(p) for p in c.get_paths()]
1385 assert (ws[1] - ws[0]) == pytest.approx(ws[2] - ws[1])
1386
1387 def test_area_width_method(self, rng):
1388
1389 x = rng.uniform(0, 1, 10_000)
1390 ax = boxenplot(x=x, width_method="area", k_depth=2)
1391 ps = ax.findobj(mpl.collections.PatchCollection)[0].get_paths()
1392 ws = [self.get_box_width(p) for p in ps]
1393 assert np.greater(ws, 0.7).all()
1394
1395 def test_box_kws(self, long_df):
1396
1397 ax = boxenplot(long_df, x="a", y="y", box_kws={"linewidth": (lw := 7.1)})
1398 for c in ax.findobj(mpl.collections.PatchCollection):
1399 assert c.get_linewidths() == lw
1400
1401 def test_line_kws(self, long_df):
1402
1403 ax = boxenplot(long_df, x="a", y="y", line_kws={"linewidth": (lw := 6.2)})
1404 for line in ax.lines:
1405 assert line.get_linewidth() == lw
1406
1407 def test_flier_kws(self, long_df):
1408
1409 ax = boxenplot(long_df, x="a", y="y", flier_kws={"marker": (marker := "X")})
1410 expected = mpl.markers.MarkerStyle(marker).get_path().vertices
1411 for c in ax.findobj(mpl.collections.PathCollection):
1412 assert_array_equal(c.get_paths()[0].vertices, expected)
1413
1414 def test_k_depth_checks(self, long_df):
1415
1416 with pytest.raises(ValueError, match="The value for `k_depth`"):
1417 boxenplot(x=long_df["y"], k_depth="auto")
1418
1419 with pytest.raises(TypeError, match="The `k_depth` parameter"):
1420 boxenplot(x=long_df["y"], k_depth=(1, 2))
1421
1422 def test_width_method_check(self, long_df):
1423
1424 with pytest.raises(ValueError, match="The value for `width_method`"):
1425 boxenplot(x=long_df["y"], width_method="uniform")
1426
1427 def test_scale_deprecation(self, long_df):
1428
1429 with pytest.warns(FutureWarning, match="The `scale` parameter has been"):
1430 boxenplot(x=long_df["y"], scale="linear")
1431
1432 with pytest.warns(FutureWarning, match=".+result for 'area' will appear"):
1433 boxenplot(x=long_df["y"], scale="area")
1434
1435 @pytest.mark.parametrize(
1436 "kwargs",
1437 [
1438 dict(data="wide"),
1439 dict(data="wide", orient="h"),
1440 dict(data="flat"),
1441 dict(data="long", x="a", y="y"),
1442 dict(data=None, x="a", y="y"),
1443 dict(data="long", x="a", y="y", hue="a"),
1444 dict(data=None, x="a", y="y", hue="a"),
1445 dict(data="long", x="a", y="y", hue="b"),
1446 dict(data=None, x="s", y="y", hue="a"),
1447 dict(data="long", x="a", y="y", hue="s", showfliers=False),
1448 dict(data="null", x="a", y="y", hue="a", saturation=.5),
1449 dict(data="long", x="s", y="y", hue="a", native_scale=True),
1450 dict(data="long", x="d", y="y", hue="a", native_scale=True),
1451 dict(data="null", x="a", y="y", hue="b", fill=False, gap=.2),
1452 dict(data="null", x="a", y="y", linecolor="r", linewidth=5),
1453 dict(data="long", x="a", y="y", k_depth="trustworthy", trust_alpha=.1),
1454 dict(data="long", x="a", y="y", k_depth="proportion", outlier_prop=.1),
1455 dict(data="long", x="a", y="z", width_method="area"),
1456 dict(data="long", x="a", y="z", box_kws={"alpha": .2}, alpha=.4)
1457 ]
1458 )
1459 def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
1460
1461 if kwargs["data"] == "long":
1462 kwargs["data"] = long_df
1463 elif kwargs["data"] == "wide":
1464 kwargs["data"] = wide_df
1465 elif kwargs["data"] == "flat":
1466 kwargs["data"] = flat_series
1467 elif kwargs["data"] == "null":
1468 kwargs["data"] = null_df
1469 elif kwargs["data"] is None:
1470 for var in ["x", "y", "hue"]:
1471 if var in kwargs:
1472 kwargs[var] = long_df[kwargs[var]]
1473
1474 ax = boxenplot(**kwargs)
1475 g = catplot(**kwargs, kind="boxen")
1476
1477 assert_plots_equal(ax, g.ax)
1478
1479
1480 class TestViolinPlot(SharedAxesLevelTests, SharedPatchArtistTests):
1481
1482 func = staticmethod(violinplot)
1483
1484 @pytest.fixture
1485 def common_kws(self):
1486 return {"saturation": 1}
1487
1488 def get_last_color(self, ax):
1489
1490 color = ax.collections[-1].get_facecolor()
1491 return to_rgba(color)
1492
1493 def violin_width(self, poly, orient="x"):
1494
1495 idx, _ = self.orient_indices(orient)
1496 return np.ptp(poly.get_paths()[0].vertices[:, idx])
1497
1498 def check_violin(self, poly, data, orient, pos, width=0.8):
1499
1500 pos_idx, val_idx = self.orient_indices(orient)
1501 verts = poly.get_paths()[0].vertices.T
1502
1503 assert verts[pos_idx].min() >= (pos - width / 2)
1504 assert verts[pos_idx].max() <= (pos + width / 2)
1505 # Assumes violin was computed with cut=0
1506 assert verts[val_idx].min() == approx(data.min())
1507 assert verts[val_idx].max() == approx(data.max())
1508
1509 @pytest.mark.parametrize("orient,col", [("x", "y"), ("y", "z")])
1510 def test_single_var(self, long_df, orient, col):
1511
1512 var = {"x": "y", "y": "x"}[orient]
1513 ax = violinplot(long_df, **{var: col}, cut=0)
1514 poly = ax.collections[0]
1515 self.check_violin(poly, long_df[col], orient, 0)
1516
1517 @pytest.mark.parametrize("orient,col", [(None, "x"), ("x", "y"), ("y", "z")])
1518 def test_vector_data(self, long_df, orient, col):
1519
1520 orient = "x" if orient is None else orient
1521 ax = violinplot(long_df[col], cut=0, orient=orient)
1522 poly = ax.collections[0]
1523 self.check_violin(poly, long_df[col], orient, 0)
1524
1525 @pytest.mark.parametrize("orient", ["h", "v"])
1526 def test_wide_data(self, wide_df, orient):
1527
1528 orient = {"h": "y", "v": "x"}[orient]
1529 ax = violinplot(wide_df, cut=0, orient=orient)
1530 for i, poly in enumerate(ax.collections):
1531 col = wide_df.columns[i]
1532 self.check_violin(poly, wide_df[col], orient, i)
1533
1534 @pytest.mark.parametrize("orient", ["x", "y"])
1535 def test_grouped(self, long_df, orient):
1536
1537 value = {"x": "y", "y": "x"}[orient]
1538 ax = violinplot(long_df, **{orient: "a", value: "z"}, cut=0)
1539 levels = categorical_order(long_df["a"])
1540 for i, level in enumerate(levels):
1541 data = long_df.loc[long_df["a"] == level, "z"]
1542 self.check_violin(ax.collections[i], data, orient, i)
1543
1544 @pytest.mark.parametrize("orient", ["x", "y"])
1545 def test_hue_grouped(self, long_df, orient):
1546
1547 value = {"x": "y", "y": "x"}[orient]
1548 ax = violinplot(long_df, hue="c", **{orient: "a", value: "z"}, cut=0)
1549 polys = iter(ax.collections)
1550 for i, level in enumerate(categorical_order(long_df["a"])):
1551 for j, hue_level in enumerate(categorical_order(long_df["c"])):
1552 rows = (long_df["a"] == level) & (long_df["c"] == hue_level)
1553 data = long_df.loc[rows, "z"]
1554 pos = i + [-.2, +.2][j]
1555 width = 0.4
1556 self.check_violin(next(polys), data, orient, pos, width)
1557
1558 def test_hue_not_dodged(self, long_df):
1559
1560 levels = categorical_order(long_df["b"])
1561 hue = long_df["b"].isin(levels[:2])
1562 ax = violinplot(long_df, x="b", y="z", hue=hue, cut=0)
1563 for i, level in enumerate(levels):
1564 poly = ax.collections[i]
1565 data = long_df.loc[long_df["b"] == level, "z"]
1566 self.check_violin(poly, data, "x", i)
1567
1568 def test_dodge_native_scale(self, long_df):
1569
1570 centers = categorical_order(long_df["s"])
1571 hue_levels = categorical_order(long_df["c"])
1572 spacing = min(np.diff(centers))
1573 width = 0.8 * spacing / len(hue_levels)
1574 offset = width / len(hue_levels)
1575 ax = violinplot(long_df, x="s", y="z", hue="c", native_scale=True, cut=0)
1576 violins = iter(ax.collections)
1577 for center in centers:
1578 for i, hue_level in enumerate(hue_levels):
1579 rows = (long_df["s"] == center) & (long_df["c"] == hue_level)
1580 data = long_df.loc[rows, "z"]
1581 pos = center + [-offset, +offset][i]
1582 poly = next(violins)
1583 self.check_violin(poly, data, "x", pos, width)
1584
1585 def test_dodge_native_scale_log(self, long_df):
1586
1587 pos = 10 ** long_df["s"]
1588 ax = mpl.figure.Figure().subplots()
1589 ax.set_xscale("log")
1590 variables = dict(x=pos, y="z", hue="c")
1591 violinplot(long_df, **variables, native_scale=True, density_norm="width", ax=ax)
1592 widths = []
1593 n_violins = long_df["s"].nunique() * long_df["c"].nunique()
1594 for poly in ax.collections[:n_violins]:
1595 verts = poly.get_paths()[0].vertices[:, 0]
1596 coords = np.log10(verts)
1597 widths.append(np.ptp(coords))
1598 assert np.std(widths) == approx(0)
1599
1600 def test_color(self, long_df):
1601
1602 color = "#123456"
1603 ax = violinplot(long_df, x="a", y="y", color=color, saturation=1)
1604 for poly in ax.collections:
1605 assert same_color(poly.get_facecolor(), color)
1606
1607 def test_hue_colors(self, long_df):
1608
1609 ax = violinplot(long_df, x="a", y="y", hue="b", saturation=1)
1610 n_levels = long_df["b"].nunique()
1611 for i, poly in enumerate(ax.collections):
1612 assert same_color(poly.get_facecolor(), f"C{i % n_levels}")
1613
1614 @pytest.mark.parametrize("inner", ["box", "quart", "stick", "point"])
1615 def test_linecolor(self, long_df, inner):
1616
1617 color = "#669913"
1618 ax = violinplot(long_df, x="a", y="y", linecolor=color, inner=inner)
1619 for poly in ax.findobj(mpl.collections.PolyCollection):
1620 assert same_color(poly.get_edgecolor(), color)
1621 for lines in ax.findobj(mpl.collections.LineCollection):
1622 assert same_color(lines.get_color(), color)
1623 for line in ax.lines:
1624 assert same_color(line.get_color(), color)
1625
1626 def test_linewidth(self, long_df):
1627
1628 width = 5
1629 ax = violinplot(long_df, x="a", y="y", linewidth=width)
1630 poly = ax.collections[0]
1631 assert poly.get_linewidth() == width
1632
1633 def test_saturation(self, long_df):
1634
1635 color = "#8912b0"
1636 ax = violinplot(long_df["x"], color=color, saturation=.5)
1637 poly = ax.collections[0]
1638 assert np.allclose(poly.get_facecolors()[0, :3], desaturate(color, 0.5))
1639
1640 @pytest.mark.parametrize("inner", ["box", "quart", "stick", "point"])
1641 def test_fill(self, long_df, inner):
1642
1643 color = "#459900"
1644 ax = violinplot(x=long_df["z"], fill=False, color=color, inner=inner)
1645 for poly in ax.findobj(mpl.collections.PolyCollection):
1646 assert poly.get_facecolor().size == 0
1647 assert same_color(poly.get_edgecolor(), color)
1648 for lines in ax.findobj(mpl.collections.LineCollection):
1649 assert same_color(lines.get_color(), color)
1650 for line in ax.lines:
1651 assert same_color(line.get_color(), color)
1652
1653 @pytest.mark.parametrize("orient", ["x", "y"])
1654 def test_inner_box(self, long_df, orient):
1655
1656 pos_idx, val_idx = self.orient_indices(orient)
1657 ax = violinplot(long_df["y"], orient=orient)
1658 stats = mpl.cbook.boxplot_stats(long_df["y"])[0]
1659
1660 whiskers = ax.lines[0].get_xydata()
1661 assert whiskers[0, val_idx] == stats["whislo"]
1662 assert whiskers[1, val_idx] == stats["whishi"]
1663 assert whiskers[:, pos_idx].tolist() == [0, 0]
1664
1665 box = ax.lines[1].get_xydata()
1666 assert box[0, val_idx] == stats["q1"]
1667 assert box[1, val_idx] == stats["q3"]
1668 assert box[:, pos_idx].tolist() == [0, 0]
1669
1670 median = ax.lines[2].get_xydata()
1671 assert median[0, val_idx] == stats["med"]
1672 assert median[0, pos_idx] == 0
1673
1674 @pytest.mark.parametrize("orient", ["x", "y"])
1675 def test_inner_quartiles(self, long_df, orient):
1676
1677 pos_idx, val_idx = self.orient_indices(orient)
1678 ax = violinplot(long_df["y"], orient=orient, inner="quart")
1679 quartiles = np.percentile(long_df["y"], [25, 50, 75])
1680
1681 for q, line in zip(quartiles, ax.lines):
1682 pts = line.get_xydata()
1683 for pt in pts:
1684 assert pt[val_idx] == q
1685 assert pts[0, pos_idx] == -pts[1, pos_idx]
1686
1687 @pytest.mark.parametrize("orient", ["x", "y"])
1688 def test_inner_stick(self, long_df, orient):
1689
1690 pos_idx, val_idx = self.orient_indices(orient)
1691 ax = violinplot(long_df["y"], orient=orient, inner="stick")
1692 for i, pts in enumerate(ax.collections[1].get_segments()):
1693 for pt in pts:
1694 assert pt[val_idx] == long_df["y"].iloc[i]
1695 assert pts[0, pos_idx] == -pts[1, pos_idx]
1696
1697 @pytest.mark.parametrize("orient", ["x", "y"])
1698 def test_inner_points(self, long_df, orient):
1699
1700 pos_idx, val_idx = self.orient_indices(orient)
1701 ax = violinplot(long_df["y"], orient=orient, inner="points")
1702 points = ax.collections[1]
1703 for i, pt in enumerate(points.get_offsets()):
1704 assert pt[val_idx] == long_df["y"].iloc[i]
1705 assert pt[pos_idx] == 0
1706
1707 def test_split_single(self, long_df):
1708
1709 ax = violinplot(long_df, x="a", y="z", split=True, cut=0)
1710 levels = categorical_order(long_df["a"])
1711 for i, level in enumerate(levels):
1712 data = long_df.loc[long_df["a"] == level, "z"]
1713 self.check_violin(ax.collections[i], data, "x", i)
1714 verts = ax.collections[i].get_paths()[0].vertices
1715 assert np.isclose(verts[:, 0], i + .4).sum() >= 100
1716
1717 def test_split_multi(self, long_df):
1718
1719 ax = violinplot(long_df, x="a", y="z", hue="c", split=True, cut=0)
1720 polys = iter(ax.collections)
1721 for i, level in enumerate(categorical_order(long_df["a"])):
1722 for j, hue_level in enumerate(categorical_order(long_df["c"])):
1723 rows = (long_df["a"] == level) & (long_df["c"] == hue_level)
1724 data = long_df.loc[rows, "z"]
1725 pos = i + [-.2, +.2][j]
1726 poly = next(polys)
1727 self.check_violin(poly, data, "x", pos, width=0.4)
1728 verts = poly.get_paths()[0].vertices
1729 assert np.isclose(verts[:, 0], i).sum() >= 100
1730
1731 def test_density_norm_area(self, long_df):
1732
1733 y = long_df["y"].to_numpy()
1734 ax = violinplot([y, y * 5], color="C0")
1735 widths = []
1736 for poly in ax.collections:
1737 widths.append(self.violin_width(poly))
1738 assert widths[0] / widths[1] == approx(5)
1739
1740 def test_density_norm_count(self, long_df):
1741
1742 y = long_df["y"].to_numpy()
1743 ax = violinplot([np.repeat(y, 3), y], density_norm="count", color="C0")
1744 widths = []
1745 for poly in ax.collections:
1746 widths.append(self.violin_width(poly))
1747 assert widths[0] / widths[1] == approx(3)
1748
1749 def test_density_norm_width(self, long_df):
1750
1751 ax = violinplot(long_df, x="a", y="y", density_norm="width")
1752 for poly in ax.collections:
1753 assert self.violin_width(poly) == approx(0.8)
1754
1755 def test_common_norm(self, long_df):
1756
1757 ax = violinplot(long_df, x="a", y="y", hue="c", common_norm=True)
1758 widths = []
1759 for poly in ax.collections:
1760 widths.append(self.violin_width(poly))
1761 assert sum(w > 0.3999 for w in widths) == 1
1762
1763 def test_scale_deprecation(self, long_df):
1764
1765 with pytest.warns(FutureWarning, match=r".+Pass `density_norm='count'`"):
1766 violinplot(long_df, x="a", y="y", hue="b", scale="count")
1767
1768 def test_scale_hue_deprecation(self, long_df):
1769
1770 with pytest.warns(FutureWarning, match=r".+Pass `common_norm=True`"):
1771 violinplot(long_df, x="a", y="y", hue="b", scale_hue=False)
1772
1773 def test_bw_adjust(self, long_df):
1774
1775 ax = violinplot(long_df["y"], bw_adjust=.2)
1776 violinplot(long_df["y"], bw_adjust=2)
1777 kde1 = ax.collections[0].get_paths()[0].vertices[:100, 0]
1778 kde2 = ax.collections[1].get_paths()[0].vertices[:100, 0]
1779 assert np.std(np.diff(kde1)) > np.std(np.diff(kde2))
1780
1781 def test_bw_deprecation(self, long_df):
1782
1783 with pytest.warns(FutureWarning, match=r".*Setting `bw_method='silverman'`"):
1784 violinplot(long_df["y"], bw="silverman")
1785
1786 def test_gap(self, long_df):
1787
1788 ax = violinplot(long_df, y="y", hue="c", gap=.2)
1789 a = ax.collections[0].get_paths()[0].vertices[:, 0].max()
1790 b = ax.collections[1].get_paths()[0].vertices[:, 0].min()
1791 assert (b - a) == approx(0.2 * 0.8 / 2)
1792
1793 def test_inner_kws(self, long_df):
1794
1795 kws = {"linewidth": 3}
1796 ax = violinplot(long_df, x="a", y="y", inner="stick", inner_kws=kws)
1797 for line in ax.lines:
1798 assert line.get_linewidth() == kws["linewidth"]
1799
1800 def test_box_inner_kws(self, long_df):
1801
1802 kws = {"box_width": 10, "whis_width": 2, "marker": "x"}
1803 ax = violinplot(long_df, x="a", y="y", inner_kws=kws)
1804 for line in ax.lines[::3]:
1805 assert line.get_linewidth() == kws["whis_width"]
1806 for line in ax.lines[1::3]:
1807 assert line.get_linewidth() == kws["box_width"]
1808 for line in ax.lines[2::3]:
1809 assert line.get_marker() == kws["marker"]
1810
1811 @pytest.mark.parametrize(
1812 "kwargs",
1813 [
1814 dict(data="wide"),
1815 dict(data="wide", orient="h"),
1816 dict(data="flat"),
1817 dict(data="long", x="a", y="y"),
1818 dict(data=None, x="a", y="y", split=True),
1819 dict(data="long", x="a", y="y", hue="a"),
1820 dict(data=None, x="a", y="y", hue="a"),
1821 dict(data="long", x="a", y="y", hue="b"),
1822 dict(data=None, x="s", y="y", hue="a"),
1823 dict(data="long", x="a", y="y", hue="s", split=True),
1824 dict(data="null", x="a", y="y", hue="a"),
1825 dict(data="long", x="s", y="y", hue="a", native_scale=True),
1826 dict(data="long", x="d", y="y", hue="a", native_scale=True),
1827 dict(data="null", x="a", y="y", hue="b", fill=False, gap=.2),
1828 dict(data="null", x="a", y="y", linecolor="r", linewidth=5),
1829 dict(data="long", x="a", y="y", inner="stick"),
1830 dict(data="long", x="a", y="y", inner="points"),
1831 dict(data="long", x="a", y="y", hue="b", inner="quartiles", split=True),
1832 dict(data="long", x="a", y="y", density_norm="count", common_norm=True),
1833 dict(data="long", x="a", y="y", bw_adjust=2),
1834 ]
1835 )
1836 def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
1837
1838 if kwargs["data"] == "long":
1839 kwargs["data"] = long_df
1840 elif kwargs["data"] == "wide":
1841 kwargs["data"] = wide_df
1842 elif kwargs["data"] == "flat":
1843 kwargs["data"] = flat_series
1844 elif kwargs["data"] == "null":
1845 kwargs["data"] = null_df
1846 elif kwargs["data"] is None:
1847 for var in ["x", "y", "hue"]:
1848 if var in kwargs:
1849 kwargs[var] = long_df[kwargs[var]]
1850
1851 ax = violinplot(**kwargs)
1852 g = catplot(**kwargs, kind="violin")
1853
1854 assert_plots_equal(ax, g.ax)
1855
1856
1857 class TestBarPlot(SharedAggTests):
1858
1859 func = staticmethod(barplot)
1860
1861 @pytest.fixture
1862 def common_kws(self):
1863 return {"saturation": 1}
1864
1865 def get_last_color(self, ax):
1866
1867 colors = [p.get_facecolor() for p in ax.containers[-1]]
1868 unique_colors = np.unique(colors, axis=0)
1869 assert len(unique_colors) == 1
1870 return to_rgba(unique_colors.squeeze())
1871
1872 @pytest.mark.parametrize("orient", ["x", "y"])
1873 def test_single_var(self, orient):
1874
1875 vals = pd.Series([1, 3, 10])
1876 ax = barplot(**{orient: vals})
1877 bar, = ax.patches
1878 prop = {"x": "width", "y": "height"}[orient]
1879 assert getattr(bar, f"get_{prop}")() == approx(vals.mean())
1880
1881 @pytest.mark.parametrize("orient", ["x", "y", "h", "v"])
1882 def test_wide_df(self, wide_df, orient):
1883
1884 ax = barplot(wide_df, orient=orient)
1885 orient = {"h": "y", "v": "x"}.get(orient, orient)
1886 prop = {"x": "height", "y": "width"}[orient]
1887 for i, bar in enumerate(ax.patches):
1888 assert getattr(bar, f"get_{prop}")() == approx(wide_df.iloc[:, i].mean())
1889
1890 @pytest.mark.parametrize("orient", ["x", "y", "h", "v"])
1891 def test_vector_orient(self, orient):
1892
1893 keys, vals = ["a", "b", "c"], [1, 2, 3]
1894 data = dict(zip(keys, vals))
1895 orient = {"h": "y", "v": "x"}.get(orient, orient)
1896 prop = {"x": "height", "y": "width"}[orient]
1897 ax = barplot(data, orient=orient)
1898 for i, bar in enumerate(ax.patches):
1899 assert getattr(bar, f"get_{orient}")() == approx(i - 0.4)
1900 assert getattr(bar, f"get_{prop}")() == approx(vals[i])
1901
1902 def test_xy_vertical(self):
1903
1904 x, y = ["a", "b", "c"], [1, 3, 2.5]
1905
1906 ax = barplot(x=x, y=y)
1907 for i, bar in enumerate(ax.patches):
1908 assert bar.get_x() + bar.get_width() / 2 == approx(i)
1909 assert bar.get_y() == approx(0)
1910 assert bar.get_height() == approx(y[i])
1911 assert bar.get_width() == approx(0.8)
1912
1913 def test_xy_horizontal(self):
1914
1915 x, y = [1, 3, 2.5], ["a", "b", "c"]
1916
1917 ax = barplot(x=x, y=y)
1918 for i, bar in enumerate(ax.patches):
1919 assert bar.get_x() == approx(0)
1920 assert bar.get_y() + bar.get_height() / 2 == approx(i)
1921 assert bar.get_height() == approx(0.8)
1922 assert bar.get_width() == approx(x[i])
1923
1924 def test_xy_with_na_grouper(self):
1925
1926 x, y = ["a", None, "b"], [1, 2, 3]
1927 ax = barplot(x=x, y=y)
1928 _draw_figure(ax.figure) # For matplotlib<3.5
1929 assert ax.get_xticks() == [0, 1]
1930 assert [t.get_text() for t in ax.get_xticklabels()] == ["a", "b"]
1931 assert ax.patches[0].get_height() == 1
1932 assert ax.patches[1].get_height() == 3
1933
1934 def test_xy_with_na_value(self):
1935
1936 x, y = ["a", "b", "c"], [1, None, 3]
1937 ax = barplot(x=x, y=y)
1938 _draw_figure(ax.figure) # For matplotlib<3.5
1939 assert ax.get_xticks() == [0, 1, 2]
1940 assert [t.get_text() for t in ax.get_xticklabels()] == ["a", "b", "c"]
1941 assert ax.patches[0].get_height() == 1
1942 assert ax.patches[1].get_height() == 3
1943
1944 def test_hue_redundant(self):
1945
1946 x, y = ["a", "b", "c"], [1, 2, 3]
1947
1948 ax = barplot(x=x, y=y, hue=x, saturation=1)
1949 for i, bar in enumerate(ax.patches):
1950 assert bar.get_x() + bar.get_width() / 2 == approx(i)
1951 assert bar.get_y() == 0
1952 assert bar.get_height() == y[i]
1953 assert bar.get_width() == approx(0.8)
1954 assert same_color(bar.get_facecolor(), f"C{i}")
1955
1956 def test_hue_matched(self):
1957
1958 x, y = ["a", "b", "c"], [1, 2, 3]
1959 hue = ["x", "x", "y"]
1960
1961 ax = barplot(x=x, y=y, hue=hue, saturation=1, legend=False)
1962 for i, bar in enumerate(ax.patches):
1963 assert bar.get_x() + bar.get_width() / 2 == approx(i)
1964 assert bar.get_y() == 0
1965 assert bar.get_height() == y[i]
1966 assert bar.get_width() == approx(0.8)
1967 assert same_color(bar.get_facecolor(), f"C{i // 2}")
1968
1969 def test_hue_matched_by_name(self):
1970
1971 data = {"x": ["a", "b", "c"], "y": [1, 2, 3]}
1972 ax = barplot(data, x="x", y="y", hue="x", saturation=1)
1973 for i, bar in enumerate(ax.patches):
1974 assert bar.get_x() + bar.get_width() / 2 == approx(i)
1975 assert bar.get_y() == 0
1976 assert bar.get_height() == data["y"][i]
1977 assert bar.get_width() == approx(0.8)
1978 assert same_color(bar.get_facecolor(), f"C{i}")
1979
1980 def test_hue_dodged(self):
1981
1982 x = ["a", "b", "a", "b"]
1983 y = [1, 2, 3, 4]
1984 hue = ["x", "x", "y", "y"]
1985
1986 ax = barplot(x=x, y=y, hue=hue, saturation=1, legend=False)
1987 for i, bar in enumerate(ax.patches):
1988 sign = 1 if i // 2 else -1
1989 assert (
1990 bar.get_x() + bar.get_width() / 2
1991 == approx(i % 2 + sign * 0.8 / 4)
1992 )
1993 assert bar.get_y() == 0
1994 assert bar.get_height() == y[i]
1995 assert bar.get_width() == approx(0.8 / 2)
1996 assert same_color(bar.get_facecolor(), f"C{i // 2}")
1997
1998 def test_gap(self):
1999
2000 x = ["a", "b", "a", "b"]
2001 y = [1, 2, 3, 4]
2002 hue = ["x", "x", "y", "y"]
2003
2004 ax = barplot(x=x, y=y, hue=hue, gap=.25, legend=False)
2005 for i, bar in enumerate(ax.patches):
2006 assert bar.get_width() == approx(0.8 / 2 * .75)
2007
2008 def test_hue_undodged(self):
2009
2010 x = ["a", "b", "a", "b"]
2011 y = [1, 2, 3, 4]
2012 hue = ["x", "x", "y", "y"]
2013
2014 ax = barplot(x=x, y=y, hue=hue, saturation=1, dodge=False, legend=False)
2015 for i, bar in enumerate(ax.patches):
2016 assert bar.get_x() + bar.get_width() / 2 == approx(i % 2)
2017 assert bar.get_y() == 0
2018 assert bar.get_height() == y[i]
2019 assert bar.get_width() == approx(0.8)
2020 assert same_color(bar.get_facecolor(), f"C{i // 2}")
2021
2022 def test_hue_order(self):
2023
2024 x, y = ["a", "b", "c"], [1, 2, 3]
2025 hue_order = ["c", "b", "a"]
2026
2027 ax = barplot(x=x, y=y, hue=x, hue_order=hue_order, saturation=1)
2028 for i, bar in enumerate(ax.patches):
2029 assert same_color(bar.get_facecolor(), f"C{i}")
2030 assert bar.get_x() + bar.get_width() / 2 == approx(2 - i)
2031
2032 def test_hue_norm(self):
2033
2034 x, y = [1, 2, 3, 4], [1, 2, 3, 4]
2035
2036 ax = barplot(x=x, y=y, hue=x, hue_norm=(2, 3))
2037 colors = [bar.get_facecolor() for bar in ax.patches]
2038 assert colors[0] == colors[1]
2039 assert colors[1] != colors[2]
2040 assert colors[2] == colors[3]
2041
2042 def test_fill(self):
2043
2044 x = ["a", "b", "a", "b"]
2045 y = [1, 2, 3, 4]
2046 hue = ["x", "x", "y", "y"]
2047
2048 ax = barplot(x=x, y=y, hue=hue, fill=False, legend=False)
2049 for i, bar in enumerate(ax.patches):
2050 assert same_color(bar.get_edgecolor(), f"C{i // 2}")
2051 assert same_color(bar.get_facecolor(), (0, 0, 0, 0))
2052
2053 def test_xy_native_scale(self):
2054
2055 x, y = [2, 4, 8], [1, 2, 3]
2056
2057 ax = barplot(x=x, y=y, native_scale=True)
2058 for i, bar in enumerate(ax.patches):
2059 assert bar.get_x() + bar.get_width() / 2 == approx(x[i])
2060 assert bar.get_y() == 0
2061 assert bar.get_height() == y[i]
2062 assert bar.get_width() == approx(0.8 * 2)
2063
2064 def test_xy_native_scale_log_transform(self):
2065
2066 x, y = [1, 10, 100], [1, 2, 3]
2067
2068 ax = mpl.figure.Figure().subplots()
2069 ax.set_xscale("log")
2070 barplot(x=x, y=y, native_scale=True, ax=ax)
2071 for i, bar in enumerate(ax.patches):
2072 x0, x1 = np.log10([bar.get_x(), bar.get_x() + bar.get_width()])
2073 center = 10 ** (x0 + (x1 - x0) / 2)
2074 assert center == approx(x[i])
2075 assert bar.get_y() == 0
2076 assert bar.get_height() == y[i]
2077 assert ax.patches[1].get_width() > ax.patches[0].get_width()
2078
2079 def test_datetime_native_scale_axis(self):
2080
2081 x = pd.date_range("2010-01-01", periods=20, freq="MS")
2082 y = np.arange(20)
2083 ax = barplot(x=x, y=y, native_scale=True)
2084 assert "Date" in ax.xaxis.get_major_locator().__class__.__name__
2085 day = "2003-02-28"
2086 assert_array_equal(ax.xaxis.convert_units([day]), mpl.dates.date2num([day]))
2087
2088 def test_native_scale_dodged(self):
2089
2090 x, y = [2, 4, 2, 4], [1, 2, 3, 4]
2091 hue = ["x", "x", "y", "y"]
2092
2093 ax = barplot(x=x, y=y, hue=hue, native_scale=True)
2094
2095 for x_i, bar in zip(x[:2], ax.patches[:2]):
2096 assert bar.get_x() + bar.get_width() == approx(x_i)
2097 for x_i, bar in zip(x[2:], ax.patches[2:]):
2098 assert bar.get_x() == approx(x_i)
2099
2100 def test_native_scale_log_transform_dodged(self):
2101
2102 x, y = [1, 100, 1, 100], [1, 2, 3, 4]
2103 hue = ["x", "x", "y", "y"]
2104
2105 ax = mpl.figure.Figure().subplots()
2106 ax.set_xscale("log")
2107 barplot(x=x, y=y, hue=hue, native_scale=True, ax=ax)
2108
2109 for x_i, bar in zip(x[:2], ax.patches[:2]):
2110 assert bar.get_x() + bar.get_width() == approx(x_i)
2111 for x_i, bar in zip(x[2:], ax.patches[2:]):
2112 assert bar.get_x() == approx(x_i)
2113
2114 def test_estimate_default(self, long_df):
2115
2116 agg_var, val_var = "a", "y"
2117 agg_df = long_df.groupby(agg_var)[val_var].mean()
2118
2119 ax = barplot(long_df, x=agg_var, y=val_var, errorbar=None)
2120 order = categorical_order(long_df[agg_var])
2121 for i, bar in enumerate(ax.patches):
2122 assert bar.get_height() == approx(agg_df[order[i]])
2123
2124 def test_estimate_string(self, long_df):
2125
2126 agg_var, val_var = "a", "y"
2127 agg_df = long_df.groupby(agg_var)[val_var].median()
2128
2129 ax = barplot(long_df, x=agg_var, y=val_var, estimator="median", errorbar=None)
2130 order = categorical_order(long_df[agg_var])
2131 for i, bar in enumerate(ax.patches):
2132 assert bar.get_height() == approx(agg_df[order[i]])
2133
2134 def test_estimate_func(self, long_df):
2135
2136 agg_var, val_var = "a", "y"
2137 agg_df = long_df.groupby(agg_var)[val_var].median()
2138
2139 ax = barplot(long_df, x=agg_var, y=val_var, estimator=np.median, errorbar=None)
2140 order = categorical_order(long_df[agg_var])
2141 for i, bar in enumerate(ax.patches):
2142 assert bar.get_height() == approx(agg_df[order[i]])
2143
2144 def test_weighted_estimate(self, long_df):
2145
2146 ax = barplot(long_df, y="y", weights="x")
2147 height = ax.patches[0].get_height()
2148 expected = np.average(long_df["y"], weights=long_df["x"])
2149 assert height == expected
2150
2151 def test_estimate_log_transform(self, long_df):
2152
2153 ax = mpl.figure.Figure().subplots()
2154 ax.set_xscale("log")
2155 barplot(x=long_df["z"], ax=ax)
2156 bar, = ax.patches
2157 assert bar.get_width() == 10 ** np.log10(long_df["z"]).mean()
2158
2159 def test_errorbars(self, long_df):
2160
2161 agg_var, val_var = "a", "y"
2162 agg_df = long_df.groupby(agg_var)[val_var].agg(["mean", "std"])
2163
2164 ax = barplot(long_df, x=agg_var, y=val_var, errorbar="sd")
2165 order = categorical_order(long_df[agg_var])
2166 for i, line in enumerate(ax.lines):
2167 row = agg_df.loc[order[i]]
2168 lo, hi = line.get_ydata()
2169 assert lo == approx(row["mean"] - row["std"])
2170 assert hi == approx(row["mean"] + row["std"])
2171
2172 def test_width(self):
2173
2174 width = .5
2175 x, y = ["a", "b", "c"], [1, 2, 3]
2176 ax = barplot(x=x, y=y, width=width)
2177 for i, bar in enumerate(ax.patches):
2178 assert bar.get_x() + bar.get_width() / 2 == approx(i)
2179 assert bar.get_width() == width
2180
2181 def test_width_native_scale(self):
2182
2183 width = .5
2184 x, y = [4, 6, 10], [1, 2, 3]
2185 ax = barplot(x=x, y=y, width=width, native_scale=True)
2186 for bar in ax.patches:
2187 assert bar.get_width() == (width * 2)
2188
2189 def test_width_spaced_categories(self):
2190
2191 ax = barplot(x=["a", "b", "c"], y=[4, 5, 6])
2192 barplot(x=["a", "c"], y=[1, 3], ax=ax)
2193 for bar in ax.patches:
2194 assert bar.get_width() == pytest.approx(0.8)
2195
2196 def test_saturation_color(self):
2197
2198 color = (.1, .9, .2)
2199 x, y = ["a", "b", "c"], [1, 2, 3]
2200 ax = barplot(x=x, y=y)
2201 for bar in ax.patches:
2202 assert np.var(bar.get_facecolor()[:3]) < np.var(color)
2203
2204 def test_saturation_palette(self):
2205
2206 palette = color_palette("viridis", 3)
2207 x, y = ["a", "b", "c"], [1, 2, 3]
2208 ax = barplot(x=x, y=y, hue=x, palette=palette)
2209 for i, bar in enumerate(ax.patches):
2210 assert np.var(bar.get_facecolor()[:3]) < np.var(palette[i])
2211
2212 def test_legend_numeric_auto(self, long_df):
2213
2214 ax = barplot(long_df, x="x", y="y", hue="x")
2215 assert len(ax.get_legend().texts) <= 6
2216
2217 def test_legend_numeric_full(self, long_df):
2218
2219 ax = barplot(long_df, x="x", y="y", hue="x", legend="full")
2220 labels = [t.get_text() for t in ax.get_legend().texts]
2221 levels = [str(x) for x in sorted(long_df["x"].unique())]
2222 assert labels == levels
2223
2224 def test_legend_disabled(self, long_df):
2225
2226 ax = barplot(long_df, x="x", y="y", hue="b", legend=False)
2227 assert ax.get_legend() is None
2228
2229 def test_error_caps(self):
2230
2231 x, y = ["a", "b", "c"] * 2, [1, 2, 3, 4, 5, 6]
2232 ax = barplot(x=x, y=y, capsize=.8, errorbar="pi")
2233
2234 assert len(ax.patches) == len(ax.lines)
2235 for bar, error in zip(ax.patches, ax.lines):
2236 pos = error.get_xdata()
2237 assert len(pos) == 8
2238 assert np.nanmin(pos) == approx(bar.get_x())
2239 assert np.nanmax(pos) == approx(bar.get_x() + bar.get_width())
2240
2241 def test_error_caps_native_scale(self):
2242
2243 x, y = [2, 4, 20] * 2, [1, 2, 3, 4, 5, 6]
2244 ax = barplot(x=x, y=y, capsize=.8, native_scale=True, errorbar="pi")
2245
2246 assert len(ax.patches) == len(ax.lines)
2247 for bar, error in zip(ax.patches, ax.lines):
2248 pos = error.get_xdata()
2249 assert len(pos) == 8
2250 assert np.nanmin(pos) == approx(bar.get_x())
2251 assert np.nanmax(pos) == approx(bar.get_x() + bar.get_width())
2252
2253 def test_error_caps_native_scale_log_transform(self):
2254
2255 x, y = [1, 10, 1000] * 2, [1, 2, 3, 4, 5, 6]
2256 ax = mpl.figure.Figure().subplots()
2257 ax.set_xscale("log")
2258 barplot(x=x, y=y, capsize=.8, native_scale=True, errorbar="pi", ax=ax)
2259
2260 assert len(ax.patches) == len(ax.lines)
2261 for bar, error in zip(ax.patches, ax.lines):
2262 pos = error.get_xdata()
2263 assert len(pos) == 8
2264 assert np.nanmin(pos) == approx(bar.get_x())
2265 assert np.nanmax(pos) == approx(bar.get_x() + bar.get_width())
2266
2267 def test_bar_kwargs(self):
2268
2269 x, y = ["a", "b", "c"], [1, 2, 3]
2270 kwargs = dict(linewidth=3, facecolor=(.5, .4, .3, .2), rasterized=True)
2271 ax = barplot(x=x, y=y, **kwargs)
2272 for bar in ax.patches:
2273 assert bar.get_linewidth() == kwargs["linewidth"]
2274 assert bar.get_facecolor() == kwargs["facecolor"]
2275 assert bar.get_rasterized() == kwargs["rasterized"]
2276
2277 def test_legend_attributes(self, long_df):
2278
2279 palette = color_palette()
2280 ax = barplot(
2281 long_df, x="a", y="y", hue="c", saturation=1, edgecolor="k", linewidth=3
2282 )
2283 for i, patch in enumerate(get_legend_handles(ax.get_legend())):
2284 assert same_color(patch.get_facecolor(), palette[i])
2285 assert same_color(patch.get_edgecolor(), "k")
2286 assert patch.get_linewidth() == 3
2287
2288 def test_legend_unfilled(self, long_df):
2289
2290 palette = color_palette()
2291 ax = barplot(long_df, x="a", y="y", hue="c", fill=False, linewidth=3)
2292 for i, patch in enumerate(get_legend_handles(ax.get_legend())):
2293 assert patch.get_facecolor() == (0, 0, 0, 0)
2294 assert same_color(patch.get_edgecolor(), palette[i])
2295 assert patch.get_linewidth() == 3
2296
2297 @pytest.mark.parametrize("fill", [True, False])
2298 def test_err_kws(self, fill):
2299
2300 x, y = ["a", "b", "c"], [1, 2, 3]
2301 err_kws = dict(color=(1, 1, .5, .5), linewidth=5)
2302 ax = barplot(x=x, y=y, fill=fill, err_kws=err_kws)
2303 for line in ax.lines:
2304 assert line.get_color() == err_kws["color"]
2305 assert line.get_linewidth() == err_kws["linewidth"]
2306
2307 @pytest.mark.parametrize(
2308 "kwargs",
2309 [
2310 dict(data="wide"),
2311 dict(data="wide", orient="h"),
2312 dict(data="flat"),
2313 dict(data="long", x="a", y="y"),
2314 dict(data=None, x="a", y="y"),
2315 dict(data="long", x="a", y="y", hue="a"),
2316 dict(data=None, x="a", y="y", hue="a"),
2317 dict(data="long", x="a", y="y", hue="b"),
2318 dict(data=None, x="s", y="y", hue="a"),
2319 dict(data="long", x="a", y="y", hue="s"),
2320 dict(data="long", x="a", y="y", units="c"),
2321 dict(data="null", x="a", y="y", hue="a", gap=.1, fill=False),
2322 dict(data="long", x="s", y="y", hue="a", native_scale=True),
2323 dict(data="long", x="d", y="y", hue="a", native_scale=True),
2324 dict(data="long", x="a", y="y", errorbar=("pi", 50)),
2325 dict(data="long", x="a", y="y", errorbar=None),
2326 dict(data="long", x="a", y="y", capsize=.3, err_kws=dict(c="k")),
2327 dict(data="long", x="a", y="y", color="blue", edgecolor="green", alpha=.5),
2328 ]
2329 )
2330 def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
2331
2332 kwargs = kwargs.copy()
2333 kwargs["seed"] = 0
2334 kwargs["n_boot"] = 10
2335
2336 if kwargs["data"] == "long":
2337 kwargs["data"] = long_df
2338 elif kwargs["data"] == "wide":
2339 kwargs["data"] = wide_df
2340 elif kwargs["data"] == "flat":
2341 kwargs["data"] = flat_series
2342 elif kwargs["data"] == "null":
2343 kwargs["data"] = null_df
2344 elif kwargs["data"] is None:
2345 for var in ["x", "y", "hue"]:
2346 if var in kwargs:
2347 kwargs[var] = long_df[kwargs[var]]
2348
2349 ax = barplot(**kwargs)
2350 g = catplot(**kwargs, kind="bar")
2351
2352 assert_plots_equal(ax, g.ax)
2353
2354 def test_errwidth_deprecation(self):
2355
2356 x, y = ["a", "b", "c"], [1, 2, 3]
2357 val = 5
2358 with pytest.warns(FutureWarning, match="\n\nThe `errwidth` parameter"):
2359 ax = barplot(x=x, y=y, errwidth=val)
2360 for line in ax.lines:
2361 assert line.get_linewidth() == val
2362
2363 def test_errcolor_deprecation(self):
2364
2365 x, y = ["a", "b", "c"], [1, 2, 3]
2366 val = (1, .7, .4, .8)
2367 with pytest.warns(FutureWarning, match="\n\nThe `errcolor` parameter"):
2368 ax = barplot(x=x, y=y, errcolor=val)
2369 for line in ax.lines:
2370 assert line.get_color() == val
2371
2372 def test_capsize_as_none_deprecation(self):
2373
2374 x, y = ["a", "b", "c"], [1, 2, 3]
2375 with pytest.warns(FutureWarning, match="\n\nPassing `capsize=None`"):
2376 ax = barplot(x=x, y=y, capsize=None)
2377 for line in ax.lines:
2378 assert len(line.get_xdata()) == 2
2379
2380 def test_hue_implied_by_palette_deprecation(self):
2381
2382 x = ["a", "b", "c"]
2383 y = [1, 2, 3]
2384 palette = "Set1"
2385 colors = color_palette(palette, len(x))
2386 msg = "Passing `palette` without assigning `hue` is deprecated."
2387 with pytest.warns(FutureWarning, match=msg):
2388 ax = barplot(x=x, y=y, saturation=1, palette=palette)
2389 for i, bar in enumerate(ax.patches):
2390 assert same_color(bar.get_facecolor(), colors[i])
2391
2392
2393 class TestPointPlot(SharedAggTests):
2394
2395 func = staticmethod(pointplot)
2396
2397 def get_last_color(self, ax):
2398
2399 color = ax.lines[-1].get_color()
2400 return to_rgba(color)
2401
2402 @pytest.mark.parametrize("orient", ["x", "y"])
2403 def test_single_var(self, orient):
2404
2405 vals = pd.Series([1, 3, 10])
2406 ax = pointplot(**{orient: vals})
2407 line = ax.lines[0]
2408 assert getattr(line, f"get_{orient}data")() == approx(vals.mean())
2409
2410 @pytest.mark.parametrize("orient", ["x", "y", "h", "v"])
2411 def test_wide_df(self, wide_df, orient):
2412
2413 ax = pointplot(wide_df, orient=orient)
2414 orient = {"h": "y", "v": "x"}.get(orient, orient)
2415 depend = {"x": "y", "y": "x"}[orient]
2416 line = ax.lines[0]
2417 assert_array_equal(
2418 getattr(line, f"get_{orient}data")(),
2419 np.arange(len(wide_df.columns)),
2420 )
2421 assert_array_almost_equal(
2422 getattr(line, f"get_{depend}data")(),
2423 wide_df.mean(axis=0),
2424 )
2425
2426 @pytest.mark.parametrize("orient", ["x", "y", "h", "v"])
2427 def test_vector_orient(self, orient):
2428
2429 keys, vals = ["a", "b", "c"], [1, 2, 3]
2430 data = dict(zip(keys, vals))
2431 orient = {"h": "y", "v": "x"}.get(orient, orient)
2432 depend = {"x": "y", "y": "x"}[orient]
2433 ax = pointplot(data, orient=orient)
2434 line = ax.lines[0]
2435 assert_array_equal(
2436 getattr(line, f"get_{orient}data")(),
2437 np.arange(len(keys)),
2438 )
2439 assert_array_equal(getattr(line, f"get_{depend}data")(), vals)
2440
2441 def test_xy_vertical(self):
2442
2443 x, y = ["a", "b", "c"], [1, 3, 2.5]
2444 ax = pointplot(x=x, y=y)
2445 for i, xy in enumerate(ax.lines[0].get_xydata()):
2446 assert tuple(xy) == (i, y[i])
2447
2448 def test_xy_horizontal(self):
2449
2450 x, y = [1, 3, 2.5], ["a", "b", "c"]
2451 ax = pointplot(x=x, y=y)
2452 for i, xy in enumerate(ax.lines[0].get_xydata()):
2453 assert tuple(xy) == (x[i], i)
2454
2455 def test_xy_with_na_grouper(self):
2456
2457 x, y = ["a", None, "b"], [1, 2, 3]
2458 ax = pointplot(x=x, y=y)
2459 _draw_figure(ax.figure) # For matplotlib<3.5
2460 assert ax.get_xticks() == [0, 1]
2461 assert [t.get_text() for t in ax.get_xticklabels()] == ["a", "b"]
2462 assert_array_equal(ax.lines[0].get_xdata(), [0, 1])
2463 assert_array_equal(ax.lines[0].get_ydata(), [1, 3])
2464
2465 def test_xy_with_na_value(self):
2466
2467 x, y = ["a", "b", "c"], [1, np.nan, 3]
2468 ax = pointplot(x=x, y=y)
2469 _draw_figure(ax.figure) # For matplotlib<3.5
2470 assert ax.get_xticks() == [0, 1, 2]
2471 assert [t.get_text() for t in ax.get_xticklabels()] == x
2472 assert_array_equal(ax.lines[0].get_xdata(), [0, 1, 2])
2473 assert_array_equal(ax.lines[0].get_ydata(), y)
2474
2475 def test_hue(self):
2476
2477 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2478 hue = ["x", "y", "x", "y"]
2479 ax = pointplot(x=x, y=y, hue=hue, errorbar=None)
2480 for i, line in enumerate(ax.lines[:2]):
2481 assert_array_equal(line.get_ydata(), y[i::2])
2482 assert same_color(line.get_color(), f"C{i}")
2483
2484 def test_wide_data_is_joined(self, wide_df):
2485
2486 ax = pointplot(wide_df, errorbar=None)
2487 assert len(ax.lines) == 1
2488
2489 def test_xy_native_scale(self):
2490
2491 x, y = [2, 4, 8], [1, 2, 3]
2492
2493 ax = pointplot(x=x, y=y, native_scale=True)
2494 line = ax.lines[0]
2495 assert_array_equal(line.get_xdata(), x)
2496 assert_array_equal(line.get_ydata(), y)
2497
2498 # Use lambda around np.mean to avoid uninformative pandas deprecation warning
2499 @pytest.mark.parametrize("estimator", ["mean", lambda x: np.mean(x)])
2500 def test_estimate(self, long_df, estimator):
2501
2502 agg_var, val_var = "a", "y"
2503 agg_df = long_df.groupby(agg_var)[val_var].agg(estimator)
2504
2505 ax = pointplot(long_df, x=agg_var, y=val_var, errorbar=None)
2506 order = categorical_order(long_df[agg_var])
2507 for i, xy in enumerate(ax.lines[0].get_xydata()):
2508 assert tuple(xy) == approx((i, agg_df[order[i]]))
2509
2510 def test_weighted_estimate(self, long_df):
2511
2512 ax = pointplot(long_df, y="y", weights="x")
2513 val = ax.lines[0].get_ydata().item()
2514 expected = np.average(long_df["y"], weights=long_df["x"])
2515 assert val == expected
2516
2517 def test_estimate_log_transform(self, long_df):
2518
2519 ax = mpl.figure.Figure().subplots()
2520 ax.set_xscale("log")
2521 pointplot(x=long_df["z"], ax=ax)
2522 val, = ax.lines[0].get_xdata()
2523 assert val == 10 ** np.log10(long_df["z"]).mean()
2524
2525 def test_errorbars(self, long_df):
2526
2527 agg_var, val_var = "a", "y"
2528 agg_df = long_df.groupby(agg_var)[val_var].agg(["mean", "std"])
2529
2530 ax = pointplot(long_df, x=agg_var, y=val_var, errorbar="sd")
2531 order = categorical_order(long_df[agg_var])
2532 for i, line in enumerate(ax.lines[1:]):
2533 row = agg_df.loc[order[i]]
2534 lo, hi = line.get_ydata()
2535 assert lo == approx(row["mean"] - row["std"])
2536 assert hi == approx(row["mean"] + row["std"])
2537
2538 def test_marker_linestyle(self):
2539
2540 x, y = ["a", "b", "c"], [1, 2, 3]
2541 ax = pointplot(x=x, y=y, marker="s", linestyle="--")
2542 line = ax.lines[0]
2543 assert line.get_marker() == "s"
2544 assert line.get_linestyle() == "--"
2545
2546 def test_markers_linestyles_single(self):
2547
2548 x, y = ["a", "b", "c"], [1, 2, 3]
2549 ax = pointplot(x=x, y=y, markers="s", linestyles="--")
2550 line = ax.lines[0]
2551 assert line.get_marker() == "s"
2552 assert line.get_linestyle() == "--"
2553
2554 def test_markers_linestyles_mapped(self):
2555
2556 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2557 hue = ["x", "y", "x", "y"]
2558 markers = ["d", "s"]
2559 linestyles = ["--", ":"]
2560 ax = pointplot(
2561 x=x, y=y, hue=hue,
2562 markers=markers, linestyles=linestyles,
2563 errorbar=None,
2564 )
2565 for i, line in enumerate(ax.lines[:2]):
2566 assert line.get_marker() == markers[i]
2567 assert line.get_linestyle() == linestyles[i]
2568
2569 def test_dodge_boolean(self):
2570
2571 x, y = ["a", "b", "a", "b"], [1, 2, 3, 4]
2572 hue = ["x", "x", "y", "y"]
2573 ax = pointplot(x=x, y=y, hue=hue, dodge=True, errorbar=None)
2574 for i, xy in enumerate(ax.lines[0].get_xydata()):
2575 assert tuple(xy) == (i - .025, y[i])
2576 for i, xy in enumerate(ax.lines[1].get_xydata()):
2577 assert tuple(xy) == (i + .025, y[2 + i])
2578
2579 def test_dodge_float(self):
2580
2581 x, y = ["a", "b", "a", "b"], [1, 2, 3, 4]
2582 hue = ["x", "x", "y", "y"]
2583 ax = pointplot(x=x, y=y, hue=hue, dodge=.2, errorbar=None)
2584 for i, xy in enumerate(ax.lines[0].get_xydata()):
2585 assert tuple(xy) == (i - .1, y[i])
2586 for i, xy in enumerate(ax.lines[1].get_xydata()):
2587 assert tuple(xy) == (i + .1, y[2 + i])
2588
2589 def test_dodge_log_scale(self):
2590
2591 x, y = [10, 1000, 10, 1000], [1, 2, 3, 4]
2592 hue = ["x", "x", "y", "y"]
2593 ax = mpl.figure.Figure().subplots()
2594 ax.set_xscale("log")
2595 pointplot(x=x, y=y, hue=hue, dodge=.2, native_scale=True, errorbar=None, ax=ax)
2596 for i, xy in enumerate(ax.lines[0].get_xydata()):
2597 assert tuple(xy) == approx((10 ** (np.log10(x[i]) - .2), y[i]))
2598 for i, xy in enumerate(ax.lines[1].get_xydata()):
2599 assert tuple(xy) == approx((10 ** (np.log10(x[2 + i]) + .2), y[2 + i]))
2600
2601 def test_err_kws(self):
2602
2603 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2604 err_kws = dict(color=(.2, .5, .3), linewidth=10)
2605 ax = pointplot(x=x, y=y, errorbar=("pi", 100), err_kws=err_kws)
2606 for line in ax.lines[1:]:
2607 assert same_color(line.get_color(), err_kws["color"])
2608 assert line.get_linewidth() == err_kws["linewidth"]
2609
2610 def test_err_kws_inherited(self):
2611
2612 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2613 kws = dict(color=(.2, .5, .3), linewidth=10)
2614 ax = pointplot(x=x, y=y, errorbar=("pi", 100), **kws)
2615 for line in ax.lines[1:]:
2616 assert same_color(line.get_color(), kws["color"])
2617 assert line.get_linewidth() == kws["linewidth"]
2618
2619 @pytest.mark.skipif(
2620 _version_predates(mpl, "3.6"),
2621 reason="Legend handle missing marker property"
2622 )
2623 def test_legend_contents(self):
2624
2625 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2626 hue = ["x", "y", "x", "y"]
2627 ax = pointplot(x=x, y=y, hue=hue)
2628 _draw_figure(ax.figure)
2629 legend = ax.get_legend()
2630 assert [t.get_text() for t in legend.texts] == ["x", "y"]
2631 for i, handle in enumerate(get_legend_handles(legend)):
2632 assert handle.get_marker() == "o"
2633 assert handle.get_linestyle() == "-"
2634 assert same_color(handle.get_color(), f"C{i}")
2635
2636 @pytest.mark.skipif(
2637 _version_predates(mpl, "3.6"),
2638 reason="Legend handle missing marker property"
2639 )
2640 def test_legend_set_props(self):
2641
2642 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2643 hue = ["x", "y", "x", "y"]
2644 kws = dict(marker="s", linewidth=1)
2645 ax = pointplot(x=x, y=y, hue=hue, **kws)
2646 legend = ax.get_legend()
2647 for i, handle in enumerate(get_legend_handles(legend)):
2648 assert handle.get_marker() == kws["marker"]
2649 assert handle.get_linewidth() == kws["linewidth"]
2650
2651 @pytest.mark.skipif(
2652 _version_predates(mpl, "3.6"),
2653 reason="Legend handle missing marker property"
2654 )
2655 def test_legend_synced_props(self):
2656
2657 x, y = ["a", "a", "b", "b"], [1, 2, 3, 4]
2658 hue = ["x", "y", "x", "y"]
2659 kws = dict(markers=["s", "d"], linestyles=["--", ":"])
2660 ax = pointplot(x=x, y=y, hue=hue, **kws)
2661 legend = ax.get_legend()
2662 for i, handle in enumerate(get_legend_handles(legend)):
2663 assert handle.get_marker() == kws["markers"][i]
2664 assert handle.get_linestyle() == kws["linestyles"][i]
2665
2666 @pytest.mark.parametrize(
2667 "kwargs",
2668 [
2669 dict(data="wide"),
2670 dict(data="wide", orient="h"),
2671 dict(data="flat"),
2672 dict(data="long", x="a", y="y"),
2673 dict(data=None, x="a", y="y"),
2674 dict(data="long", x="a", y="y", hue="a"),
2675 dict(data=None, x="a", y="y", hue="a"),
2676 dict(data="long", x="a", y="y", hue="b"),
2677 dict(data=None, x="s", y="y", hue="a"),
2678 dict(data="long", x="a", y="y", hue="s"),
2679 dict(data="long", x="a", y="y", units="c"),
2680 dict(data="null", x="a", y="y", hue="a"),
2681 dict(data="long", x="s", y="y", hue="a", native_scale=True),
2682 dict(data="long", x="d", y="y", hue="a", native_scale=True),
2683 dict(data="long", x="a", y="y", errorbar=("pi", 50)),
2684 dict(data="long", x="a", y="y", errorbar=None),
2685 dict(data="null", x="a", y="y", hue="a", dodge=True),
2686 dict(data="null", x="a", y="y", hue="a", dodge=.2),
2687 dict(data="long", x="a", y="y", capsize=.3, err_kws=dict(c="k")),
2688 dict(data="long", x="a", y="y", color="blue", marker="s"),
2689 dict(data="long", x="a", y="y", hue="a", markers=["s", "d", "p"]),
2690 ]
2691 )
2692 def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
2693
2694 kwargs = kwargs.copy()
2695 kwargs["seed"] = 0
2696 kwargs["n_boot"] = 10
2697
2698 if kwargs["data"] == "long":
2699 kwargs["data"] = long_df
2700 elif kwargs["data"] == "wide":
2701 kwargs["data"] = wide_df
2702 elif kwargs["data"] == "flat":
2703 kwargs["data"] = flat_series
2704 elif kwargs["data"] == "null":
2705 kwargs["data"] = null_df
2706 elif kwargs["data"] is None:
2707 for var in ["x", "y", "hue"]:
2708 if var in kwargs:
2709 kwargs[var] = long_df[kwargs[var]]
2710
2711 ax = pointplot(**kwargs)
2712 g = catplot(**kwargs, kind="point")
2713
2714 assert_plots_equal(ax, g.ax)
2715
2716 def test_legend_disabled(self, long_df):
2717
2718 ax = pointplot(long_df, x="x", y="y", hue="b", legend=False)
2719 assert ax.get_legend() is None
2720
2721 def test_join_deprecation(self):
2722
2723 with pytest.warns(UserWarning, match="The `join` parameter"):
2724 ax = pointplot(x=["a", "b", "c"], y=[1, 2, 3], join=False)
2725 assert ax.lines[0].get_linestyle().lower() == "none"
2726
2727 def test_scale_deprecation(self):
2728
2729 x, y = ["a", "b", "c"], [1, 2, 3]
2730 ax = pointplot(x=x, y=y, errorbar=None)
2731 with pytest.warns(UserWarning, match="The `scale` parameter"):
2732 pointplot(x=x, y=y, errorbar=None, scale=2)
2733 l1, l2 = ax.lines
2734 assert l2.get_linewidth() == 2 * l1.get_linewidth()
2735 assert l2.get_markersize() > l1.get_markersize()
2736
2737 def test_layered_plot_clipping(self):
2738
2739 x, y = ['a'], [4]
2740 pointplot(x=x, y=y)
2741 x, y = ['b'], [5]
2742 ax = pointplot(x=x, y=y)
2743 y_range = ax.viewLim.intervaly
2744 assert y_range[0] < 4 and y_range[1] > 5
2745
2746
2747 class TestCountPlot:
2748
2749 def test_empty(self):
2750
2751 ax = countplot()
2752 assert not ax.patches
2753
2754 ax = countplot(x=[])
2755 assert not ax.patches
2756
2757 def test_labels_long(self, long_df):
2758
2759 fig = mpl.figure.Figure()
2760 axs = fig.subplots(2)
2761 countplot(long_df, x="a", ax=axs[0])
2762 countplot(long_df, x="b", stat="percent", ax=axs[1])
2763
2764 # To populate texts; only needed on older matplotlibs
2765 _draw_figure(fig)
2766
2767 assert axs[0].get_xlabel() == "a"
2768 assert axs[1].get_xlabel() == "b"
2769 assert axs[0].get_ylabel() == "count"
2770 assert axs[1].get_ylabel() == "percent"
2771
2772 def test_wide_data(self, wide_df):
2773
2774 ax = countplot(wide_df)
2775 assert len(ax.patches) == len(wide_df.columns)
2776 for i, bar in enumerate(ax.patches):
2777 assert bar.get_x() + bar.get_width() / 2 == approx(i)
2778 assert bar.get_y() == 0
2779 assert bar.get_height() == len(wide_df)
2780 assert bar.get_width() == approx(0.8)
2781
2782 def test_flat_series(self):
2783
2784 vals = ["a", "b", "c"]
2785 counts = [2, 1, 4]
2786 vals = pd.Series([x for x, n in zip(vals, counts) for _ in range(n)])
2787 ax = countplot(vals)
2788 for i, bar in enumerate(ax.patches):
2789 assert bar.get_x() == 0
2790 assert bar.get_y() + bar.get_height() / 2 == approx(i)
2791 assert bar.get_height() == approx(0.8)
2792 assert bar.get_width() == counts[i]
2793
2794 def test_x_series(self):
2795
2796 vals = ["a", "b", "c"]
2797 counts = [2, 1, 4]
2798 vals = pd.Series([x for x, n in zip(vals, counts) for _ in range(n)])
2799 ax = countplot(x=vals)
2800 for i, bar in enumerate(ax.patches):
2801 assert bar.get_x() + bar.get_width() / 2 == approx(i)
2802 assert bar.get_y() == 0
2803 assert bar.get_height() == counts[i]
2804 assert bar.get_width() == approx(0.8)
2805
2806 def test_y_series(self):
2807
2808 vals = ["a", "b", "c"]
2809 counts = [2, 1, 4]
2810 vals = pd.Series([x for x, n in zip(vals, counts) for _ in range(n)])
2811 ax = countplot(y=vals)
2812 for i, bar in enumerate(ax.patches):
2813 assert bar.get_x() == 0
2814 assert bar.get_y() + bar.get_height() / 2 == approx(i)
2815 assert bar.get_height() == approx(0.8)
2816 assert bar.get_width() == counts[i]
2817
2818 def test_hue_redundant(self):
2819
2820 vals = ["a", "b", "c"]
2821 counts = [2, 1, 4]
2822 vals = pd.Series([x for x, n in zip(vals, counts) for _ in range(n)])
2823
2824 ax = countplot(x=vals, hue=vals, saturation=1)
2825 for i, bar in enumerate(ax.patches):
2826 assert bar.get_x() + bar.get_width() / 2 == approx(i)
2827 assert bar.get_y() == 0
2828 assert bar.get_height() == counts[i]
2829 assert bar.get_width() == approx(0.8)
2830 assert same_color(bar.get_facecolor(), f"C{i}")
2831
2832 def test_hue_dodged(self):
2833
2834 vals = ["a", "a", "a", "b", "b", "b"]
2835 hue = ["x", "y", "y", "x", "x", "x"]
2836 counts = [1, 3, 2, 0]
2837
2838 ax = countplot(x=vals, hue=hue, saturation=1, legend=False)
2839 for i, bar in enumerate(ax.patches):
2840 sign = 1 if i // 2 else -1
2841 assert (
2842 bar.get_x() + bar.get_width() / 2
2843 == approx(i % 2 + sign * 0.8 / 4)
2844 )
2845 assert bar.get_y() == 0
2846 assert bar.get_height() == counts[i]
2847 assert bar.get_width() == approx(0.8 / 2)
2848 assert same_color(bar.get_facecolor(), f"C{i // 2}")
2849
2850 @pytest.mark.parametrize("stat", ["percent", "probability", "proportion"])
2851 def test_stat(self, long_df, stat):
2852
2853 col = "a"
2854 order = categorical_order(long_df[col])
2855 expected = long_df[col].value_counts(normalize=True)
2856 if stat == "percent":
2857 expected *= 100
2858 ax = countplot(long_df, x=col, stat=stat)
2859 for i, bar in enumerate(ax.patches):
2860 assert bar.get_height() == approx(expected[order[i]])
2861
2862 def test_xy_error(self, long_df):
2863
2864 with pytest.raises(TypeError, match="Cannot pass values for both"):
2865 countplot(long_df, x="a", y="b")
2866
2867 def test_legend_numeric_auto(self, long_df):
2868
2869 ax = countplot(long_df, x="x", hue="x")
2870 assert len(ax.get_legend().texts) <= 6
2871
2872 def test_legend_disabled(self, long_df):
2873
2874 ax = countplot(long_df, x="x", hue="b", legend=False)
2875 assert ax.get_legend() is None
2876
2877 @pytest.mark.parametrize(
2878 "kwargs",
2879 [
2880 dict(data="wide"),
2881 dict(data="wide", orient="h"),
2882 dict(data="flat"),
2883 dict(data="long", x="a"),
2884 dict(data=None, x="a"),
2885 dict(data="long", y="b"),
2886 dict(data="long", x="a", hue="a"),
2887 dict(data=None, x="a", hue="a"),
2888 dict(data="long", x="a", hue="b"),
2889 dict(data=None, x="s", hue="a"),
2890 dict(data="long", x="a", hue="s"),
2891 dict(data="null", x="a", hue="a"),
2892 dict(data="long", x="s", hue="a", native_scale=True),
2893 dict(data="long", x="d", hue="a", native_scale=True),
2894 dict(data="long", x="a", stat="percent"),
2895 dict(data="long", x="a", hue="b", stat="proportion"),
2896 dict(data="long", x="a", color="blue", ec="green", alpha=.5),
2897 ]
2898 )
2899 def test_vs_catplot(self, long_df, wide_df, null_df, flat_series, kwargs):
2900
2901 kwargs = kwargs.copy()
2902 if kwargs["data"] == "long":
2903 kwargs["data"] = long_df
2904 elif kwargs["data"] == "wide":
2905 kwargs["data"] = wide_df
2906 elif kwargs["data"] == "flat":
2907 kwargs["data"] = flat_series
2908 elif kwargs["data"] == "null":
2909 kwargs["data"] = null_df
2910 elif kwargs["data"] is None:
2911 for var in ["x", "y", "hue"]:
2912 if var in kwargs:
2913 kwargs[var] = long_df[kwargs[var]]
2914
2915 ax = countplot(**kwargs)
2916 g = catplot(**kwargs, kind="count")
2917
2918 assert_plots_equal(ax, g.ax)
2919
2920
2921 class CategoricalFixture:
2922 """Test boxplot (also base class for things like violinplots)."""
2923 rs = np.random.RandomState(30)
2924 n_total = 60
2925 x = rs.randn(int(n_total / 3), 3)
2926 x_df = pd.DataFrame(x, columns=pd.Series(list("XYZ"), name="big"))
2927 y = pd.Series(rs.randn(n_total), name="y_data")
2928 y_perm = y.reindex(rs.choice(y.index, y.size, replace=False))
2929 g = pd.Series(np.repeat(list("abc"), int(n_total / 3)), name="small")
2930 h = pd.Series(np.tile(list("mn"), int(n_total / 2)), name="medium")
2931 u = pd.Series(np.tile(list("jkh"), int(n_total / 3)))
2932 df = pd.DataFrame(dict(y=y, g=g, h=h, u=u))
2933 x_df["W"] = g
2934
2935 def get_box_artists(self, ax):
2936
2937 if _version_predates(mpl, "3.5.0b0"):
2938 return ax.artists
2939 else:
2940 # Exclude labeled patches, which are for the legend
2941 return [p for p in ax.patches if not p.get_label()]
2942
2943
2944 class TestCatPlot(CategoricalFixture):
2945
2946 def test_facet_organization(self):
2947
2948 g = cat.catplot(x="g", y="y", data=self.df)
2949 assert g.axes.shape == (1, 1)
2950
2951 g = cat.catplot(x="g", y="y", col="h", data=self.df)
2952 assert g.axes.shape == (1, 2)
2953
2954 g = cat.catplot(x="g", y="y", row="h", data=self.df)
2955 assert g.axes.shape == (2, 1)
2956
2957 g = cat.catplot(x="g", y="y", col="u", row="h", data=self.df)
2958 assert g.axes.shape == (2, 3)
2959
2960 def test_plot_elements(self):
2961
2962 g = cat.catplot(x="g", y="y", data=self.df, kind="point")
2963 want_lines = 1 + self.g.unique().size
2964 assert len(g.ax.lines) == want_lines
2965
2966 g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="point")
2967 want_lines = (
2968 len(self.g.unique()) * len(self.h.unique()) + 2 * len(self.h.unique())
2969 )
2970 assert len(g.ax.lines) == want_lines
2971
2972 g = cat.catplot(x="g", y="y", data=self.df, kind="bar")
2973 want_elements = self.g.unique().size
2974 assert len(g.ax.patches) == want_elements
2975 assert len(g.ax.lines) == want_elements
2976
2977 g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="bar")
2978 want_elements = self.g.nunique() * self.h.nunique()
2979 assert len(g.ax.patches) == (want_elements + self.h.nunique())
2980 assert len(g.ax.lines) == want_elements
2981
2982 g = cat.catplot(x="g", data=self.df, kind="count")
2983 want_elements = self.g.unique().size
2984 assert len(g.ax.patches) == want_elements
2985 assert len(g.ax.lines) == 0
2986
2987 g = cat.catplot(x="g", hue="h", data=self.df, kind="count")
2988 want_elements = self.g.nunique() * self.h.nunique() + self.h.nunique()
2989 assert len(g.ax.patches) == want_elements
2990 assert len(g.ax.lines) == 0
2991
2992 g = cat.catplot(y="y", data=self.df, kind="box")
2993 want_artists = 1
2994 assert len(self.get_box_artists(g.ax)) == want_artists
2995
2996 g = cat.catplot(x="g", y="y", data=self.df, kind="box")
2997 want_artists = self.g.unique().size
2998 assert len(self.get_box_artists(g.ax)) == want_artists
2999
3000 g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="box")
3001 want_artists = self.g.nunique() * self.h.nunique()
3002 assert len(self.get_box_artists(g.ax)) == want_artists
3003
3004 g = cat.catplot(x="g", y="y", data=self.df,
3005 kind="violin", inner=None)
3006 want_elements = self.g.unique().size
3007 assert len(g.ax.collections) == want_elements
3008
3009 g = cat.catplot(x="g", y="y", hue="h", data=self.df,
3010 kind="violin", inner=None)
3011 want_elements = self.g.nunique() * self.h.nunique()
3012 assert len(g.ax.collections) == want_elements
3013
3014 g = cat.catplot(x="g", y="y", data=self.df, kind="strip")
3015 want_elements = self.g.unique().size
3016 assert len(g.ax.collections) == want_elements
3017 for strip in g.ax.collections:
3018 assert same_color(strip.get_facecolors(), "C0")
3019
3020 g = cat.catplot(x="g", y="y", hue="h", data=self.df, kind="strip")
3021 want_elements = self.g.nunique()
3022 assert len(g.ax.collections) == want_elements
3023
3024 def test_bad_plot_kind_error(self):
3025
3026 with pytest.raises(ValueError):
3027 cat.catplot(x="g", y="y", data=self.df, kind="not_a_kind")
3028
3029 def test_count_x_and_y(self):
3030
3031 with pytest.raises(ValueError):
3032 cat.catplot(x="g", y="y", data=self.df, kind="count")
3033
3034 def test_plot_colors(self):
3035
3036 ax = cat.barplot(x="g", y="y", data=self.df)
3037 g = cat.catplot(x="g", y="y", data=self.df, kind="bar")
3038 for p1, p2 in zip(ax.patches, g.ax.patches):
3039 assert p1.get_facecolor() == p2.get_facecolor()
3040 plt.close("all")
3041
3042 ax = cat.barplot(x="g", y="y", data=self.df, color="purple")
3043 g = cat.catplot(x="g", y="y", data=self.df,
3044 kind="bar", color="purple")
3045 for p1, p2 in zip(ax.patches, g.ax.patches):
3046 assert p1.get_facecolor() == p2.get_facecolor()
3047 plt.close("all")
3048
3049 ax = cat.barplot(x="g", y="y", data=self.df, palette="Set2", hue="h")
3050 g = cat.catplot(x="g", y="y", data=self.df,
3051 kind="bar", palette="Set2", hue="h")
3052 for p1, p2 in zip(ax.patches, g.ax.patches):
3053 assert p1.get_facecolor() == p2.get_facecolor()
3054 plt.close("all")
3055
3056 ax = cat.pointplot(x="g", y="y", data=self.df)
3057 g = cat.catplot(x="g", y="y", data=self.df)
3058 for l1, l2 in zip(ax.lines, g.ax.lines):
3059 assert l1.get_color() == l2.get_color()
3060 plt.close("all")
3061
3062 ax = cat.pointplot(x="g", y="y", data=self.df, color="purple")
3063 g = cat.catplot(x="g", y="y", data=self.df, color="purple", kind="point")
3064 for l1, l2 in zip(ax.lines, g.ax.lines):
3065 assert l1.get_color() == l2.get_color()
3066 plt.close("all")
3067
3068 ax = cat.pointplot(x="g", y="y", data=self.df, palette="Set2", hue="h")
3069 g = cat.catplot(
3070 x="g", y="y", data=self.df, palette="Set2", hue="h", kind="point"
3071 )
3072 for l1, l2 in zip(ax.lines, g.ax.lines):
3073 assert l1.get_color() == l2.get_color()
3074 plt.close("all")
3075
3076 def test_ax_kwarg_removal(self):
3077
3078 f, ax = plt.subplots()
3079 with pytest.warns(UserWarning, match="catplot is a figure-level"):
3080 g = cat.catplot(x="g", y="y", data=self.df, ax=ax)
3081 assert len(ax.collections) == 0
3082 assert len(g.ax.collections) > 0
3083
3084 def test_share_xy(self):
3085
3086 # Test default behavior works
3087 g = cat.catplot(x="g", y="y", col="g", data=self.df, sharex=True)
3088 for ax in g.axes.flat:
3089 assert len(ax.collections) == len(self.df.g.unique())
3090
3091 g = cat.catplot(x="y", y="g", col="g", data=self.df, sharey=True)
3092 for ax in g.axes.flat:
3093 assert len(ax.collections) == len(self.df.g.unique())
3094
3095 # Test unsharing works
3096 g = cat.catplot(
3097 x="g", y="y", col="g", data=self.df, sharex=False, kind="bar",
3098 )
3099 for ax in g.axes.flat:
3100 assert len(ax.patches) == 1
3101
3102 g = cat.catplot(
3103 x="y", y="g", col="g", data=self.df, sharey=False, kind="bar",
3104 )
3105 for ax in g.axes.flat:
3106 assert len(ax.patches) == 1
3107
3108 g = cat.catplot(
3109 x="g", y="y", col="g", data=self.df, sharex=False, color="b"
3110 )
3111 for ax in g.axes.flat:
3112 assert ax.get_xlim() == (-.5, .5)
3113
3114 g = cat.catplot(
3115 x="y", y="g", col="g", data=self.df, sharey=False, color="r"
3116 )
3117 for ax in g.axes.flat:
3118 assert ax.get_ylim() == (.5, -.5)
3119
3120 # Make sure order is used if given, regardless of sharex value
3121 order = self.df.g.unique()
3122 g = cat.catplot(x="g", y="y", col="g", data=self.df, sharex=False, order=order)
3123 for ax in g.axes.flat:
3124 assert len(ax.collections) == len(self.df.g.unique())
3125
3126 g = cat.catplot(x="y", y="g", col="g", data=self.df, sharey=False, order=order)
3127 for ax in g.axes.flat:
3128 assert len(ax.collections) == len(self.df.g.unique())
3129
3130 def test_facetgrid_data(self, long_df):
3131
3132 g1 = catplot(data=long_df, x="a", y="y", col="c")
3133 assert g1.data is long_df
3134
3135 g2 = catplot(x=long_df["a"], y=long_df["y"], col=long_df["c"])
3136 assert g2.data.equals(long_df[["a", "y", "c"]])
3137
3138 @pytest.mark.parametrize("var", ["col", "row"])
3139 def test_array_faceter(self, long_df, var):
3140
3141 g1 = catplot(data=long_df, x="y", **{var: "a"})
3142 g2 = catplot(data=long_df, x="y", **{var: long_df["a"].to_numpy()})
3143
3144 for ax1, ax2 in zip(g1.axes.flat, g2.axes.flat):
3145 assert_plots_equal(ax1, ax2)
3146
3147 def test_invalid_kind(self, long_df):
3148
3149 with pytest.raises(ValueError, match="Invalid `kind`: 'wrong'"):
3150 catplot(long_df, kind="wrong")
3151
3152 def test_legend_with_auto(self):
3153
3154 g1 = catplot(self.df, x="g", y="y", hue="g", legend='auto')
3155 assert g1._legend is None
3156
3157 g2 = catplot(self.df, x="g", y="y", hue="g", legend=True)
3158 assert g2._legend is not None
3159
3160 def test_weights_warning(self, long_df):
3161
3162 with pytest.warns(UserWarning, match="The `weights` parameter"):
3163 g = catplot(long_df, x="a", y="y", weights="z")
3164 assert g.ax is not None
3165
3166
3167 class TestBeeswarm:
3168
3169 def test_could_overlap(self):
3170
3171 p = Beeswarm()
3172 neighbors = p.could_overlap(
3173 (1, 1, .5),
3174 [(0, 0, .5),
3175 (1, .1, .2),
3176 (.5, .5, .5)]
3177 )
3178 assert_array_equal(neighbors, [(.5, .5, .5)])
3179
3180 def test_position_candidates(self):
3181
3182 p = Beeswarm()
3183 xy_i = (0, 1, .5)
3184 neighbors = [(0, 1, .5), (0, 1.5, .5)]
3185 candidates = p.position_candidates(xy_i, neighbors)
3186 dx1 = 1.05
3187 dx2 = np.sqrt(1 - .5 ** 2) * 1.05
3188 assert_array_equal(
3189 candidates,
3190 [(0, 1, .5), (-dx1, 1, .5), (dx1, 1, .5), (dx2, 1, .5), (-dx2, 1, .5)]
3191 )
3192
3193 def test_find_first_non_overlapping_candidate(self):
3194
3195 p = Beeswarm()
3196 candidates = [(.5, 1, .5), (1, 1, .5), (1.5, 1, .5)]
3197 neighbors = np.array([(0, 1, .5)])
3198
3199 first = p.first_non_overlapping_candidate(candidates, neighbors)
3200 assert_array_equal(first, (1, 1, .5))
3201
3202 def test_beeswarm(self, long_df):
3203
3204 p = Beeswarm()
3205 data = long_df["y"]
3206 d = data.diff().mean() * 1.5
3207 x = np.zeros(data.size)
3208 y = np.sort(data)
3209 r = np.full_like(y, d)
3210 orig_xyr = np.c_[x, y, r]
3211 swarm = p.beeswarm(orig_xyr)[:, :2]
3212 dmat = np.sqrt(np.sum(np.square(swarm[:, np.newaxis] - swarm), axis=-1))
3213 triu = dmat[np.triu_indices_from(dmat, 1)]
3214 assert_array_less(d, triu)
3215 assert_array_equal(y, swarm[:, 1])
3216
3217 def test_add_gutters(self):
3218
3219 p = Beeswarm(width=1)
3220
3221 points = np.zeros(10)
3222 t_fwd = t_inv = lambda x: x
3223 assert_array_equal(points, p.add_gutters(points, 0, t_fwd, t_inv))
3224
3225 points = np.array([0, -1, .4, .8])
3226 msg = r"50.0% of the points cannot be placed.+$"
3227 with pytest.warns(UserWarning, match=msg):
3228 new_points = p.add_gutters(points, 0, t_fwd, t_inv)
3229 assert_array_equal(new_points, np.array([0, -.5, .4, .5]))
3230
3231
3232 class TestBoxPlotContainer:
3233
3234 @pytest.fixture
3235 def container(self, wide_array):
3236
3237 ax = mpl.figure.Figure().subplots()
3238 artist_dict = ax.boxplot(wide_array)
3239 return BoxPlotContainer(artist_dict)
3240
3241 def test_repr(self, container, wide_array):
3242
3243 n = wide_array.shape[1]
3244 assert str(container) == f"<BoxPlotContainer object with {n} boxes>"
3245
3246 def test_iteration(self, container):
3247 for artist_tuple in container:
3248 for attr in ["box", "median", "whiskers", "caps", "fliers", "mean"]:
3249 assert hasattr(artist_tuple, attr)
3250
3251 def test_label(self, container):
3252
3253 label = "a box plot"
3254 container.set_label(label)
3255 assert container.get_label() == label
3256
3257 def test_children(self, container):
3258
3259 children = container.get_children()
3260 for child in children:
3261 assert isinstance(child, mpl.artist.Artist)