Bar Charts
DS 2023 | Communicating with Data

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 , , an for the nominal feature. First, let’s acquire the data.
In this case, we’ll just make them up.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsmy_data = [
['A', 15],
['B', 34],
['C', 22]
]
df1 = pd.DataFrame(my_data)
df1Before we plot anything, let’s properly label the axes in the data frame.
We will call the features group and measure.
df1.columns = ['group', 'measure']
df1Because 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.
for i, row in df1.iterrows():
print(row['group'], row['measure'] * '|')A |||||||||||||||
B ||||||||||||||||||||||||||||||||||
C ||||||||||||||||||||||
We can improve the display by using the block character █ instead of a pipe:
for i, row in df1.iterrows():
print(row['group'], row['measure'] * '█')A ███████████████
B ██████████████████████████████████
C ██████████████████████
We can even add the number value to make it more legible.
for i, row in df1.iterrows():
print(row['group'], row['measure'] * '█' + " " + str(row['measure']))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.
df1.plot(kind='bar', x='group', y='measure', title="A Very Simple Bar Chart")
plt.show()
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.
df1.plot(kind='bar', x='group', y='measure',
title="A Very Simple Bar Chart",
legend=False, rot=0)
plt.show()
To create a horizontal chart, we set kind to barh.
df1.plot(kind='barh', x='group', y='measure', title="A Very Simple Bar Chart", legend=False, rot=0)
plt.show()
Note that instead of using the argument kind, we can call bar and barh as chained methods to .plot(), like so:
df1.plot.bar(x='group', y='measure', title="A Very Simple Bar Chart", legend=False, rot=0)
plt.show()
Plotting with indexes¶
Note that if we do not set the value of x, Pandas will use the index as the x axis.
df1.plot.bar(y='measure', title="A Very Simple Bar Chart", legend=False, rot=0)
plt.show()
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.
df2 = df1.set_index('group')
df2.plot.bar(y='measure', title="A Very Simple Bar Chart", legend=False, rot=0)
plt.show()
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.
df2['measure']group
A 15
B 34
C 22
Name: measure, dtype: int64df2['measure'].plot.bar(title="A Very Simple Bar Chart", legend=False, rot=0)
plt.show()
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.
iris = sns.load_dataset('iris')
iris.sample(10)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.
(
iris.groupby('species').sepal_length.mean()
.plot.bar(rot=0, title="Mean Sepal Length by Species")
)
plt.show()
Another thing we can do is just get the number of instances of a particular value in the nominal column using .value_counts().
iris.species.value_counts().plot.bar(rot=0)
plt.show()
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.
iris_means = iris.groupby('species').mean()
iris_meansNow, when we call plot.bar(), Pandas creates a bar chart for each variable and then combines them.
By default, it combines them into groups.
iris_means.plot.bar(rot=0)
plt.show()
We can also combine them by stacking if we set stacked = True.
iris_means.plot.bar(rot=0, stacked=True)
plt.show()
Finally, we can use subplot = True to create a separate plot for each feature.
iris_means.plot.bar(rot=0, subplots=True)
plt.show()
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.
iris_means.plot.bar(rot=0, subplots=True, figsize=(5,10), sharey=True, legend=False)
plt.tight_layout()
plt.show()
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.
iris_means.TThe result is a different bar plot.
Now, the variable names become the categories on the x axis.
iris_means.T.plot.bar(rot=0, subplots=True, figsize=(5,10), legend=False)
plt.show()
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.
iris_means.T.plot.bar(rot=0, stacked=True)
plt.show()
iris_means.T.plot.bar(rot=0, stacked=False)
plt.show()