Skip to content
Analyzing and Visualizing Data

Bar Charts


Learning Objectives

  • You can draw a bar chart from a prepared table of category results.
  • You can explain how labels, units, and the vertical scale affect a bar chart’s interpretation.
  • You can distinguish displaying prepared totals from calculating means while plotting.
  • You can write a drawing function that uses a supplied Axes object.

The pandas chapters prepared and checked numerical results. We will now use seaborn to draw them. A table provides exact values for each subject; a bar chart makes their relative sizes easier to compare. It places subjects along one axis and represents their values with bar heights.

Drawing the Subject Totals

Save this example as analysis.py beside sessions.csv. It loads the records, calculates the sorted subject totals, and draws them:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sessions = pd.read_csv("sessions.csv")
subject_totals = sessions.groupby("subject", as_index=False)["minutes"].sum()
subject_totals = subject_totals.sort_values("minutes", ascending=False)
fig, ax = plt.subplots()
sns.barplot(data=subject_totals, x="subject", y="minutes", errorbar=None, ax=ax)
ax.set_title("Recorded study time by subject")
ax.set_xlabel("Subject")
ax.set_ylabel("Total time in minutes")
fig.savefig("subject-totals.png", bbox_inches="tight")
plt.close(fig)

plt.subplots() creates a Figure and an Axes object. The Figure contains the chart; the Axes is its drawing area. The assignment names them fig and ax, in that order. ax.set_title, ax.set_xlabel, and ax.set_ylabel set the chart’s title and axis labels.

In the seaborn call, data supplies the table. x="subject" selects the column for horizontal categories; y="minutes" selects the bar heights. ax=ax draws on the Axes we created. errorbar=None hides uncertainty intervals, which we do not need for these prepared results.

Run python analysis.py and open subject-totals.png. Figure 1 shows the result.

Bar chart showing Programming at 350 minutes, Mathematics at 315, Writing at 150, and Languages at 100.

Figure 1. Each row of the grouped table supplies one category label and one bar height.

The categories follow the table’s row order. Sorting the summary therefore put the largest total first. The axis starts at zero, so bar heights are proportional to total minutes. Labels distinguish these durations from counts of sessions.

How the libraries work together

Pandas prepares the table. Seaborn reads that table and draws on a matplotlib Axes. Matplotlib also provides the enclosing Figure and saves it with fig.savefig. These are ordinary objects with methods, as in Part 6.

bbox_inches="tight" fits the saved image around the chart and its labels. plt.close(fig) releases the figure after saving. A PNG works even when Python cannot open a separate plot window.

fig.savefig saves the Figure named fig. A chart drawn on another Figure’s Axes will not appear in that file.

If a height surprises you, print subject_totals just before drawing. Check the calculated values first, then check the column names passed as x and y.

Practise these drawing arguments and labels by making one small change in each supplied program:

Checking the Vertical Scale

Suppose two groups of 100 students try different practice tasks. With Option 1, 81 students complete the task; with Option 2, 82 complete it. Figure 2 shows the rates with an axis starting at 80%.

Bar chart of completion rates of 81% and 82%, with a vertical axis from 80% to 85%.

Figure 2. A cropped axis exaggerates the visible difference.

The visible bars extend one and two percentage points above 80%, so the second looks twice as tall. Figure 3 displays the same values from zero.

Bar chart of the same 81% and 82% completion rates, with a vertical axis from 0% to 100%.

Figure 3. A zero baseline makes heights proportional to the recorded rates.

The difference is one percentage point, not a doubling of the completion rate. Start the value axis at zero when comparing bar heights, and keep the full bars visible. Check the units and axis limits before interpreting a chart.

The Values Behind the Bars

Seaborn’s barplot calculates a mean when it receives several values for the same category. Our prepared table has one row per subject, so each mean is just that supplied total. Passing the original sessions table would instead produce mean session lengths.

For example, this call would give Programming a height of 35 minutes, the mean of its ten durations, rather than their 350-minute total:

sns.barplot(data=sessions, x="subject", y="minutes", errorbar=None, ax=ax)

