AI Hints
Home›Python Tutorial›Data Science Toolkit
Python · Lesson 35 of 49

Charts with matplotlib

Turn numbers into pictures.

⏱ 2 min read▶ Video at 1:46:56🎓 Free
Watch this lesson in the Python courseWatch on YouTube ↗Full Python course

Numbers in a table are hard to feel. Ava's accountant wants to see the trend, and a picture will tell it in a second. Matplotlib is the most widely used plotting library in Python. A few lines turn your data into a clear chart, that you can save as an image, and put into a report or a website.

Charts with matplotlib
From the video: Charts with matplotlib
  • Tables hide the trend
  • A chart shows it in a second
  • matplotlib: plots from code

A line chart

Import pyplot as plt. Call plot with the x values and the y values. Add a title, and labels for the axes, so the chart is understandable on its own. Then save the figure to a file, or show it on the screen. Here, Ava plots her weekly sales. The picture appears on the right.

plot1.pypython
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

weeks = [1, 2, 3, 4, 5, 6]
sales = [120, 150, 170, 160, 210, 260]
plt.plot(weeks, sales, marker="o", color="#3776ab")
plt.title("Weekly sales")
plt.xlabel("Week")
plt.ylabel("Dollars")
plt.grid(alpha=0.3)
plt.savefig("chart.png", dpi=110)
Output
Matplotlib is building the font cache; this may take a moment.

Bar charts

Bar charts compare categories. Pass the names and the values to bar. Colours can be a list, one per bar, and you can add the value labels on top. Here, Ava compares the revenue of her best plants. The tallest bar is clear to see, even without reading a number.

plot2.pypython
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plants = ["fern", "ivy", "rose", "cactus"]
revenue = [260, 180, 310, 140]
bars = plt.bar(plants, revenue, color=["#3776ab", "#6cb4f0", "#ffd43b", "#7be3a0"])
plt.bar_label(bars)
plt.title("Revenue by plant")
plt.savefig("chart.png", dpi=110)

Several charts in one figure

Use subplots to place several charts side by side. You get a figure, and an array of axes, and draw on each one. Here, a histogram shows how the order sizes are spread, and a scatter plot compares the price and the quantity. Tight layout prevents overlapping labels. Pandas has its own plot method, that calls matplotlib for you.

plot3.pypython
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(3)
sizes = rng.normal(30, 8, 200)
fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.6))
a.hist(sizes, bins=15, color="#3776ab")
a.set_title("Order sizes")
b.scatter(rng.random(40), rng.random(40), color="#ffd43b")
b.set_title("Price vs qty")
fig.tight_layout()
fig.savefig("chart.png", dpi=110)

Plot your own data

Your turn. Create a bar chart of three numbers, with a title. Save it to a file, and print a message when it is done. Ready? Here is one solution. A bar call, a title, a save, and a print.

✍️ Exercise: Plot your own data

Draw a bar chart of three values with a title, save it as chart.png, and print "saved".

Show hint

plt.bar(names, values)

Show solution
plot_own.pypython
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.bar(["Mon", "Tue", "Wed"], [5, 9, 7])
plt.title("Sales this week")
plt.savefig("chart.png")
print("saved")
Output
saved

Summary

Excellent. You can now draw line charts, bar charts, histograms and scatter plots, label them clearly, and save them as images. NumPy, pandas, and matplotlib are the core of data science with Python, and you have met them all. Next, we look under the hood at how Python manages performance and memory.

Key takeaways
  • plt.plot, bar, hist, scatter
  • Always title and label
  • savefig to share your chart
Next up: Performance and Memory — make it fast, and understand why