How to Create a Diverging Stacked Bar Chart in Matplotlib?


To create a diverging stacked bar chart in Matplotlib, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Initialize a variable N to get the number of indices.
  • Get menMeans, womenMeans, menStd and womenStd tuple.
  • Initialize the width of bars.
  • Create a figure and a set of subplots.
  • To get diverging bar, we can put the data with positive and negative values to make diverging bars.
  • Add a horizontal line across the axis.
  • Set Ylabel, title, ticks, ticklabels, and legend.
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 5
menMeans = (20, -35, 30, 35, -27)
womenMeans = (25, -32, 34, 20, -25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)

ind = np.arange(N)
width = 0.35
fig, ax = plt.subplots()

p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
p2 = ax.bar(ind, womenMeans, width, bottom=menMeans, yerr=womenStd, label='Women')
ax.axhline(0, color='grey', linewidth=0.8)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()

plt.show()

Output

Updated on: 07-Jul-2021

736 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements