Chapter 03 · Section III · 22 min read
matplotlib: seeing your data
Humans read pictures faster than tables. matplotlib turns a NumPy array or a pandas Series into a chart in one or two lines. Once you can see your data, half the bugs announce themselves on sight.
A column of numbers tells you something. A chart of the same numbers tells you much more, much faster — and almost always tells you something the column did not. A long flat line that suddenly spikes. A scatter plot where two clouds of points sit, side by side, screaming “these are two different things, treat them differently”. matplotlib is how Python draws pictures of data, and learning to reach for it early — before you trust your numbers — is one of the better habits in this whole track.
Installing matplotlib
pip install matplotlib
In a notebook:
!pip install matplotlib
The conventional import is one line longer than the others:
import matplotlib.pyplot as plt
Almost every chart you draw starts with that import.
Your first plot
A line chart of NEPSE closes:
import matplotlib.pyplot as plt
dates = ["Mon", "Tue", "Wed", "Thu", "Fri"]
closes = [2105.4, 2128.9, 2117.3, 2134.7, 2142.1]
plt.plot(dates, closes)
plt.show()
In a notebook, the chart appears below the cell. In a script, plt.show() opens a window. Two lines of plotting, and you have a picture.
A picture by itself is rarely enough. Always label it:
plt.plot(dates, closes, marker="o")
plt.title("NEPSE Index — past week")
plt.xlabel("Day")
plt.ylabel("Closing value")
plt.show()
marker="o" puts a dot on each data point — useful when you have only a handful of values. A chart without a title, axis labels, and (where relevant) units is a chart that will confuse you in three weeks.
Three chart types you will draw a hundred times
A short tour:
Line chart — for anything that changes over time. Stock prices, temperatures, daily transaction counts.
plt.plot(dates, closes)
Bar chart — for comparing categories. Total amount per vendor, students per district, languages spoken.
vendors = ["Khalti", "eSewa", "FonePay"]
totals = [5450, 1200, 900]
plt.bar(vendors, totals)
plt.ylabel("Total Rs.")
plt.title("Transactions by vendor")
plt.show()
Scatter plot — for two numeric variables together. Time spent studying vs. exam score; rainfall vs. paddy yield; house size vs. rent.
study_hours = [1, 2, 3, 4, 5, 6, 7]
scores = [55, 60, 64, 70, 76, 79, 82]
plt.scatter(study_hours, scores)
plt.xlabel("Study hours")
plt.ylabel("Exam score")
plt.title("Studying vs. score")
plt.show()
If you can choose the right one of these three for a question, you can sketch most things you will encounter. A fourth, the histogram, comes in Course 02 when we look at the distribution of single variables.
Plotting straight from pandas
Once you are in pandas, you usually do not need to pull numbers out into lists. Both Series and DataFrames have a .plot() method that uses matplotlib under the hood:
import pandas as pd
import matplotlib.pyplot as plt
prices = pd.read_csv("data/prices.csv")
prices.plot(x="date", y="close", marker="o")
plt.title("NEPSE Index — past week")
plt.show()
For a bar chart of grouped data:
totals = transactions.groupby("vendor")["amount"].sum()
totals.plot(kind="bar")
plt.title("Transactions by vendor")
plt.ylabel("Total Rs.")
plt.show()
The kind argument controls the chart type — "line" (default), "bar", "barh" (horizontal bar), "hist", "scatter", and a few others.
Saving a chart to a file
When your work is in a notebook, the chart appears in the output and is saved with the notebook. When you want a standalone image — to email a teacher, post on LinkedIn, or include in a report — save it:
plt.plot(dates, closes, marker="o")
plt.title("NEPSE Index — past week")
plt.savefig("data/nepse_week.png", dpi=200, bbox_inches="tight")
A few production niceties:
dpi=200gives a sharp image. The default (100) is fine on screen but blurry when printed.bbox_inches="tight"trims the white border, which matters when the chart is going on a slide.- Save before calling
plt.show(). Aftershow(), matplotlib clears the figure, andsavefigwrites an empty file.
When a chart catches a bug
A real example. Suppose you have a year of daily temperatures from Pokhara and you compute the mean: 23.4°C. Plausible. You compute the max: 124°C. Implausible — that is fever territory for the planet.
You plot the data:
plt.plot(dates, temperatures)
plt.show()
The chart shows a steady line around 20–25°C, with a single spike to 124 on April 17. That is almost certainly a data-entry error or a sensor failure — and you would have spent an hour searching for it in a 365-row table without the chart. The chart found it in three seconds.
This is what we mean by seeing your data. The numbers were right; the chart asked the right question.
Check your understanding
Quick check
—You want to compare total revenue across five regions for a single quarter. Which matplotlib chart type is the right default choice?
Quick check
—A friend writes: plt.plot(dates, closes) plt.show() plt.savefig('chart.png') She opens 'chart.png' and finds it empty. What happened?
What comes next
You can now hold data in shapes, move it through functions and loops, read and write it from disk, crunch it with NumPy, organise it with pandas, and see it with matplotlib. That is, more or less, the toolkit. Chapter 4 leaves the language for a moment to look at three habits that turn a tinkerer into a builder: keeping projects separate, saving work with version control, and reading errors instead of fearing them.