🐍 کتابخانه مرجع پایتون

📊 Plotly

Plotly یک کتابخانه قدرتمند برای ایجاد نمودارهای تعاملی در پایتون است. برخلاف Matplotlib و Seaborn که نمودارهای استاتیک تولید می‌کنند، Plotly به شما امکان می‌دهد نمودارهای تعاملی با قابلیت بزرگ‌نمایی، پنهان‌سازی و نمایش اطلاعات ایجاد کنید. این کتابخانه برای داشبوردها، گزارش‌های تحت وب و تحلیل داده‌های تعاملی بسیار مناسب است.

پیش‌نیاز: آشنایی با Pandas و مفاهیم پایه مصورسازی داده.

🔹 نصب و import

# نصب (در محیط واقعی)
# pip install plotly

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# بررسی نسخه
print(f"Plotly version: {px.__version__}")

print("Plotly imported successfully!")

🔹 نمودارهای پراکندگی تعاملی

import plotly.express as px
import pandas as pd

# داده نمونه (مجموعه iris)
df = px.data.iris()
print("Iris dataset:")
print(df.head())

# scatterplot تعاملی
fig = px.scatter(
    df, 
    x='sepal_width', 
    y='sepal_length',
    color='species',
    size='petal_length',
    hover_data=['petal_width'],
    title="Interactive Scatter Plot - Iris Dataset"
)
fig.show()

# scatterplot با رنگ‌بندی پیوسته
fig = px.scatter(
    df,
    x='sepal_width',
    y='sepal_length',
    color='petal_length',
    size='petal_width',
    color_continuous_scale='Viridis',
    title="Scatter Plot with Continuous Color"
)
fig.show()

🔹 نمودارهای خطی تعاملی

import plotly.express as px
import pandas as pd
import numpy as np

# ایجاد داده زمانی
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=100)
df = pd.DataFrame({
    'date': dates,
    'value1': np.cumsum(np.random.randn(100)) + 10,
    'value2': np.cumsum(np.random.randn(100)) + 20,
    'value3': np.cumsum(np.random.randn(100)) + 30
})

# خطی تعاملی
fig = px.line(
    df,
    x='date',
    y=['value1', 'value2', 'value3'],
    title="Interactive Line Chart",
    labels={'value': 'Value', 'date': 'Date'}
)
fig.show()

# خطی با نقاط
fig = px.line(
    df,
    x='date',
    y='value1',
    markers=True,
    title="Line Chart with Markers"
)
fig.show()

🔹 نمودارهای میله‌ای تعاملی

import plotly.express as px
import pandas as pd

# داده نمونه
df = px.data.tips()
print("Tips dataset:")
print(df.head())

# barplot تعاملی
fig = px.bar(
    df,
    x='day',
    y='total_bill',
    color='sex',
    title="Average Total Bill by Day and Sex",
    barmode='group',
    labels={'total_bill': 'Total Bill ($)', 'day': 'Day'}
)
fig.show()

# barplot انباشته (stacked)
fig = px.bar(
    df,
    x='day',
    y='total_bill',
    color='sex',
    title="Stacked Bar Chart",
    barmode='stack'
)
fig.show()

# barplot با میانگین
df_agg = df.groupby(['day', 'sex'], as_index=False)['total_bill'].mean()
fig = px.bar(
    df_agg,
    x='day',
    y='total_bill',
    color='sex',
    title="Average Total Bill by Day and Sex",
    text_auto=True
)
fig.show()

🔹 هیستوگرام و توزیع

import plotly.express as px
import numpy as np

# داده‌های تصادفی
np.random.seed(42)
df = pd.DataFrame({
    'normal': np.random.normal(0, 1, 1000),
    'exponential': np.random.exponential(1, 1000),
    'uniform': np.random.uniform(-3, 3, 1000)
})

# هیستوگرام تعاملی
fig = px.histogram(
    df,
    x='normal',
    nbins=30,
    title="Histogram - Normal Distribution",
    labels={'normal': 'Value', 'count': 'Frequency'}
)
fig.show()

# هیستوگرام با KDE
fig = px.histogram(
    df,
    x='normal',
    nbins=30,
    marginal='violin',
    title="Histogram with Violin Plot"
)
fig.show()

# چند هیستوگرام با هم
fig = px.histogram(
    df,
    x='normal',
    color='normal',
    title="Multiple Histograms"
)
fig.show()

🔹 نمودارهای جعبه‌ای و ویولن

import plotly.express as px

tips = px.data.tips()

