Data analysis with pandas · Lesson 14 of 15

Charts with matplotlib and df.plot

Draw line, bar, scatter and histogram charts with matplotlib, add titles and labels, and chart a DataFrame straight away with df.plot.

About 16 minutes · code runs in your browser, nothing to install

A chart shows in a second what a table of numbers hides: a trend, a winner, an odd value. matplotlib is the standard Python library for charts, and pandas uses it for its own plot method. Everyone imports its drawing part as plt. The recipe is always the same: draw, add a title and labels, then call plt.show(). On this page the chart appears under the output.

Line chart

plt.plot(x, y) joins points with a line, the right choice for values over time. marker="o" adds a dot on each point.

Pythoneditable
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
temps = [8, 9, 13, 16, 20, 25]
print("Warmest month:", months[temps.index(max(temps))])

plt.plot(months, temps, marker="o", color="tomato")
plt.title("Average temperature in Seville (°C)")
plt.xlabel("Month")
plt.ylabel("°C")
plt.grid(alpha=0.3)
plt.show()
Output
Warmest month: Jun
Chart drawn by this code

Bar chart

Bars compare amounts between groups. plt.bar(labels, values) draws vertical bars, plt.barh horizontal ones, which suit long names.

Pythoneditable
import matplotlib.pyplot as plt

items = ["coffee", "tea", "cake", "juice"]
sold = [140, 65, 48, 30]
for i, n in zip(items, sold):
    print(f"{i:<7}{n:>4}")

plt.bar(items, sold, color="teal")
plt.title("Items sold this week")
plt.ylabel("Items")
plt.show()
Output
coffee  140
tea      65
cake     48
juice    30
Chart drawn by this code

Charts straight from a DataFrame

A DataFrame has its own plot method: the index goes along the bottom and every number column becomes a line (or a set of bars). kind= chooses the chart: "line", "bar", "barh", "hist", "scatter", "pie".

Pythoneditable
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "Oslo": [-4, -3, 1, 6, 11, 15],
    "Rome": [8, 9, 12, 15, 19, 24],
    "Cairo": [14, 16, 19, 23, 26, 28],
}, index=["Jan", "Feb", "Mar", "Apr", "May", "Jun"])
print(df.mean().round(1))

df.plot(kind="bar", title="Average temperature (°C)")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
Output
Oslo      4.3
Rome     14.5
Cairo    21.0
dtype: float64
Chart drawn by this code

Grouped bars: one colour per city, one group per month.

Scatter plot

A scatter plot puts one dot per row, to see whether two columns move together. Here: hours of study against the test mark.

Pythoneditable
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "hours": [1, 2, 2, 3, 4, 5, 6, 7],
    "mark": [52, 60, 55, 66, 63, 74, 70, 86],
})
print("Correlation:", round(float(df["hours"].corr(df["mark"])), 2))

df.plot(kind="scatter", x="hours", y="mark", s=50,
        title="Study hours and marks")
plt.show()
Output
Correlation: 0.93
Chart drawn by this code

A correlation near 1 means the two columns tend to rise together; near 0 means no link.

Histogram

A histogram counts how many values fall into each range (a bin). It shows the shape of the data: where most values are and how spread out they are.

Pythoneditable
import matplotlib.pyplot as plt

marks = [45, 52, 58, 61, 63, 64, 66, 68, 70, 71,
         72, 74, 75, 78, 81, 83, 85, 88, 92, 97]
print("Students:", len(marks))

plt.hist(marks, bins=[40, 50, 60, 70, 80, 90, 100],
         color="slateblue", edgecolor="white")
plt.title("Test marks")
plt.xlabel("Mark")
plt.ylabel("Students")
plt.show()
Output
Students: 20
Chart drawn by this code

On your own computer, plt.savefig("chart.png", dpi=150) before plt.show() saves the chart as an image.

✎ Exercise

Draw a horizontal bar chart (plt.barh) of the money spent on each category, with the title Spending (€). Before drawing, print the name of the biggest category.

Hint: Start with import matplotlib.pyplot as plt, then plt.barh(cats, spent), plt.title(...) and plt.show().

Your codewrite your answer, then Run
cats = ["rent", "food", "travel", "fun"]
spent = [800, 350, 120, 90]
# your code here: import pyplot as plt, print, then draw

Expected output:

Biggest: rent
Show a solution
Solutioneditable
import matplotlib.pyplot as plt

cats = ["rent", "food", "travel", "fun"]
spent = [800, 350, 120, 90]
print("Biggest:", cats[spent.index(max(spent))])
plt.barh(cats, spent, color="orange")
plt.title("Spending (€)")
plt.show()
Output
Biggest: rent
Chart drawn by this code

Check yourself

1. Which chart suits values over time best?

2. In df.plot(), what goes along the bottom by default?

3. What does a histogram show?

Spotted a mistake on this page? Tell us