Is there a matplotlib equivalent to `seaborn.violinplot` `hue`?
Oct 7, 10:26pm
Not directly — matplotlib.pyplot.violinplot has no hue parameter (that's a seaborn-level concept for splitting each category by a second variable). The equivalent is to draw one violin per hue level yourself, offsetting the positions within each category:
python
import numpy as np
import matplotlib.pyplot as plt
# data: dict of category -> (hue A values, hue B values)
fig, ax = plt.subplots()
offset = 0.2 # half-width of the dodge
for i, (cat, (vals_a, vals_b)) in enumerate(data.items()):
for j, vals in enumerate([vals_a, vals_b]):
pos = i + (j - 0.5) * 2 * offset
v = ax.violinplot(vals, positions=[pos], widths=0.35)
# optionally recolor each body
for body in v["bodies"]:
body.set_facecolor(f"C{j}")
ax.set_xticks(range(len(data)))
ax.set_xticklabels(data.keys())
What you're reimplementing from seaborn's hue:
Dodging: offset positions within each category (seaborn's dodge=True behavior).
Legend: add manually, e.g. ax.legend() with proxy artists (Patch(facecolor="C0"), Patch(facecolor="C1")).
Coloring: violinplot returns a dict of artists (bodies, cmins, cmaxes, etc.), so you set colors per collection yourself.
Notes:
ax.violinplot (the object-oriented Axes method, available since Matplotlib 3.x) accepts positions, widths, side (side="high"/"low" since 3.9, which mimics seaborn's split=True halves), vert, and showmeans/showmedians/showextrema.
Matplotlib violins always show both kernel halves; there's no split-style single-sided KDE without the side workaround.
If you want a true violinplot(dataset, x=..., hue=...) like seaborn's newer interface, Matplotlib doesn't have that API — the per-hue loop above is the standard equivalent.
Oct 7, 10:26pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.