Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Bar Charts

DS 2023 | Communicating with Data

bar-chart.png

Overview

A simple bar chart uses rectangular bars to represent and compare a numerical measurement variable over the domain of a group.

Groups (e.g., product types, months, or cities) are usually represented on the x axis.

Measurements (e.g., sales numbers, temperatures, or percentages) are usually represented on the y axis.

The height of each bar is proportional to the value it represents.

The width of the bar has no relationship to the value the bar represents.

Tasks and Use Cases

  • Compare a measurement variable over a grouping variable, for example revenue by region, headcount per department, medals won by country, average rent in five cities, or votes per candidate.

  • Rank items from largest to smallest, for example a company’s top ten customers by spend, most common causes of support tickets, bestselling book titles, or the leading sources of a country’s emissions.

  • Compare a measurement variable over two or more grouping variables, for example quarterly revenue split by product line, survey answers by response option, budget by spending category across several years, or population by age band in each country.

  • Show deviation above and below a baseline with diverging bars, for example actual vs. budgeted spend per team, temperature anomalies by year, net sentiment scores by topic, or percentage change in sales by store.

  • Compare values across a small number of discrete time periods, for example annual profit for the last five years, quarterly enrollment, or headcount at the end of each fiscal year. In this case, time periods act as grouping variables.

Creating a bar chart from scratch

We start with a data frame that contains a grouping variable with unique values and an associated measurement.

This is the simplest form of data that can be visualized with a bar chart.

In this case, a bar chart will show us visually the differences in magnitude among the values AA, BB, an CC for the nominal feature. First, let’s acquire the data.

In this case, we’ll just make them up.

Loading...

Before we plot anything, let’s properly label the axes in the data frame.

We will call the features group and measure.

Loading...

Because the group data are unique, we can create a rudimentary bar chart just by converting the measurement value into a string.

To do this, we can use the handy .iterrows() method, which iterates over each row, returning the row index and row values each time.

A |||||||||||||||
B ||||||||||||||||||||||||||||||||||
C ||||||||||||||||||||||

We can improve the display by using the block character █ instead of a pipe:

A ███████████████
B ██████████████████████████████████
C ██████████████████████

We can even add the number value to make it more legible.

A ███████████████ 15
B ██████████████████████████████████ 34
C ██████████████████████ 22

And — voilà! — you have a bar chart.

Using Pandas’ plot method

Now, to produce this kind of chart we call Pandas’ .plot() method and pass it the argument kind = 'bar' along with passing features to the x and y axes of the plot.

<Figure size 640x480 with 1 Axes>

Let’s clean the figure up a bit.

First, let’s remove the legend since it is not really needed in this example.

Second, let’s rotate the letters on the x axis for readability.

<Figure size 640x480 with 1 Axes>

To create a horizontal chart, we set kind to barh.

<Figure size 640x480 with 1 Axes>

Note that instead of using the argument kind, we can call bar and barh as chained methods to .plot(), like so:

<Figure size 640x480 with 1 Axes>

Plotting with indexes

Note that if we do not set the value of x, Pandas will use the index as the x axis.

<Figure size 640x480 with 1 Axes>

In fact, it is a good practice to assign the grouping variable to be the index in this case.

Since the values are unique, they can used as index values.

<Figure size 640x480 with 1 Axes>

Note also that if we pass a series to the plot method, by selecting a feature, we don’t need to specify the y argument either.

group A 15 B 34 C 22 Name: measure, dtype: int64
<Figure size 640x480 with 1 Axes>

A better example

In the preceding example we had a data set in which unique grouping values are paired with measurements.

In reality, we don’t often get data like this. More typically, the grouping values are repeated over observations.

Consider the Iris data set, which we will grab from the Seaborn library.

Loading...

Notice the repetition of the grouping variable species.

To plot this variable against any of the other measurements, we need to group the measurements by the grouping variable and compute an aggregate value, such as the median, sum, or mean of the feature for each group.

To do this, we can use .groupby() as follows.

<Figure size 640x480 with 1 Axes>

Another thing we can do is just get the number of instances of a particular value in the nominal column using .value_counts().

<Figure size 640x480 with 1 Axes>

Here we can see that the data set is balanced over species — there are 50 observations per species.

Showing multiple measurements

What if we want to compare the magnitudes of more than one measurement across a grouping variable, in this case species?

Let’s experiment to find out.

First, we get the mean of all the measurements by grouping on species and not specifying any columns to aggregate.

Pandas will interpret this as saying you want all the columns aggregated.

Loading...

Now, when we call plot.bar(), Pandas creates a bar chart for each variable and then combines them.

By default, it combines them into groups.

<Figure size 640x480 with 1 Axes>

We can also combine them by stacking if we set stacked = True.

<Figure size 640x480 with 1 Axes>

Finally, we can use subplot = True to create a separate plot for each feature.

<Figure size 640x480 with 4 Axes>

Notice that this figure needs some work to improve its legibility.

Let’s change the size of the figure to give each plot more room.

To do this, we set figsize = (5,10), i.e. we set width to 5 and height to 10 and remove the legend since it is redundant.

We can also set plt.tight_layout(), which adds spacing between the plots.

<Figure size 500x1000 with 4 Axes>

Changing group value order

Finally, we can transpose the table to change the priority of categories.

The order of representation is as follows: Each observation row gets a bar, and each feature column gets a plot.

So, if we want each species to get its own plot with features as bars, we can use the .T operator to flip the table.

Loading...

The result is a different bar plot.

Now, the variable names become the categories on the x axis.

<Figure size 500x1000 with 3 Axes>

Of course, we can recreate the plots we made above with the new transposed table.

This plot shows the relative magnitudes of each measurement over species.

<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>