Sub topic 7
Meet pandas and matplotlib in a notebook
This chapter assumes you can write basic Python, have a working virtual environment with JupyterLab, pandas, and matplotlib installed, and have registered that environment as a kernel. You should also know what a CSV file is. Here you will see what the two libraries do, how they fit together inside a notebook, and which mistakes cause the most confusion.
What each library does
pandas holds tabular data in memory and gives you operations on it. matplotlib draws charts. They meet because pandas objects have a .plot() method that calls matplotlib for you.
| Library | Core object | Main job |
|---|---|---|
| pandas | `DataFrame`, `Series` | Load, clean, filter, group, and summarize tables |
| matplotlib | `Figure`, `Axes` | Draw and style charts |
A DataFrame is a two-dimensional table with labeled columns and a row index. A Series is one column of that table, or any one-dimensional labeled array. Selecting a single column with df["revenue"] returns a Series. Selecting several with df[["revenue", "units"]] returns a smaller DataFrame.
The conventional imports
Nearly all pandas and matplotlib code uses the same two import lines. Putting them in the first code cell of the notebook is a good habit, because every later cell depends on them.
import pandas as pd
import matplotlib.pyplot as plt
print(pd.__version__)
print(plt.matplotlib.__version__)Printing the versions confirms that the notebook is using the kernel you registered. If an import fails with ModuleNotFoundError, the notebook is probably running on a different Python than the one where you installed the packages. Check the kernel name in the top-right corner of the notebook. Switching to the right kernel fixes this far more often than reinstalling does.
How the two libraries connect
When you call df["revenue"].plot(kind="hist"), pandas builds the arguments and hands them to matplotlib. It returns a matplotlib Axes object. That is why you can combine the two styles: use pandas for quick plots, then use matplotlib calls to adjust titles, labels, and sizes.
The last step depends on the plotting backend. In JupyterLab the usual backend renders figures as static images below the cell. The %matplotlib inline magic command selects it explicitly, and a later chapter covers magics in detail. Recent versions of the Jupyter kernel choose a sensible default, so you often do not need to set it.
A first complete example
The example below builds its own data, so you can run it without any file. It uses a small sales table with a date, a region, and a revenue figure.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"month": ["Jan", "Feb", "Mar", "Jan", "Feb", "Mar"],
"region": ["North", "North", "North", "South", "South", "South"],
"revenue": [120, 135, 150, 90, 110, 95],
}
)
dfA notebook cell displays the value of its last expression. Here that is df, so you see a formatted HTML table instead of plain text. If you wrote print(df), you would get a plain text version. The formatted table is usually easier to read, but only the last expression in a cell is shown this way.
Now group and plot:
totals = df.groupby("region")["revenue"].sum()
print(totals)
ax = totals.plot(kind="bar", title="Total revenue by region")
ax.set_xlabel("Region")
ax.set_ylabel("Revenue")
plt.show()Step by step:
groupby("region")splits the rows into one group per region.["revenue"].sum()adds up revenue inside each group and returns aSeriesindexed by region..plot(kind="bar")draws one bar per index label and returns theAxes.set_xlabelandset_ylabelare matplotlib methods on thatAxes.plt.show()finishes the figure and displays it.
Two matplotlib styles
matplotlib has two interfaces, and mixing them is a common source of confusion.
- The state-based interface uses
plt.plot(...),plt.title(...), and similar calls. It acts on a hidden "current" figure. - The object-based interface creates a figure and axes explicitly, then calls methods on them.
In a notebook, where many plots live in one session, the object-based style is safer, because each call names the axes it changes.
fig, ax = plt.subplots(figsize=(6, 3))
for region, group in df.groupby("region"):
ax.plot(group["month"], group["revenue"], marker="o", label=region)
ax.set_title("Monthly revenue")
ax.set_ylabel("Revenue")
ax.legend()
fig.tight_layout()
plt.show()plt.subplots returns a figure and an axes. The loop draws one line per region on the same axes. fig.tight_layout() adjusts spacing so labels do not overlap.
Reading the shape of a DataFrame
Before plotting, check what you have. Four attributes and methods cover most of what you need.
| Call | What it tells you |
|---|---|
| `df.shape` | Rows and columns as a tuple |
| `df.dtypes` | The data type of each column |
| `df.head(n)` | The first `n` rows (default 5) |
| `df.isna().sum()` | Count of missing values per column |
print(df.shape)
print(df.dtypes)
print(df.isna().sum())Data types matter for plotting. A column of numbers read as text (object dtype) will not plot as a numeric series, and sorting it gives alphabetical order. Convert it with pd.to_numeric(df["revenue"], errors="coerce"), which turns unparseable entries into NaN rather than raising an error.
Common errors and how to read them
ModuleNotFoundError: No module named 'pandas': the kernel's environment lacks the package. Check the kernel name, then install into that environment.- A plot does not appear: either the last expression was not the plot, or a non-inline backend is active. Call
plt.show()and, if needed, run%matplotlib inline. - Plots pile up on each other: the state-based interface keeps drawing on the current figure. Create a new figure with
plt.subplots()for each chart. SettingWithCopyWarning: you assigned to a slice that may be a copy of the original. Make the intent explicit with.copy()or assign through.loc.KeyError: 'revenue': the column name differs from what you typed. Rundf.columnsand look for trailing spaces or different capitalization.
Why this matters for the rest of the setup
pandas and matplotlib are the first libraries that make your environment matter. They are installed in your virtual environment, found through your kernel, and recorded in your dependency file later. A notebook that imports them without a matching kernel is the typical "works on my machine" failure. The next chapter uses these tools on a real CSV file, with more inspection and a histogram.
Exercise
A colleague's notebook raises ModuleNotFoundError: No module named 'matplotlib' even though they ran pip install matplotlib in a terminal. Name two likely causes and how you would check each.
Show answer
First, the terminal's virtual environment was not active when they installed, so the package went to a different Python. Check with python -m pip show matplotlib in the terminal after activating the project environment. Second, the notebook is using a different kernel than the environment they installed into. Check the kernel name in the notebook's top-right corner and run import sys; print(sys.executable) in a cell to see which Python is running. If the paths differ, select or register the correct kernel.
Exercise
Using the df from this chapter, write code that computes the average revenue per month across both regions and draws it as a line chart with a title and a y-axis label, using the object-based matplotlib style.
Show answer
```python