How can I plot multiple columns on a bar chart using Pandas?

The process of plotting multiple columns on a bar chart using Pandas involves utilizing the Pandas library in Python to create a data frame from a given dataset. This data frame can then be used to generate a bar chart using the built-in plotting function. The columns to be included in the chart can be specified by selecting the desired columns from the data frame. The resulting bar chart will display the data from each selected column in a visually appealing and easy-to-compare format. This method is useful for visualizing and analyzing multiple data points simultaneously, making it a valuable tool for data analysis and presentation.

Pandas: Plot Multiple Columns on Bar Chart


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.pyplotas 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.pyplotas 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'])

Additional Resources

x