Intermediate

Data Visualization

Create compelling visualizations with Matplotlib, Seaborn, and Plotly. Learn to choose the right chart type and customize plots for maximum impact.

Matplotlib Basics

Python
import matplotlib.pyplot as plt
import numpy as np

# Line plot
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.xlabel("x")
plt.ylabel("y")
plt.title("Trigonometric Functions")
plt.legend()
plt.show()

# Scatter plot
plt.scatter(df["age"], df["salary"], c="blue", alpha=0.6)
plt.xlabel("Age")
plt.ylabel("Salary")
plt.show()

# Bar chart
categories = ["A", "B", "C", "D"]
values = [23, 45, 12, 67]
plt.bar(categories, values, color="steelblue")
plt.show()

# Histogram
plt.hist(df["age"], bins=20, edgecolor="black")
plt.show()

# Subplots
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].plot(x, np.sin(x))
axes[0].set_title("Sine")
axes[1].plot(x, np.cos(x))
axes[1].set_title("Cosine")
plt.tight_layout()
plt.show()

Seaborn

Python
import seaborn as sns

sns.set_theme(style="whitegrid")

# Heatmap (correlation)
sns.heatmap(df.corr(), annot=True, cmap="coolwarm", fmt=".2f")

# Pair plot (all pairwise relationships)
sns.pairplot(df, hue="species")

# Box plot (distribution by category)
sns.boxplot(x="department", y="salary", data=df)

# Violin plot (distribution shape)
sns.violinplot(x="department", y="salary", data=df)

# Count plot
sns.countplot(x="department", data=df, order=df["department"].value_counts().index)

Plotly (Interactive Charts)

Python
import plotly.express as px

# Interactive scatter plot
fig = px.scatter(df, x="age", y="salary", color="department",
                 hover_data=["name"], title="Salary vs Age")
fig.show()

# Interactive bar chart
fig = px.bar(df.groupby("department")["salary"].mean().reset_index(),
             x="department", y="salary", color="department")
fig.show()

# Interactive line chart with animation
fig = px.line(df, x="date", y="revenue", color="product")
fig.show()

Choosing the Right Chart

GoalChart TypeLibrary
Trends over timeLine chartMatplotlib, Plotly
Comparing categoriesBar chartMatplotlib, Seaborn
DistributionHistogram, KDE, Box plotSeaborn
RelationshipsScatter plot, Pair plotSeaborn, Plotly
CompositionPie chart, Stacked barMatplotlib, Plotly
CorrelationHeatmapSeaborn
Interactive explorationAny chart typePlotly

Saving Plots

Python
# Matplotlib
plt.savefig("chart.png", dpi=300, bbox_inches="tight")
plt.savefig("chart.svg")  # Vector format

# Plotly
fig.write_html("chart.html")
fig.write_image("chart.png")
Visualization best practices: Always label axes. Use color meaningfully, not decoratively. Avoid 3D charts unless they add genuine value. Start bar charts at zero. Choose colorblind-friendly palettes.