Seaborn with example

📊 Seaborn in Python (Complete Guide with Examples)

Seaborn is a statistical data visualization library built on top of Matplotlib. It provides high-level interface for creating attractive and informative charts.


✅ 1. Installation

pip install seaborn

✅ 2. Importing Seaborn

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

✅ 3. Load Example Dataset

Seaborn comes with built-in datasets:

# Load "tips" dataset
tips = sns.load_dataset("tips")
print(tips.head())

Output (example):

total_bill tip sex smoker day time size
16.99 1.01 Female No Sun Dinner 2
10.34 1.66 Male No Sun Dinner 3

✅ 4. Simple Scatter Plot

sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex")
plt.title("Total Bill vs Tip by Sex")
plt.show()
  • hue → color by category

  • data → dataset

  • x, y → columns


✅ 5. Line Plot

sns.lineplot(data=tips, x="size", y="tip", hue="sex")
plt.title("Tip vs Size by Sex")
plt.show()

✅ 6. Histogram / Distribution Plot

sns.histplot(tips['total_bill'], bins=10, kde=True)
plt.title("Histogram of Total Bill")
plt.show()
  • kde=True → plots Kernel Density Estimate (smooth curve)


✅ 7. Box Plot

Shows distribution and outliers.

sns.boxplot(data=tips, x="day", y="total_bill", hue="sex")
plt.title("Total Bill by Day and Sex")
plt.show()

✅ 8. Bar Plot

Displays aggregate statistics.

sns.barplot(data=tips, x="day", y="total_bill", hue="sex")
plt.title("Average Total Bill by Day and Sex")
plt.show()

✅ 9. Pair Plot

Visualizes relationships between all numerical columns.

sns.pairplot(tips, hue="sex")
plt.show()

✅ 10. Heatmap

Useful for correlation matrices.

corr = tips.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm")
plt.title("Correlation Heatmap")
plt.show()

🧠 Summary Table

Plot Type Function Notes
Scatter Plot scatterplot() Relationship between two variables
Line Plot lineplot() Trends over numeric x-axis
Histogram histplot() Distribution of numeric data
Box Plot boxplot() Distribution and outliers
Bar Plot barplot() Mean values for categories
Pair Plot pairplot() Scatter & distribution matrix
Heatmap heatmap() Correlation or 2D data matrix

🎯 Practical Example

# Load dataset
df = sns.load_dataset("iris")

# Pairplot to visualize relationships
sns.pairplot(df, hue="species")
plt.show()

# Boxplot for sepal_length by species
sns.boxplot(x="species", y="sepal_length", data=df)
plt.show()

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *