5 min read min read
Introduction to Seaborn
Learn to create beautiful charts with less code
Introduction to Seaborn
What is Seaborn?
Seaborn is built on top of matplotlib but:
- Easier to use
- Better looking by default
- Great for statistics
Install Seaborn
$ terminalBash
pip install seabornImport Convention
code.pyPython
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pdLine Plot
code.pyPython
import seaborn as sns
import matplotlib.pyplot as plt
data = {'Month': ['Jan', 'Feb', 'Mar', 'Apr'],
'Sales': [100, 120, 115, 140]}
df = pd.DataFrame(data)
sns.lineplot(data=df, x='Month', y='Sales')
plt.show()Bar Plot
code.pyPython
sns.barplot(data=df, x='Month', y='Sales')
plt.show()Scatter Plot
code.pyPython
df = pd.DataFrame({
'Age': [25, 30, 35, 40, 45],
'Salary': [40000, 50000, 60000, 70000, 80000]
})
sns.scatterplot(data=df, x='Age', y='Salary')
plt.show()Histogram
code.pyPython
sns.histplot(data=df, x='Salary')
plt.show()Box Plot
code.pyPython
df = pd.DataFrame({
'Department': ['Sales', 'Sales', 'IT', 'IT', 'HR', 'HR'],
'Salary': [50000, 55000, 70000, 75000, 45000, 48000]
})
sns.boxplot(data=df, x='Department', y='Salary')
plt.show()Why Seaborn is Easier
Matplotlib:
code.pyPython
fig, ax = plt.subplots()
for dept in df['Department'].unique():
dept_data = df[df['Department'] == dept]['Salary']
ax.boxplot(dept_data)
# ... lots more codeSeaborn:
code.pyPython
sns.boxplot(data=df, x='Department', y='Salary')One line!
Color by Category
code.pyPython
df = pd.DataFrame({
'Age': [25, 30, 35, 40, 45, 50],
'Salary': [40000, 50000, 60000, 70000, 80000, 90000],
'Gender': ['M', 'F', 'M', 'F', 'M', 'F']
})
sns.scatterplot(data=df, x='Age', y='Salary', hue='Gender')
plt.show()hue automatically colors by category!
Quick Summary
| Matplotlib | Seaborn |
|---|---|
| plt.plot() | sns.lineplot() |
| plt.bar() | sns.barplot() |
| plt.scatter() | sns.scatterplot() |
| plt.hist() | sns.histplot() |
| plt.boxplot() | sns.boxplot() |
Complete Example
code.pyPython
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Sample data
df = pd.DataFrame({
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'Sales': [100, 120, 115, 140, 160, 180],
'Region': ['East', 'West', 'East', 'West', 'East', 'West']
})
# Create nice chart
plt.figure(figsize=(10, 6))
sns.barplot(data=df, x='Month', y='Sales', hue='Region')
plt.title('Sales by Month and Region')
plt.show()Key Points
- import seaborn as sns is standard
- Works directly with pandas DataFrames
- Pass column names as strings
- Use hue to color by category
- Use plt.show() to display
- Much less code than matplotlib!
What's Next?
Learn Seaborn's statistical plots for deeper analysis.