Learn / Python for AI / Lesson 3

Charts with matplotlib

11 min Tested on Python 3.15Updated By
In short

matplotlib is Python's standard plotting library. Create a figure and axes with fig, ax = plt.subplots(), draw with ax.plot(), ax.bar() or ax.scatter(), label everything, then plt.show() or fig.savefig("chart.png"). pandas and most AI libraries use it for their built-in charts.

A line chart

Python
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
users = [120, 180, 260, 310, 420, 560]

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(months, users, marker="o", color="#3776ab", linewidth=2)
ax.set_title("Monthly active users")
ax.set_xlabel("Month")
ax.set_ylabel("Users")
ax.grid(alpha=0.3)
plt.show()
Line chart of monthly active users rising from 120 in January to 560 in June
Press Run above to draw it yourself, then change the numbers or the colour.
  • fig is the whole image; ax is one chart inside it. Calling methods on ax is the recommended style.
  • Always add a title and axis labels — a chart without them is a guessing game.
  • marker="o" shows each data point; alpha controls transparency.

Bar charts

Python
import matplotlib.pyplot as plt

languages = ["Python", "JavaScript", "SQL", "Java", "Go"]
share = [51, 42, 38, 30, 14]

fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.barh(languages, share, color="#3776ab")
ax.bar_label(bars, fmt="%d%%", padding=3)
ax.invert_yaxis()
ax.set_title("Languages used by a sample team (%)")
ax.set_xlim(0, 60)
plt.show()
Horizontal bar chart with Python at the top at 51 percent

Horizontal bars (barh) keep long category names readable. bar_label writes the values on the bars so readers don't have to estimate.

Scatter plots and several charts

Python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(7)
hours = rng.uniform(0, 10, 60)
score = 40 + 5 * hours + rng.normal(0, 6, 60)

fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.6))
left.scatter(hours, score, alpha=0.7, color="#3776ab")
left.set_title("Study hours vs exam score")
left.set_xlabel("Hours")
left.set_ylabel("Score")

right.hist(score, bins=10, color="#ffd43b", edgecolor="#333")
right.set_title("Score distribution")
fig.tight_layout()
plt.show()
Scatter plot showing scores rising with study hours, next to a histogram of scores

Before training any model, plot the data: a scatter plot shows whether two values move together, and a histogram shows how values are spread and whether there are outliers.

Plotting from pandas and saving

Python · run on your computer
import pandas as pd

df = pd.DataFrame({"month": ["Jan", "Feb", "Mar"], "eu": [120, 150, 170], "india": [90, 160, 240]})
ax = df.plot(x="month", kind="bar", title="Revenue by region")
ax.figure.savefig("revenue.png", dpi=150, bbox_inches="tight")

Practice

Prepare data for a chart. From sales = {"Mon": 120, "Tue": 95, "Wed": 140, "Thu": 80, "Fri": 160}, print the list of days and the list of values (the two inputs for ax.bar), then the day with the highest sales. Bonus: plot it with ax.bar(days, values) and press Run.

Expected output:
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
[120, 95, 140, 80, 160]
Fri
Your code

Quick check

1. What does fig, ax = plt.subplots() give you?

2. Which chart shows whether two numeric values move together?

3. Why add bbox_inches="tight" to savefig?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →