범주형 그래프: boxplot, barplot, violinplot
상자 그림과 바이올린 그림으로 그룹별 분포를 비교하고 barplot으로 오차 막대와 함께 그룹 평균을 그립니다.
범주형 그래프: boxplot, barplot, violinplot은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Categorical Comparison Plots?
When you want to compare a numeric variable across different categories — for example, tips received by day of the week, or product prices by brand — you need specialised plots. Seaborn provides three essential categorical comparison plots: boxplot, barplot, and violinplot. Each one reveals different aspects of the distribution and is suited to different analytical goals.
import seaborn as sns
import matplotlib.pyplot as plt
# Load the tips dataset — a classic Seaborn example
tips = sns.load_dataset('tips')
print(tips.groupby('day')['total_bill'].describe())Box Plots with sns.boxplot
A box plot summarises a distribution using five statistics: the minimum, first quartile (Q1), median, third quartile (Q3), and maximum (excluding outliers). The box spans Q1 to Q3 (the Interquartile Range, IQR), the line inside the box is the median, and the whiskers extend to 1.5×IQR. Points beyond the whiskers are plotted individually as outliers. Box plots are excellent for spotting skewness and outliers at a glance.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
sns.boxplot(data=tips, x='day', y='total_bill', order=['Thur', 'Fri', 'Sat', 'Sun'])
plt.title('Total Bill Distribution by Day')
plt.xlabel('Day')
plt.ylabel('Total Bill ($)')
plt.show()Adding Hue to Box Plots
The hue parameter splits each category into sub-groups shown side by side with different colours. For example, adding hue='smoker' to a day-by-bill box plot shows two boxes per day — one for smokers and one for non-smokers. This makes three-variable comparisons clear without needing facets. Use a legend to keep the plot readable.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
sns.boxplot(
data=tips,
x='day',
y='total_bill',
hue='smoker',
order=['Thur', 'Fri', 'Sat', 'Sun'],
palette='Set2'
)
plt.title('Bill by Day and Smoker Status')
plt.legend(title='Smoker')
plt.show()Bar Plots with sns.barplot
sns.barplot() shows the mean of a numeric variable for each category, with error bars representing a 95% confidence interval by default (computed via bootstrapping in older Seaborn versions, or from the standard error in newer ones). Unlike histograms, bar plots summarise each group in a single value — they are best when you care about the average and its uncertainty, not the full distribution shape.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# Show mean tip per day with 95% CI
sns.barplot(
data=tips,
x='day',
y='tip',
order=['Thur', 'Fri', 'Sat', 'Sun'],
palette='Blues_d',
errorbar='ci'
)
plt.title('Average Tip by Day (with 95% CI)')
plt.ylabel('Average Tip ($)')
plt.show()Violin Plots with sns.violinplot
A violin plot combines a box plot with a KDE curve mirrored on both sides. The width of the violin at each y-value represents the density of data at that point — wide sections have many observations, narrow sections have few. Violin plots convey more information than box plots because they show whether the distribution is unimodal or multimodal, but they require more data to be meaningful (aim for n > 20 per group).
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
sns.violinplot(
data=tips,
x='day',
y='total_bill',
order=['Thur', 'Fri', 'Sat', 'Sun'],
palette='pastel',
inner='quartile' # show quartile lines inside the violin
)
plt.title('Bill Distribution by Day — Violin Plot')
plt.show()inner Parameter of violinplot
The inner parameter of violinplot controls what is drawn inside the violin shape. Options include 'box' (a mini box plot), 'quartile' (horizontal lines at Q1, median, Q3), 'point' (individual data points), and 'stick' (vertical tick marks per observation). Setting inner=None draws only the density envelope with no internal marks, giving the cleanest look for side-by-side comparisons.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.violinplot(data=tips, x='smoker', y='tip',
inner='box', ax=axes[0])
axes[0].set_title('inner="box"')
sns.violinplot(data=tips, x='smoker', y='tip',
inner='point', ax=axes[1])
axes[1].set_title('inner="point"')
plt.tight_layout()
plt.show()Combining Strip Plots with Box/Violin
Adding a sns.stripplot() on top of a box or violin plot shows every individual data point as a dot, preventing hiding of outliers and small sample sizes. Set jitter=True to spread points horizontally so they do not all stack on top of each other, and set alpha to make them semi-transparent when there are many points.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
ax = sns.boxplot(data=tips, x='day', y='tip',
order=['Thur', 'Fri', 'Sat', 'Sun'],
palette='Set3', width=0.5)
# Overlay individual points
sns.stripplot(data=tips, x='day', y='tip',
order=['Thur', 'Fri', 'Sat', 'Sun'],
color='black', alpha=0.3, jitter=True, size=3, ax=ax)
plt.title('Tip Distribution with Raw Points')
plt.show()Choosing Between boxplot, barplot, violinplot
Use a box plot when you need to see medians, IQR, and outliers and sample sizes are moderate. Use a bar plot when your audience cares about means and confidence intervals (common in reports and dashboards). Use a violin plot when you want to reveal the full distributional shape — especially multimodality. For small datasets (n < 30 per group), prefer box plots plus strip plots over violin plots because KDE curves become unreliable with few points.
catplot: The Figure-Level Interface
sns.catplot() is the figure-level wrapper for all categorical plots. Pass kind='box', 'bar', 'violin', 'strip', 'swarm', 'count', or 'point' to switch plot types. Its key advantage is the col and row parameters that create a grid of subplots automatically — for example, separate panels per gender or time of day without manually creating plt.subplots.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# Faceted box plots: separate panel per time of day
sns.catplot(
data=tips,
x='day',
y='total_bill',
col='time',
kind='box',
order=['Thur', 'Fri', 'Sat', 'Sun'],
height=5,
aspect=0.8
)
plt.suptitle('Bill by Day, Faceted by Time', y=1.02)
plt.show()Count Plots for Frequency Tables
sns.countplot() shows how many observations fall into each category — essentially a bar chart of counts. It is equivalent to calling value_counts() and then plotting. Use it to visualise class imbalance in datasets, frequency of categorical values, or the sample size per group before making any distributional comparison. Sort bars by frequency with order=df['col'].value_counts().index.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# Count by day, sorted by frequency
day_order = tips['day'].value_counts().index
sns.countplot(data=tips, x='day', order=day_order, palette='viridis')
plt.title('Number of Observations per Day')
plt.ylabel('Count')
plt.show()Point Plots for Effect Comparison
sns.pointplot() draws the mean for each category as a dot and connects them with a line, making it easy to see trends across ordered categories. Error bars show confidence intervals. This is particularly useful when the x-axis represents ordered groups (like age brackets or education levels) where you want to emphasise the direction and magnitude of change across groups, not just isolated means.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
sns.pointplot(
data=tips,
x='day',
y='tip',
hue='smoker',
order=['Thur', 'Fri', 'Sat', 'Sun'],
dodge=True,
capsize=0.1
)
plt.title('Mean Tip by Day and Smoker Status')
plt.show()Quick Check
Test your understanding of Seaborn categorical plots from this lesson.
Lesson Recap
In this lesson you learned: sns.boxplot summarises distributions with median, IQR, and outliers, sns.barplot shows group means with confidence interval error bars, and sns.violinplot reveals the full distribution shape including multimodality. Next up we explore scatter plots and pair plots for visualising relationships between numeric variables.
자주 묻는 질문
“범주형 그래프: boxplot, barplot, violinplot” 강의는 무료인가요?
네 — “범주형 그래프: boxplot, barplot, violinplot” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“범주형 그래프: boxplot, barplot, violinplot”에서 뭘 배우나요?
상자 그림과 바이올린 그림으로 그룹별 분포를 비교하고 barplot으로 오차 막대와 함께 그룹 평균을 그립니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“범주형 그래프: boxplot, barplot, violinplot” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 분포 그래프: histplot과 kdeplot
- 범주형 그래프: boxplot, barplot, violinplot
- 산점도와 쌍별 그래프
- 상관 행렬 히트맵