Charts with matplotlib
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
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()
figis the whole image;axis one chart inside it. Calling methods onaxis the recommended style.- Always add a title and axis labels — a chart without them is a guessing game.
marker="o"shows each data point;alphacontrols transparency.
Bar charts
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 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
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()
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
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.
['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] [120, 95, 140, 80, 160] Fri