# boxplot تعاملی
fig = px.box(
    tips,
    x='day',
    y='total_bill',
    color='sex',
    title="Boxplot of Total Bill by Day and Sex",
    labels={'total_bill': 'Total Bill ($)'}
)
fig.show()

# violinplot تعاملی
fig = px.violin(
    tips,
    x='day',
    y='total_bill',
    color='sex',
    box=True,
    title="Violinplot of Total Bill by Day and Sex"
)
fig.show()

# boxplot با points
fig = px.box(
    tips,
    x='day',
    y='total_bill',
    color='sex',
    points='all',
    title="Boxplot with All Points"
)
fig.show()

🔹 نمودارهای حرارتی تعاملی

import plotly.express as px
import plotly.graph_objects as go
import numpy as np

# داده نمونه
df = px.data.iris()
correlation = df.select_dtypes(include=[np.number]).corr()

# heatmap با plotly express
fig = px.imshow(
    correlation,
    text_auto=True,
    color_continuous_scale='RdBu_r',
    title="Correlation Heatmap"
)
fig.show()

# heatmap با go (graph_objects)
fig = go.Figure(data=go.Heatmap(
    z=correlation.values,
    x=correlation.columns,
    y=correlation.columns,
    colorscale='Viridis',
    hoverongaps=False
))
fig.update_layout(title="Heatmap with Graph Objects")
fig.show()

# heatmap از جدول محوری
flights = px.data.flights()
flights_pivot = flights.pivot(index='month', columns='year', values='passengers')

fig = px.imshow(
    flights_pivot,
    text_auto=True,
    color_continuous_scale='YlOrRd',
    title="Flight Passengers Heatmap"
)
fig.show()

🔹 نمودارهای سه‌بعدی

import plotly.express as px
import numpy as np

# داده نمونه
df = px.data.iris()

# scatter3d تعاملی
fig = px.scatter_3d(
    df,
    x='sepal_length',
    y='sepal_width',
    z='petal_length',
    color='species',
    size='petal_width',
    title="3D Scatter Plot - Iris Dataset"
)
fig.show()

# داده‌های تصادفی سه‌بعدی
np.random.seed(42)
n = 100
df_3d = pd.DataFrame({
    'x': np.random.randn(n),
    'y': np.random.randn(n),
    'z': np.random.randn(n),
    'color': np.random.choice(['A', 'B', 'C'], n)
})

fig = px.scatter_3d(
    df_3d,
    x='x',
    y='y',
    z='z',
    color='color',
    title="Random 3D Scatter Plot"
)
fig.show()

🔹 نقشه‌های تعاملی

import plotly.express as px

# داده نمونه (شهرهای آمریکا)
df = px.data.usa_cities()
print("USA Cities:")
print(df.head())

# نقشه تعاملی
fig = px.scatter_mapbox(
    df,
    lat='lat',
    lon='lon',
    hover_name='City',
    hover_data=['State', 'Population'],
    color='Population',
    size='Population',
    color_continuous_scale=px.colors.sequential.Viridis,
    title="US Cities Map",
    mapbox_style='open-street-map',
    zoom=3,
    height=600
)
fig.show()

# نقشه با داده‌های کشورها
df_gap = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(
    df_gap,
    locations='iso_alpha',
    size='pop',
    hover_name='country',
    color='continent',
    title="World Population Map (2007)",
    projection='natural earth'
)
fig.show()

🔹 نمودارهای سفارشی با go

import plotly.graph_objects as go
import numpy as np

# داده‌های تصادفی
np.random.seed(42)
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# ایجاد شکل با go
fig = go.Figure()

# اضافه کردن trace‌ها
fig.add_trace(go.Scatter(
    x=x,
    y=y1,
    mode='lines+markers',
    name='sin(x)',
    line=dict(color='blue', width=3),
    marker=dict(size=6, color='red')
))

fig.add_trace(go.Scatter(
    x=x,
    y=y2,
    mode='lines',
    name='cos(x)',
    line=dict(color='green', width=2, dash='dash')
))

# تنظیم layout
fig.update_layout(
    title="Custom Plot with go",
    xaxis_title="X-axis",
    yaxis_title="Y-axis",
    template='plotly_dark',
    legend=dict(
        x=0.8,
        y=0.2,
        bgcolor='rgba(255,255,255,0.5)'
    )
)

fig.show()

# نمودار دایره‌ای با go
labels = ['A', 'B', 'C', 'D']
values = [15, 30, 45, 10]

