Stacked bar plot using matplotlib

How to create a simple stacked bar chart.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# open data file
df = pd.read_csv('data_file.csv')

# get the data you want to plot
dataVar1 = df['column1']
dataVar2 = df['column2']
dataVar3 = df['column3']
dataVar4 = df['column4']
dataVar5 = df['column5']

# number of entries (x axis)
xMain = np.arange(30)

# plot each data
p1 = plt.bar(xMain, 
             dataVar1)

p2 = plt.bar(xMain, 
             dataVar2,
             bottom=dataVar1)

p3 = plt.bar(xMain,
             dataVar3,
             bottom=dataVar1+dataVar2)

p4 = plt.bar(xMain,
             dataVar4,
             bottom=dataVar1+dataVar2+dataVar3)

p5 = plt.bar(xMain,
             dataVar4,
             bottom=dataVar1+dataVar2+dataVar3+dataVar4)

# save the graph
plt.savefig('output_fig.png')

The botttom=dataVarn option is needed to stack the data, otherwise it will draw the next set of data at y=0.

If you do it right, you’ll get something like this.