Lesson 11: Data Visualization with Matplotlib
Create plots and charts; visualize data distributions and relationships.
By Bishwambhar Sen • 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 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.
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.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!
- Create a list of
epochs = [1, 2, 3, 4, 5]. - Create a list of
loss_values = [2.5, 1.8, 1.2, 0.8, 0.5]. - Use
plt.plot()to draw a line graph of epochs vs. loss values. Add a marker style likemarker='o'to see the exact points. - Add an X-label: "Epoch" and a Y-label: "Loss".
- Add a title: "Training Loss Curve".
- Call
plt.show()to display it.