Plotting Fundamentals
Matplotlib's `pyplot` API provides MATLAB-like plotting with full customization control.
Create everything from simple lines to complex multi-subplot dashboards.
| Function |
Creates |
Use Case |
plt.plot() |
Line plots |
Trends over time |
plt.scatter() |
Scatter plots |
Correlations |
plt.bar() |
Bar charts |
Categorical data |
plt.hist() |
Histograms |
Distributions |
plt.subplot() |
Multi-plots |
Dashboards |
Hello Matplotlib World
๐ python matplotlib_intro.py
๐ Line Plot: [1,2,3] โ Rising Trend
import matplotlib.pyplot as plt
# Basic line plot
plt.plot([1, 2, 3], [1, 4, 9])
plt.title('y = xยฒ')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.grid(True, alpha=0.3)
plt.show()
# Quick plot
plt.plot([1,2,3]); plt.show()
Essential Plot Types
Line Plots
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend()
plt.show()
Scatter Plots
plt.scatter(df['age'], df['salary'],
c=df['department'], s=100, alpha=0.7)
plt.colorbar()
plt.show()
Bar Charts
cities = ['London', 'Paris', 'Berlin']
sales = [55000, 62000, 48000]
plt.bar(cities, sales, color=['#EC4899', '#8B5CF6', '#06B6D4'])
plt.show()
Histograms
data = np.random.randn(1000)
plt.hist(data, bins=30, alpha=0.7, edgecolor='white')
plt.title('Normal Distribution')
plt.show()
Professional Styling
Publication Quality
Custom colors โข Grid โข Legends โข Annotations
# Professional styling
plt.style.use('seaborn-v0_8-darkgrid') # Modern theme
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 12
# Custom colors and styles
colors = ['#EC4899', '#8B5CF6', '#06B6D4', '#10B981']
plt.plot(x, y1, color=colors[0], linewidth=3, marker='o', markersize=6)
plt.plot(x, y2, color=colors[1], linewidth=2, linestyle='--')
# Annotations
plt.annotate('Peak Value', xy=(5, 10), xytext=(7, 12),
arrowprops=dict(arrowstyle='->', color='white'))
plt.tight_layout()
plt.savefig('professional_plot.png', dpi=300, bbox_inches='tight')
Subplots & Multi-Plot Layouts
# 2x2 subplot grid
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
axes[0,0].plot(x, np.sin(x)); axes[0,0].set_title('Sine')
axes[0,1].scatter(x, np.cos(x)); axes[0,1].set_title('Cosine Scatter')
axes[1,0].hist(np.random.randn(1000)); axes[1,0].set_title('Histogram')
axes[1,1].bar(categories, values); axes[1,1].set_title('Categories')
plt.tight_layout()
plt.show()
# Pandas integration
df.plot(kind='line', subplots=True, layout=(2,2), figsize=(12,8))
plt.show()
Advanced Visualizations
# Heatmaps
plt.imshow(matrix, cmap='viridis', aspect='auto')
plt.colorbar()
# Contour plots
plt.contourf(X, Y, Z, levels=20, cmap='plasma')
plt.contour(X, Y, Z, levels=10, colors='white', alpha=0.5)
# 3D plots
from mpl_toolkits.mplot3d import Axes3D
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
# Animations
from matplotlib.animation import FuncAnimation
def animate(i): line.set_data(x[:i], y[:i])
anim = FuncAnimation(fig, animate, frames=len(x))
Pandas + Matplotlib
# Direct plotting from DataFrames
df['sales'].plot(kind='line', title='Sales Trend')
df.plot(x='date', y='sales', kind='scatter')
df.groupby('city')['sales'].sum().plot(kind='bar')
# Advanced: Seaborn-style
import seaborn as sns
sns.lineplot(data=df, x='date', y='sales', hue='city')
# Export for web/reports
fig = plt.gcf()
fig.savefig('dashboard.png', dpi=300, bbox_inches='tight')
fig.savefig('dashboard.pdf')
Interactive & Production
# Interactive backend
%matplotlib widget # Jupyter
plt.ion() # Interactive mode
# Plotly conversion (interactive web)
import plotly.express as px
fig = px.line(df, x='date', y='sales', color='city')
fig.show()
# Dashboards
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# HTML export
fig.write_html('interactive_dashboard.html')
Production Projects
1. Executive Dashboard
KPIs, trends, forecasts - 50+ charts automated daily
2. Research Publications
Publication-quality figures for Nature/Science papers
3. Real-time Monitoring
Live streaming data visualization (IoT/sensors)
4. Interactive Web Reports
Plotly Dash + Matplotlib โ client-facing analytics
Visualization Expert!
๐จ Production Visualizations:
๐ Executive Dashboards
Real-time KPIs & metrics
๐ฌ Scientific Publications
Journal-quality figures
๐ Financial Reports
Interactive web charts
๐งช ML Model Evaluation
ROC curves, confusion matrices
๐ Web-Ready Exports
PNG/SVG/PDF/HTML
Turn data into stunning, publication-ready visualizations! ๐