Python Tutorial
Pandas Plotting
DataFrame.plot uses Matplotlib. You get a quick chart without leaving Pandas.
Line and Bar
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"week": [1, 2, 3, 4],
"signups": [12, 18, 15, 22],
})
df.plot(x="week", y="signups", kind="line")
plt.show()
df.plot(x="week", y="signups", kind="bar")
plt.show()Histogram and Scatter
df = pd.DataFrame({"score": [88, 92, 70, 95, 60, 88]})
df["score"].plot(kind="hist")
plt.show()For richer styling, continue with Matplotlib or Seaborn. For interactive dashboards, continue with Dash.
📘 Real-World Deep Dive
Knowing <strong>Pandas Plotting (pandas)</strong> well is what turns pandas from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Pandas Plotting that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"x": range(10), "y": [i**2 for i in range(10)]})
df.plot(x="x", y="y", kind="line")
plt.show()Expected Output
(no output)Common mistakes
- A
DataFrameindexing pattern likedf[df.col > 5]returns a copy — use.loc[row_mask, col]for assignment to avoidSettingWithCopyWarning. - Pandas infers
objectdtype for CSVs with mixed numeric/text columns; cast withpd.to_numeric/astype("category")for big speed/memory wins. df.iterrows()is O(n) and slow; iterate withdf.itertuples()or vectorise column-wise.- Treating Pandas Plotting as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Enable the Arrow backend:
pd.read_csv("…", engine="pyarrow", dtype_backend="pyarrow")for faster, type-stable reads. - Use
categoricaldtype for columns with low-cardinality strings — sort/join/group-by speed up dramatically. - Switching a hot loop from row-wise Python to
df.eval("…")/df.query("…")often gives 5–50×. - When working with pandas, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.