Charts with Matplotlib
A picture beats a table — draw line and bar charts to make patterns jump out instantly.
What you will learn
- Draw a line chart and a bar chart
- Add titles and axis labels
- Know when to use each chart
Why we draw charts
A wall of numbers hides its story; a chart reveals it in a second. Matplotlib is Python’s classic charting library. By convention we import its main part as plt.
You build a chart in three moves: give plt the data, add labels, then call plt.show() to display it.
A line chart — trends over time
Line charts are perfect for change over time, like sales across months.
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr']
sales = [250, 300, 280, 400]
plt.plot(months, sales)
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()Note: Output: (A window opens showing a line rising from 250 in Jan to 400 in Apr, dipping slightly in Mar. The title reads “Monthly Sales” with labelled axes.) The upward trend is obvious at a glance — far clearer than reading the four numbers.
A bar chart — comparing categories
Bar charts compare separate categories, like sales per product.
products = ['Keyboard', 'Mouse', 'Monitor']
amounts = [250, 120, 900]
plt.bar(products, amounts)
plt.title('Sales by Product')
plt.ylabel('Amount')
plt.show()Note: Output: (A window with three bars. The Monitor bar towers over the others at 900, Keyboard sits at 250, Mouse is shortest at 120.) The Monitor clearly dominates sales — the tall bar tells the story instantly.
| Chart | Use it for | Function |
|---|---|---|
| Line | Trends over time | plt.plot() |
| Bar | Comparing categories | plt.bar() |
| Histogram | Distribution of one number | plt.hist() |
| Scatter | Relationship of two numbers | plt.scatter() |
Tip: Always label your chart — a title, an xlabel and a ylabel. An unlabelled chart is a puzzle; a labelled one is an answer.
Watch out: Forgetting plt.show() is a common beginner trip-up: you build the chart but nothing appears. (In a Jupyter notebook, charts often show automatically, but plt.show() always works.)
Q. Which chart type is best for showing a trend over time?
✍️ Practice
- Draw a line chart of any five values over five days, with a title and axis labels.
- Draw a bar chart comparing the populations of four cities.
🏠 Homework
- From a real CSV, make one line chart (something over time) and one bar chart (a comparison). Give both clear titles and labels.