Plot Multiple Columns on Bar Chart with pandas


You can use the following syntax to plot multiple columns of a pandas DataFrame on a single bar chart:

df[['x', 'var1', 'var2', 'var3']].plot(x='x', kind='bar')

The x column will be used as the x-axis variable and var1, var2, and var3 will be used as the y-axis variables.

The following examples show how to use this function in practice.

Example 1: Plot Columns on a Bar Chart

The following code shows how to plot three columns on a bar chart, specifying that the column named period should be used as the x-axis variable:

import pandas as pd
import matplotlib.pyplot as plt

#create fake data
df = pd.DataFrame({'period': [1, 2, 3, 4, 5, 6, 7, 8],
                   'A': [9, 12, 15, 14, 19, 23, 25, 29],
                   'B': [5, 7, 7, 9, 12, 9, 9, 14],
                   'C': [5, 4, 7, 13, 15, 15, 18, 31]})

#plot columns on bar chart
df[['period', 'A', 'B', 'C']].plot(x='period', kind='bar')

Pandas plot multiple columns in bar chart

We could also choose to plot only certain columns, such as A and B:

df[['period', 'A', 'B']].plot(x='period', kind='bar')

Example 2: Plot Columns on a Stacked Bar Chart

To create a stacked bar chart, we simply need to specify stacked=True in the plot function:

import pandas as pd
import matplotlib.pyplot as plt

#create fake data
df = pd.DataFrame({'period': [1, 2, 3, 4, 5, 6, 7, 8],
                   'A': [9, 12, 15, 14, 19, 23, 25, 29],
                   'B': [5, 7, 7, 9, 12, 9, 9, 14],
                   'C': [5, 4, 7, 13, 15, 15, 18, 31]})

#create stacked bar chart
df[['period', 'A', 'B', 'C']].plot(x='period', kind='bar', stacked=True)

Stacked bar chart with pandas columns

To change the colors of the bars, simply use the color argument as follows:

df[['period', 'A', 'B', 'C']].plot(x='period', kind='bar', stacked=True,
                                   color=['red', 'pink', 'gold'])

x