Lesson 20 of 23
โฎPrev Nextโฏ

PY-401 ยท Visualisation

Charts straight from pandas

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

20of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    Charts straight from pandas, running
    1. import pandas as pd
    2. sales = pd.DataFrame({
    3. "region": ["North", "South", "North", "East", "South", "West", "East"],
    4. "revenue": [120, 90, 200, 60, 150, 40, 110],
    5. })
    6. per_region = sales.groupby("region")["revenue"].sum().sort_values()
    7. print(per_region)
    8. ax = per_region.plot.barh(figsize=(6, 3), color="#2563eb")
    9. ax.set_title("North brings in the most revenue")
    10. ax.set_xlabel("Revenue")
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideas.plot(kind="bar")Every pandas Series and DataFrame has a .plot() method that draws with matplotlib for you.
    3. 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("...")

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does pandas .plot() draw with?
    2. 2. In s.plot(kind="bar"), what is on the x-axis?
    3. 3. Which draws horizontal bars?
    4. 4. How do you add a title to a pandas plot?
    5. 5. Why sort before plotting bars?

    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