Lesson 11: Data Visualization with Matplotlib

Create plots and charts; visualize data distributions and relationships.

By • Last updated • 65 min

AI is visual. Whether it's diagnosing models or presenting data, we need charts. Matplotlib is the standard visualization library.

We typically import the pyplot module from Matplotlib as plt.

Line Plots and Scatter Plots

The most basic ways to visualize data are connecting points with lines or plotting individual dots.

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

plt.plot(x, y) # Line plot
# plt.scatter(x, y) # Scatter plot
plt.show() # Actually displays the graph

Interactive Matplotlib Chart Builder

Toggle configuration options, switch chart styles, and see the generated Python code.

Chart Type
Chart Options
Color Palette Picker
0.01.02.03.012345Model Training Loss CurveTraining EpochLoss (Mean Squared Error)Loss
Equivalent Python Code
import matplotlib.pyplot as plt

epochs = [1,2,3,4,5]
loss = [2.5,1.8,1.2,0.8,0.5]

plt.plot(epochs, loss, marker='o', color='indigo')
plt.title("Training Loss Curve")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.grid(True)
plt.legend(["Training Loss"])
plt.show()

Customizing Your Charts

A graph is useless without labels! You should always add titles and axis labels.

plt.title("Model Training Progress")
plt.xlabel("Epochs")
plt.ylabel("Loss")

Visualizing AI Concepts

In ML, we often plot distributions to understand our data, or loss curves to see how our model is learning.

  • plt.hist(data) - Histograms (for distribution)
  • plt.bar(labels, heights) - Bar charts (for categorical comparisons)

Coding Challenge: The Loss Curve

When an AI model trains, its "loss" (error) should go down over time. Let's visualize this!

  1. Create a list of epochs = [1, 2, 3, 4, 5].
  2. Create a list of loss_values = [2.5, 1.8, 1.2, 0.8, 0.5].
  3. Use plt.plot() to draw a line graph of epochs vs. loss values. Add a marker style like marker='o' to see the exact points.
  4. Add an X-label: "Epoch" and a Y-label: "Loss".
  5. Add a title: "Training Loss Curve".
  6. Call plt.show() to display it.
main.py
Run your code to see output here.