Session 13 of 15

Data Visualization

Matplotlib and seaborn charts you can run from a .py file

Sign in to save your place.

Pick the chart that matches the question

A chart is a sentence about data. Compare categories with a bar chart. Show change over time with a line. Show how two numbers move together with a scatter plot. Show one distribution with a histogram. Show how several numeric columns rise and fall together with a heatmap.

Revenue by month

Matplotlib from a script

Install into the project environment from session 1: uv add matplotlib pandas. plt.show() opens a window. fig.savefig writes a file you can commit or drop into a report. layout="constrained" keeps labels inside the figure.

from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd

sales = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr"],
    "revenue": [120, 150, 130, 180],
})

fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
ax.bar(sales["month"], sales["revenue"], color="#db2777")
ax.set_title("Monthly revenue")
ax.set_ylabel("Revenue")
out = Path("revenue.png")
fig.savefig(out, dpi=120)
print(f"Wrote {out.resolve()}")

Notebook cells are optional

The same lines run in a .py file. A notebook is only a different editor. Do not look for a session-13 .ipynb on this site. The example is the page.

Seaborn on the same data

Seaborn 0.13 draws statistical charts from a DataFrame. Pass data=, then column names. sns.distplot was removed. Use sns.histplot for one distribution and sns.heatmap for a grid of numbers.

import seaborn as sns

fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
sns.barplot(data=sales, x="month", y="revenue", ax=ax, color="#db2777")
ax.set_title("Same bars, seaborn API")

scores = pd.DataFrame(
    [[1.0, 0.4, -0.2], [0.4, 1.0, 0.7], [-0.2, 0.7, 1.0]],
    index=["hours", "score", "sleep"],
    columns=["hours", "score", "sleep"],
)
fig, ax = plt.subplots(figsize=(5, 4), layout="constrained")
sns.heatmap(scores, annot=True, cmap="magma", ax=ax, vmin=-1, vmax=1)
ax.set_title("How the columns move together")

A heatmap of correlations is a map of relationships, not a proof that one column causes another. Read the numbers, then go back to the table.

Knowledge check

You have revenue for four product names and no time column. Which chart should you start with?