Phone:+16179821253
Address: 315 W 3rd St, Boston, Massachusetts, 02127, USA
Email: sloanecarter773@gmail.com
Phone:+16179821253
Address: 315 W 3rd St, Boston, Massachusetts, 02127, USA
Email: sloanecarter773@gmail.com
Working Python code for violin plots in seaborn, matplotlib and plotly, updated for the seaborn 0.13 API.
The quickest way to make a violin plot in Python is seaborn.violinplot(): pass a DataFrame, a category column for x and a numeric column for y. For full low-level control, use matplotlib’s Axes.violinplot(). For an interactive chart with hover labels, use plotly.express.violin(). This guide shows all three with code that runs on current versions.
Need a single chart and no script? Our free violin plot maker turns pasted numbers into a downloadable chart in the browser.
| Library | Best for | Input | Output |
|---|---|---|---|
| seaborn | Fast, good-looking statistical charts | Tidy DataFrame | Static image (matplotlib) |
| matplotlib | Full control, no extra dependency | List of arrays | Static image |
| plotly express | Dashboards, notebooks, hover details | Tidy DataFrame | Interactive HTML |
seaborn 0.13 rewrote its categorical plots and renamed several violin arguments. Many older tutorials use names that now raise deprecation warnings. The examples here use the 0.13 names.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
ax = sns.violinplot(data=tips, x="day", y="total_bill")
plt.savefig("violin.png", dpi=150, bbox_inches="tight")
Each violin is a kernel density estimate of total_bill for one day, mirrored on both sides. By default seaborn draws a small boxplot inside. The guide on how to read a violin plot explains the shape if it is new to you.
hue adds a second grouping variable and dodges the violins side by side. With two hue levels, split=True draws one half of each violin per level, which saves space and makes the comparison direct. gap adds a little space between the halves.
sns.violinplot(data=tips, x="day", y="total_bill",
hue="sex", split=True, inner="quart", gap=0.1)
To colour each category differently without a second variable, set hue to the same column as x and turn off the legend:
sns.violinplot(data=tips, x="day", y="total_bill",
hue="day", palette="pastel", legend=False)
More on when the half-and-half layout helps is in our split violin plot guide.
"box" (default): a mini boxplot. Style it with inner_kws, for example inner_kws=dict(box_width=6, whis_width=1.5)."quart": dashed lines at the quartiles and median."stick": one line per observation."point": one dot per observation.None: an empty violin, useful when you overlay your own layer.In 0.13, scale became density_norm, with the same three choices:
"area" (default): every violin has the same area."count": width grows with the number of observations."width": every violin has the same maximum width.The old scale_hue became common_norm, which decides whether normalisation applies across all violins or within each hue group. The old bw was split into bw_method (the rule, "scott" by default) and bw_adjust (a multiplier).
bw_adjust below 1 shows more detail, above 1 smooths more. cut sets how far the density extends past the extreme data points, in bandwidth units. The default is 2. Use cut=0 to stop each violin at its observed minimum and maximum, which avoids drawing impossible values such as negative bills.
sns.violinplot(data=tips, x="day", y="total_bill",
inner="stick", density_norm="count",
bw_adjust=0.5, cut=0)
Bandwidth choice can hide or invent peaks. See the violin plot bandwidth guide for side-by-side examples.
seaborn usually infers orientation from which variable is numeric. To be explicit, put the numbers on x and pass orient="y". The older "h" and "v" values are still accepted.
sns.violinplot(data=tips, x="total_bill", y="day", orient="y")
ax = sns.violinplot(data=tips, x="day", y="total_bill",
inner=None, color="0.85")
sns.stripplot(data=tips, x="day", y="total_bill",
size=3, jitter=0.15, ax=ax)
Swap stripplot for swarmplot to avoid overlap in small datasets. Our page on the violin plot with points covers when this matters most.
matplotlib works with a list of arrays instead of a DataFrame. Positions start at 1 by default. Remove missing values first, because NaN values break the density estimate.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
groups = [rng.normal(0, 1, 200),
rng.normal(1, 1.5, 200),
rng.exponential(1, 200)]
fig, ax = plt.subplots()
parts = ax.violinplot(groups, showmeans=False, showmedians=True,
quantiles=[[0.25, 0.75]] * 3)
ax.set_xticks([1, 2, 3], labels=["Control", "Treatment A", "Treatment B"])
for body in parts["bodies"]:
body.set_alpha(0.6)
fig.savefig("mpl_violin.png", dpi=150)
The main options:
showmeans, showmedians: draw a line at the mean or median. Both are off by default.showextrema: the min and max bars, on by default.quantiles: one list of quantiles per dataset, as in [[0.25, 0.75]] * 3 above.bw_method: "scott", "silverman", a number, or a function.widths, positions, points (how many points the density is evaluated at).The call returns a dictionary of artists, such as "bodies", "cmedians" and "cquantiles", which you can restyle one by one. For horizontal violins, recent matplotlib versions use orientation="horizontal". The older vert=False still works on many installs but is being phased out.
plotly draws interactive violins. Hovering shows summary values, and you can zoom or toggle groups in the legend.
import plotly.express as px
df = px.data.tips()
fig = px.violin(df, x="day", y="total_bill", box=True, points="all")
fig.write_html("violin.html")
fig.show()
box=True draws a boxplot inside each violin.points can be "all", "outliers", "suspectedoutliers" or False.color adds a second grouping, and violinmode="overlay" or "group" controls how those violins sit.hover_data adds columns to the hover label.For a split violin in plotly, draw each colour on one side:
fig = px.violin(df, x="day", y="total_bill", color="sex")
fig.update_traces(side="positive", selector=dict(name="Male"))
fig.update_traces(side="negative", selector=dict(name="Female"))
fig.update_layout(violinmode="overlay")
Saving a static PNG from plotly needs the separate kaleido package. HTML export works out of the box.
seaborn and plotly expect “long” data: one row per observation, one column for the group and one for the value. Spreadsheets often hold “wide” data instead, with one column per group. Convert it with pandas melt():
import pandas as pd
wide = pd.read_csv("results.csv") # columns: Control, Drug A, Drug B
long = wide.melt(var_name="group", value_name="value").dropna()
sns.violinplot(data=long, x="group", y="value", cut=0)
For matplotlib, go the other way and pass one array per column, for example [wide[c].dropna() for c in wide.columns].
order=["Thur", "Fri", "Sat", "Sun"] in seaborn, or category_orders={"day": [...]} in plotly.density_norm. With "count", small groups shrink on purpose.native_scale=True if you want violins placed at their real numeric positions.| Before 0.13 | 0.13 and later |
|---|---|
scale="count" | density_norm="count" |
scale_hue=False | common_norm=True |
bw=0.3 | bw_method=0.3 or bw_adjust |
orient="h" | orient="y" (old value still accepted) |
For the concepts behind the code, including when a violin beats a boxplot, read the violin plot guide. If a colleague needs the same chart without Python, they can make a violin plot online by pasting the column.
seaborn 0.13 renamed scale to density_norm. Change the argument name and the warning goes away.
In seaborn, set cut=0. matplotlib’s violins already stop at the data’s minimum and maximum.
Yes. Pass quantiles with one list per dataset, for example [[0.25, 0.75]] * 3 for three groups, and set showmedians=True.
plotly. px.violin() gives hover labels, zoom and legend toggles, and exports to HTML.
Transform complex datasets into clear, interactive visualizations with Violin Plot. Start exploring data distributions in a way that empowers insight and drives smarter decisions.