This is a comparison with the earlier call, not an additional line to draw on the same chart. errorbar=None hides intervals; it does not turn means into totals. Prepare the intended results before drawing and label the chart to match them.

Reading a Category Chart

0 / 5 points

The question is about total booking time for each room, but this code plots the individual records directly:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
bookings = pd.DataFrame([
{"room": "East", "minutes": 30},
{"room": "West", "minutes": 20},
{"room": "East", "minutes": 10},
{"room": "East", "minutes": 20}
])
fig, ax = plt.subplots()
sns.barplot(data=bookings, x="room", y="minutes", errorbar=None, ax=ax)

What height does this code give the East bar?

Comparing Totals and Mean Durations

The same drawing steps can display a different prepared calculation. Add this block after the earlier plt.close(fig) to save the mean session duration for each subject:

subject_means = sessions.groupby("subject", as_index=False)["minutes"].mean()
fig, ax = plt.subplots()
sns.barplot(data=subject_means, x="subject", y="minutes", errorbar=None, ax=ax)
ax.set_title("Mean study session length by subject")
ax.set_xlabel("Subject")
ax.set_ylabel("Mean time in minutes")
fig.savefig("subject-means.png", bbox_inches="tight")
plt.close(fig)

The mean table uses the alphabetical category order returned by groupby. Figure 4 puts the totals in that same order for comparison. Both value axes start at zero. Their labels distinguish accumulated time from mean session duration.

Two bar charts using the same alphabetical subject order. Total minutes are Languages 100, Mathematics 315, Programming 350, and Writing 150. Mean session lengths are 20, 52.5, 35, and 50 minutes respectively.

Figure 4. Programming has the greatest accumulated time; Mathematics has the longest mean session duration.

Programming’s ten sessions contribute more total time than Mathematics’s six sessions, although Programming sessions are shorter on average. The grouped calculation and axis label change together. The plotting function and Figure-handling steps stay the same.

Drawing with a Function

A drawing function lets the caller choose the figure and output file. Add this function after the imports in analysis.py:

def draw_subject_totals(summary, ax):
sns.barplot(data=summary, x="subject", y="minutes", errorbar=None, ax=ax)
ax.set_title("Recorded study time by subject")
ax.set_xlabel("Subject")
ax.set_ylabel("Total time in minutes")

Replace the original subject-total drawing block with this caller. The saved total chart remains the same:

fig, ax = plt.subplots()
draw_subject_totals(subject_totals, ax)
fig.savefig("subject-totals.png", bbox_inches="tight")
plt.close(fig)

In draw_subject_totals(subject_totals, ax), summary refers to the prepared table, and ax refers to the same drawing area that the caller will save. The function uses these supplied objects without creating another Figure.

The drawing function changes that Axes and does not need to return a value. Now write a drawing function for a different dataset. The exercise supplies the figure-handling code.

Run the following exercise’s supplied main.py locally in your data-analysis environment. Open reading-time.png and compare the bar heights, labels, and order with the supplied summary table before submitting.

A Reading Time Chart

0 / 35 points

Complete draw_reading_chart(summary, ax). Draw vertical bars on the supplied ax using genre as the categories and minutes as their heights, in the table’s row order. The table already contains one total per genre. Set:

  • Title: Recorded reading time by genre
  • Horizontal axis: Genre
  • Vertical axis: Total time in minutes

Keep the complete bars visible, starting from zero. Leave summary unchanged. It contains at least one row, distinct genres, and nonnegative numeric durations without missing values. The caller creates and saves the figure; the function need not return a value.

Check Your Understanding

  1. A chart shows rates of 76% and 78%, with its axis starting at 74%. How does this affect the apparent difference? What is the difference in percentage points?
  2. A saved PNG is blank after a drawing helper runs. How would you check whether the helper drew on the Axes belonging to the saved Figure?
  3. A chart uses barplot with the original session records, x="subject", and y="minutes", but its vertical axis says Total time in minutes. What does each bar actually represent, and what would you change to make the chart match its label?