🎨 Seaborn
Seaborn یک کتابخانه مصورسازی داده بر پایه Matplotlib است که با ارائه تمهای زیبا، پالتهای رنگی پیشرفته و توابع سطح بالا، کار با دادههای آماری را بسیار آسان میکند. Seaborn برای تحلیل اکتشافی داده و ارائه گزارشهای حرفهای طراحی شده است.
پیشنیاز: آشنایی با Pandas و Matplotlib (سطح Intermediate).
🔹 نصب و تنظیمات
# نصب (در محیط واقعی)
# pip install seaborn
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# بررسی نسخه
print(f"Seaborn version: {sns.__version__}")
# تنظیم استایل
sns.set_theme(style="whitegrid", palette="muted")
print("Seaborn configured successfully!")
🔹 استایلها و تمها
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# ایجاد داده نمونه
x = np.linspace(0, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.1, 100)
# تنظیم تمهای مختلف
styles = ["whitegrid", "darkgrid", "white", "dark", "ticks"]
for i, style in enumerate(styles):
sns.set_style(style)
plt.figure(figsize=(6, 3))
plt.plot(x, y)
plt.title(f"Style: {style}")
plt.tight_layout()
plt.show()
# بازگشت به تم پیشفرض
sns.set_style("whitegrid")
# تنظیم پالت رنگی
sns.set_palette("viridis")
print("Palette set to viridis")
🔹 توزیع دادهها
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# دادههای تصادفی
np.random.seed(42)
data = pd.DataFrame({
'normal': np.random.normal(0, 1, 1000),
'uniform': np.random.uniform(-3, 3, 1000),
'exponential': np.random.exponential(1, 1000)
})
# histplot: هیستوگرام با KDE
plt.figure(figsize=(12, 4))
plt.subplot(1, 3, 1)
sns.histplot(data['normal'], kde=True, bins=30)
plt.title("Normal Distribution")
plt.subplot(1, 3, 2)
sns.histplot(data['uniform'], kde=True, bins=30)
plt.title("Uniform Distribution")
plt.subplot(1, 3, 3)
sns.histplot(data['exponential'], kde=True, bins=30)
plt.title("Exponential Distribution")
plt.tight_layout()
plt.show()
# kdeplot: فقط توزیع
plt.figure(figsize=(10, 6))
sns.kdeplot(data['normal'], label='Normal')
sns.kdeplot(data['uniform'], label='Uniform')
sns.kdeplot(data['exponential'], label='Exponential')
plt.legend()
plt.title("KDE Plots")
plt.show()
🔹 نمودارهای پراکندگی
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# دادههای نمونه با دستهبندی
np.random.seed(42)
n = 200
df = pd.DataFrame({
'x': np.random.randn(n),
'y': np.random.randn(n),
'category': np.random.choice(['A', 'B', 'C'], n),
'size': np.random.rand(n) * 100,
'hue': np.random.randn(n)
})
# scatterplot ساده
plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x='x', y='y', hue='category', style='category', s=100)
plt.title("Scatterplot with Categories")
plt.show()
# scatterplot با اندازه متغیر
plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x='x', y='y', hue='hue', size='size', sizes=(20, 200))
plt.title("Scatterplot with Size and Color")
plt.show()
# jointplot: ترکیب پراکندگی و توزیع
sns.jointplot(data=df, x='x', y='y', kind='scatter')
plt.show()
# jointplot با reg (رگرسیون)
sns.jointplot(data=df, x='x', y='y', kind='reg')
plt.show()
🔹 نمودارهای میلهای
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# دادههای نمونه (از دیتاستهای داخلی Seaborn)
tips = sns.load_dataset('tips')
print("Tips dataset:")
print(tips.head())
# barplot: میانگین با فاصله اطمینان
plt.figure(figsize=(10, 6))
sns.barplot(data=tips, x='day', y='total_bill', hue='sex')
plt.title("Average Total Bill by Day and Sex")
plt.show()
# countplot: تعداد مشاهدات
plt.figure(figsize=(8, 5))
sns.countplot(data=tips, x='day', hue='sex')
plt.title("Number of Observations by Day and Sex")
plt.show()
# barplot با خطا (errorbar)
plt.figure(figsize=(8, 5))
sns.barplot(data=tips, x='day', y='total_bill', errorbar='sd')
plt.title("Average Total Bill with Standard Deviation")
plt.show()
🔹 نمودارهای جعبهای و ویولن
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# boxplot: نمودار جعبهای
plt.figure(figsize=(10, 6))
sns.boxplot(data=tips, x='day', y='total_bill', hue='sex')
plt.title("Boxplot of Total Bill by Day and Sex")
plt.show()
# violinplot: نمودار ویولن (ترکیب boxplot و KDE)
plt.figure(figsize=(10, 6))
sns.violinplot(data=tips, x='day', y='total_bill', hue='sex', split=True)
plt.title("Violinplot of Total Bill by Day and Sex")
plt.show()
# boxplot با swarmplot (نمایش نقاط)
plt.figure(figsize=(10, 6))
sns.boxplot(data=tips, x='day', y='total_bill')
sns.swarmplot(data=tips, x='day', y='total_bill', color='black', alpha=0.5)
plt.title("Boxplot with Swarm Overlay")
plt.show()
🔹 نمودارهای رگرسیون
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# regplot: نمودار رگرسیون
plt.figure(figsize=(8, 6))
sns.regplot(data=tips, x='total_bill', y='tip')
plt.title("Regression Plot: Total Bill vs Tip")
plt.show()
# regplot با دستهبندی
plt.figure(figsize=(10, 6))
sns.lmplot(data=tips, x='total_bill', y='tip', hue='sex', col='day')
plt.suptitle("Regression by Sex and Day")
plt.tight_layout()
plt.show()
# regplot با درجه چندجملهای
plt.figure(figsize=(8, 6))
sns.regplot(data=tips, x='total_bill', y='tip', order=2)
plt.title("Polynomial Regression (degree=2)")
plt.show()
# residplot: نمودار باقیماندهها
plt.figure(figsize=(8, 6))
sns.residplot(data=tips, x='total_bill', y='tip')
plt.title("Residual Plot")
plt.show()
🔹 نمودارهای حرارتی
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# دادههای نمونه
flights = sns.load_dataset('flights')
print("Flights dataset:")
print(flights.head())
# تبدیل به جدول محوری
flights_pivot = flights.pivot(index='month', columns='year', values='passengers')
print("\nPivot table:")
print(flights_pivot.head())
# heatmap
plt.figure(figsize=(12, 8))
sns.heatmap(flights_pivot, annot=True, fmt='d', cmap='YlOrRd')
plt.title("Heatmap of Flight Passengers")
plt.show()
# heatmap با تنظیمات پیشرفته
plt.figure(figsize=(10, 8))
sns.heatmap(flights_pivot, annot=True, fmt='d', cmap='coolwarm',
linewidths=0.5, cbar_kws={'label': 'Passengers'})
plt.title("Advanced Heatmap")
plt.show()
# heatmap همبستگی
tips = sns.load_dataset('tips')
correlation = tips.select_dtypes(include=[np.number]).corr()
plt.figure(figsize=(8, 6))
sns.heatmap(correlation, annot=True, cmap='RdBu_r', center=0)
plt.title("Correlation Heatmap")
plt.show()
🔹 پالتهای رنگی
import seaborn as sns
import matplotlib.pyplot as plt
# نمایش پالتهای مختلف
palettes = ['viridis', 'magma', 'coolwarm', 'RdBu', 'Set2', 'husl']
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
for ax, palette in zip(axes.flat, palettes):
sns.color_palette(palette)
sns.barplot(x=list(range(10)), y=list(range(10)), palette=palette, ax=ax)
ax.set_title(f"Palette: {palette}")
plt.tight_layout()
plt.show()
# پالتهای مختلف در یک plot
tips = sns.load_dataset('tips')
plt.figure(figsize=(12, 6))
sns.barplot(data=tips, x='day', y='total_bill', hue='sex',
palette={'Male': 'blue', 'Female': 'pink'})
plt.title("Custom Palette")
plt.show()
# color_palette برای ایجاد پالت سفارشی
custom_palette = sns.color_palette("husl", 5)
print(f"Custom palette: {custom_palette}")
🔹 دیتاستهای داخلی Seaborn
import seaborn as sns
import matplotlib.pyplot as plt
# لیست دیتاستهای موجود
print("Available datasets:", sns.get_dataset_names())
# بارگذاری دیتاستهای مختلف
tips = sns.load_dataset('tips')
iris = sns.load_dataset('iris')
titanic = sns.load_dataset('titanic')
penguins = sns.load_dataset('penguins')
# نمایش چند نمونه
print("\nPenguins dataset:")
print(penguins.head())
# نمودارهای مختلف برای دیتاستهای مختلف
plt.figure(figsize=(15, 5))
# Iris: scatterplot
plt.subplot(1, 3, 1)
sns.scatterplot(data=iris, x='sepal_length', y='sepal_width', hue='species')
plt.title("Iris Dataset")
# Penguins: boxplot
plt.subplot(1, 3, 2)
sns.boxplot(data=penguins, x='species', y='body_mass_g')
plt.title("Penguins Body Mass")
# Titanic: countplot
plt.subplot(1, 3, 3)
sns.countplot(data=titanic, x='class', hue='survived')
plt.title("Titanic Survival by Class")
plt.tight_layout()
plt.show()
🔹 تنظیمات پیشرفته
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
tips = sns.load_dataset('tips')
# تنظیم اندازه فونت
sns.set(font_scale=1.2)
sns.set_style("whitegrid")
sns.set_palette("Set2")
# plot با تنظیمات
plt.figure(figsize=(10, 6))
sns.boxplot(data=tips, x='day', y='total_bill', hue='sex')
plt.title("Customized Boxplot", fontsize=16, fontweight='bold')
plt.xlabel("Day of Week", fontsize=12)
plt.ylabel("Total Bill ($)", fontsize=12)
plt.legend(title='Sex', loc='upper right')
plt.show()
# بازنشانی تنظیمات
sns.set_theme()
sns.set(font_scale=1)
print("Settings reset to default")
# استفاده از context (برای تنظیم اندازهها)
with sns.plotting_context("notebook", font_scale=1.2):
plt.figure(figsize=(8, 5))
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='day')
plt.title("Plotting Context Example")
plt.tight_layout()
plt.show()
🔹 مثال جامع: تحلیل داده فروش
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# ایجاد داده فروش
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=100)
products = ['Product A', 'Product B', 'Product C', 'Product D']
data = pd.DataFrame({
'date': np.random.choice(dates, 500),
'product': np.random.choice(products, 500),
'sales': np.random.randint(100, 500, 500),
'quantity': np.random.randint(1, 20, 500),
'region': np.random.choice(['North', 'South', 'East', 'West'], 500)
})
print("Sales Data:")
print(data.head())
# ۱. توزیع فروش
plt.figure(figsize=(12, 6))
sns.histplot(data['sales'], kde=True, bins=30)
plt.title("Distribution of Sales")
plt.show()
# ۲. فروش بر اساس محصول و منطقه
plt.figure(figsize=(12, 6))
sns.boxplot(data=data, x='product', y='sales', hue='region')
plt.title("Sales by Product and Region")
plt.show()
# ۳. scatterplot فروش و تعداد با رنگبندی
plt.figure(figsize=(10, 6))
sns.scatterplot(data=data, x='quantity', y='sales', hue='product', size='region', sizes=(50, 200))
plt.title("Sales vs Quantity by Product and Region")
plt.show()
# ۴. heatmap همبستگی
correlation = data[['sales', 'quantity']].corr()
plt.figure(figsize=(6, 4))
sns.heatmap(correlation, annot=True, cmap='coolwarm', center=0)
plt.title("Correlation Matrix")
plt.show()
# ۵. pairplot برای تحلیل رابطهها
plt.figure(figsize=(10, 8))
sns.pairplot(data[['sales', 'quantity']])
plt.suptitle("Pairplot of Sales and Quantity", y=1.02)
plt.show()
# ۶. jointplot با رگرسیون
sns.jointplot(data=data, x='quantity', y='sales', kind='reg')
plt.suptitle("Sales vs Quantity with Regression", y=1.02)
plt.show()
📌 نکات کلیدی
- ✅ Seaborn بر پایه Matplotlib ساخته شده و تمهای زیبا ارائه میدهد.
- ✅ با
sns.set_theme()میتوانید تنظیمات کلی را اعمال کنید. - ✅
histplot()وkdeplot()برای نمایش توزیع دادهها. - ✅
scatterplot()برای نمایش رابطه بین دو متغیر با دستهبندی. - ✅
barplot()وcountplot()برای دادههای دستهبندی. - ✅
boxplot()وviolinplot()برای نمایش پراکنش دادهها. - ✅
regplot()وlmplot()برای رگرسیون. - ✅
heatmap()برای نمایش ماتریس همبستگی و دادههای جدولی. - ✅
pairplot()برای نمایش روابط دوتایی بین متغیرها. - ✅ Seaborn با Pandas و NumPy به خوبی یکپارچه شده است.