How to Create Catplot with Seaborn in Python
Use
seaborn.catplot() to create categorical plots in Python. Provide your data and specify the kind of plot like 'strip', 'box', or 'bar' to visualize categories easily.Syntax
The basic syntax of seaborn.catplot() is:
data: Your dataset (usually a pandas DataFrame).x: The categorical variable on the x-axis.y: The numeric variable on the y-axis.kind: The type of categorical plot (e.g., 'strip', 'box', 'bar', 'violin').hue: (Optional) Variable for color grouping.heightandaspect: Control the size and shape of the plot.
python
seaborn.catplot(data=dataframe, x='category_column', y='numeric_column', kind='box', hue='group_column', height=5, aspect=1.5)
Example
This example shows how to create a box plot using catplot with the built-in tips dataset from Seaborn. It groups tips by day and shows the distribution of total bills.
python
import seaborn as sns import matplotlib.pyplot as plt # Load example dataset tips = sns.load_dataset('tips') # Create a box plot with catplot sns.catplot(data=tips, x='day', y='total_bill', kind='box', height=4, aspect=1.2) plt.show()
Output
A box plot window showing total bill distributions for each day (Thur, Fri, Sat, Sun).
Common Pitfalls
Common mistakes when using catplot include:
- Not importing
seabornormatplotlib.pyplotbefore plotting. - Passing incorrect column names that don't exist in the DataFrame.
- Forgetting to call
plt.show()in some environments to display the plot. - Using
kindvalues not supported bycatplot(only 'strip', 'swarm', 'box', 'violin', 'boxen', 'point', 'bar', 'count').
Example of a wrong and right way:
python
# Wrong: typo in column name sns.catplot(data=tips, x='day', y='totalbill', kind='box') # 'totalbill' should be 'total_bill' # Right: sns.catplot(data=tips, x='day', y='total_bill', kind='box')
Quick Reference
| Parameter | Description | Example Values |
|---|---|---|
| data | Dataset to plot | pandas DataFrame |
| x | Categorical variable for x-axis | 'day', 'time' |
| y | Numeric variable for y-axis | 'total_bill', 'tip' |
| kind | Type of categorical plot | 'strip', 'box', 'bar', 'violin' |
| hue | Variable for color grouping | 'sex', 'smoker' |
| height | Height of the plot in inches | 4, 5 |
| aspect | Aspect ratio (width/height) | 1, 1.5 |
Key Takeaways
Use seaborn.catplot() to create flexible categorical plots with simple syntax.
Always specify the kind of plot you want with the kind parameter.
Check your column names carefully to avoid errors.
Call plt.show() to display the plot in some environments.
Use the built-in datasets like tips to practice catplot easily.