fig = go.Figure(data=[go.Pie(
    labels=labels,
    values=values,
    hole=0.3,
    textinfo='label+percent',
    marker=dict(colors=['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'])
)])
fig.update_layout(title="Donut Chart with go")
fig.show()

🔹 ذخیره و به اشتراک‌گذاری

import plotly.express as px

tips = px.data.tips()

# ایجاد نمودار
fig = px.scatter(
    tips,
    x='total_bill',
    y='tip',
    color='day',
    title="Interactive Plot"
)

# ذخیره به صورت HTML (تعاملی)
fig.write_html("interactive_plot.html")
print("HTML file saved as interactive_plot.html")

# ذخیره به صورت تصویر (نیاز به kaleido)
# fig.write_image("plot.png")
# fig.write_image("plot.pdf")

# نمایش در Jupyter Notebook
# fig.show()

# به اشتراک‌گذاری با Chart Studio (آنلاین)
# import plotly.io as pio
# pio.renderers.default = 'browser'
# fig.show()

# ایجاد JSON
fig_json = fig.to_json()
print(f"Plot JSON: {fig_json[:200]}...")

🔹 مثال جامع: داشبورد فروش تعاملی

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# ایجاد داده فروش
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=90)
products = ['Product A', 'Product B', 'Product C', 'Product D']
regions = ['North', 'South', 'East', 'West']

data = pd.DataFrame({
    'date': np.random.choice(dates, 500),
    'product': np.random.choice(products, 500),
    'region': np.random.choice(regions, 500),
    'sales': np.random.randint(100, 500, 500),
    'quantity': np.random.randint(1, 20, 500),
    'customer': np.random.choice(['Customer 1', 'Customer 2', 'Customer 3'], 500)
})

print("Sales Data:")
print(data.head())

# ۱. فروش روزانه (خطی)
daily_sales = data.groupby('date')['sales'].sum().reset_index()
fig1 = px.line(
    daily_sales,
    x='date',
    y='sales',
    title="Daily Sales",
    labels={'date': 'Date', 'sales': 'Sales ($)'}
)
fig1.show()

# ۲. فروش بر اساس محصول (میله‌ای)
product_sales = data.groupby('product')['sales'].sum().reset_index()
fig2 = px.bar(
    product_sales,
    x='product',
    y='sales',
    color='product',
    title="Sales by Product",
    labels={'product': 'Product', 'sales': 'Sales ($)'}
)
fig2.show()

# ۳. فروش بر اساس منطقه و محصول (جعبه‌ای)
fig3 = px.box(
    data,
    x='region',
    y='sales',
    color='product',
    title="Sales Distribution by Region and Product"
)
fig3.show()

# ۴. scatterplot فروش و تعداد
fig4 = px.scatter(
    data,
    x='quantity',
    y='sales',
    color='region',
    size='sales',
    title="Sales vs Quantity by Region",
    labels={'quantity': 'Quantity', 'sales': 'Sales ($)'}
)
fig4.show()

# ۵. heatmap فروش (محصول × منطقه)
pivot_sales = data.pivot_table(
    values='sales',
    index='product',
    columns='region',
    aggfunc='sum'
)
fig5 = px.imshow(
    pivot_sales,
    text_auto=True,
    color_continuous_scale='YlOrRd',
    title="Sales Heatmap (Product × Region)"
)
fig5.show()

# ۶. فروش روزانه با رنگ‌بندی محصول (خطی با رنگ)
fig6 = px.line(
    data,
    x='date',
    y='sales',
    color='product',
    title="Daily Sales by Product",
    labels={'date': 'Date', 'sales': 'Sales ($)'}
)
fig6.show()

# ترکیب در یک داشبورد با subplots
from plotly.subplots import make_subplots

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=('Sales by Product', 'Sales by Region',
                    'Sales vs Quantity', 'Sales Distribution')
)

# اضافه کردن trace‌ها
fig.add_trace(
    go.Bar(x=product_sales['product'], y=product_sales['sales']),
    row=1, col=1
)

region_sales = data.groupby('region')['sales'].sum().reset_index()
fig.add_trace(
    go.Bar(x=region_sales['region'], y=region_sales['sales']),
    row=1, col=2
)

fig.add_trace(
    go.Scatter(x=data['quantity'], y=data['sales'], mode='markers'),
    row=2, col=1
)

fig.add_trace(
    go.Histogram(x=data['sales']),
    row=2, col=2
)

fig.update_layout(title="Sales Dashboard")
fig.show()

📌 نکات کلیدی

← قبلی: Seaborn → بعدی: Scikit-learn ↑ بازگشت به فهرست پیشرفته