PY-401 ยท Visualisation
Charts straight from pandas
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
Every pandas Series and DataFrame has a .plot() method that draws with matplotlib for you. df.plot(x="month", y="revenue") draws a line, kind="bar" or .plot.barh() draws bars, and the index and column names become the axis labels. The common pattern is: groupby, sort, then plot.
- Plot a DataFrame with .plot
- Chart a groupby result
- Sort before you plot
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pdsales = pd.DataFrame({"region": ["North", "South", "North", "East", "South", "West", "East"],"revenue": [120, 90, 200, 60, 150, 40, 110],})per_region = sales.groupby("region")["revenue"].sum().sort_values()print(per_region)ax = per_region.plot.barh(figsize=(6, 3), color="#2563eb")ax.set_title("North brings in the most revenue")ax.set_xlabel("Revenue")
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
region
West 40
East 170
South 240
North 320
Name: revenue, dtype: int64 ๐ฏ Set per_city to total "amount" per "city", sorted from smallest to largest, then draw it as a bar chart with per_city.plot(kind="bar").
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
per_city = orders.groupby("city")["amount"].sum().sort_values(); ax = per_city.plot(kind="bar")
- The problemYou already have revenue per region from groupby. Your manager wants it as a chart for a slide. It is one more method on the end of the line you already wrote.
- The Python idea
s.plot(kind="bar")Every pandas Series and DataFrame has a.plot()method that draws with matplotlib for you. - In real lifeA support team runs
tickets.groupby("product")["minutes"].mean().sort_values().plot.barh()every Friday to see which product takes longest to support.
Start with a question
You already have revenue per region from groupby. Your manager wants it as a chart for a slide. It is one more method on the end of the line you already wrote.
Most charts in real analysis come straight from a pandas result. Learning .plot turns every summary you make into a picture in seconds.
Explain it like I'm 10
pandas already knows your table's names and numbers, so you just say "draw it as bars" and it does the drawing for you.
The technical explanation
series.plot(kind="bar") uses the index for the x-axis and the values for the bar heights.
df.plot(x="month", y=["north", "south"]) draws one line per column, with a legend.
.plot returns a matplotlib axes, so ax = s.plot.barh(); ax.set_title("...") adds a title.
Chain it: df.groupby("region")["revenue"].sum().sort_values().plot.barh().
Syntax
s.plot(kind="bar")
s.plot.barh()
df.plot(x="col", y=["a", "b"])
ax = s.plot(); ax.set_title("...") Real-world scenario
A support team runs tickets.groupby("product")["minutes"].mean().sort_values().plot.barh() every Friday to see which product takes longest to support.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Choosing the right chart โQuestions people ask
How do I plot a pandas groupby result?
Aggregate first so you have one value per group, then call .plot on it, for example df.groupby("region")["revenue"].sum().plot(kind="bar").
How do I plot several columns as lines in pandas?
Use df.plot(x="date", y=["north", "south"]). Each column becomes a line and pandas adds a legend with the column names.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I plot a pandas groupby result?
Aggregate first so you have one value per group, then call .plot on it, for example df.groupby("region")["revenue"].sum().plot(kind="bar").
beginner How do I plot several columns as lines in pandas?
Use df.plot(x="date", y=["north", "south"]). Each column becomes a line and pandas adds a legend with the column names.
intermediate What does pandas .plot() draw with?
matplotlib. pandas plotting is a wrapper around matplotlib.
intermediate In s.plot(kind="bar"), what is on the x-axis?
The index. The index labels the bars.
Quick revision
Remember
- Plot a DataFrame with .plot
- Chart a groupby result
- Sort before you plot
- Sort bars by value before plotting,
.sort_values(), so the biggest and smallest are easy to find. Alphabetical order rarely tells a story.
Syntax
s.plot(kind="bar")
s.plot.barh()
df.plot(x="col", y=["a", "b"])
ax = s.plot(); ax.set_title("...") Official documentation
- pandas chart visualization (docs.python.org)