Create a back-to-back bar plot in Matplotlib




Create back-to-back

Luc B.



Bar Plot

Back-to-back bar plots are useful for comparing two data sets with a common independent variable. For example, a back-to-back bar plot could show the male/female composition of a population by year, allowing readers to simultaneously observe trends in sex composition and total population.

A visualization with similar applications is the stacked bar plot.

Code Example

To create a back-to-back bar plot, simply negate one of the two data series, plot as usual with plt.barh(), and then manually change the tick labels so none is negative.

import matplotlib.pyplot as plt
import numpy as np

group1 = np.array([60, 56, 63, 75, 48])
group2 = np.array([38, 52, 40, 80, 55])
labels = ["This", "is", "a", "bar", "plot"]

# Create back-to-back bar plot here
plt.barh(labels, -group1)
plt.barh(labels, group2)

# Change tick labels so all values are positive
plt.xticks(range(-80, 81, 20),
           list(range(80, 0, -20)) + list(range(0, 81, 20)))

plt.legend(["Group 1", "Group 2"])


Here we use plt.barh() to create a horizontal bar plot. Replacing this with will create the same plot just rotated by 90 degrees.

More Examples

Object Oriented Interface

The same plot is easily accomplished with Matplotlib's object oriented interface.

ax = plt.axes()

# Create back-to-back bar plot here
ax.barh(labels, -group1)
ax.barh(labels, group2)

# Change tick labels so all values are positive
ax.set_xticks(range(-80, 81, 20))
ax.set_xticklabels(list(range(80, 0, -20)) + list(range(0, 81, 20)))

ax.legend(["Group 1", "Group 2"])