Pandas Plotting – How to Create a Horizontal Bar Chart

Spread the love

Create Horizontal Bar Chart –

Read a dataset to work with.

import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv"
df = pd.read_csv(url)
df.head()

And Group the data by Method of payment.

payment_sales = df.groupby('Method of Payment')['Net Sales'].sum().reset_index()

Now to plot a Horizontal bar Chart in pandas, we use the DataFrame.plot.barh() method.

payment_sales.plot.barh(x='Method of Payment', y='Net Sales', figsize=(8, 8));

To create a Horizontal Bar Chart, you can also use DataFrame.plot() method. All you have to do is set the kind parameter to kind=’barh’

payment_sales.plot(x='Method of Payment', y='Net Sales', kind='barh', figsize=(8, 8))

To color the Bars use the color parameter

bar_colors = ['red','blue','seagreen','crimson','gold']

payment_sales.plot.barh(x='Method of Payment', y='Net Sales', 
                        color=bar_colors, figsize=(10,8))

Grouped Horizontal Bar Chart –

url ="https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
df = pd.read_csv(url)
df.head()

Here, we have some data about cricket matches. And let’s say you want to know on average how many 4s and 6s hit by players of each teams.

To do that, first we need to calculate the average of 4s and 6s by each team

team_avg = df.groupby('Team')[['4s','6s']].mean()
team_avg

Then we need to visualize this data using Grouped Horizontal bar Chart.

team_avg.plot.barh(figsize=(10,8));

Stacked Horizontal Bar Chart –

To create a Stacked Horizontal Bar chart, all we need to do is set stacked=True.

team_avg.plot.barh(figsize=(10,8), stacked=True)

Create Subplots –

To create subplots set subplot=True

team_avg.plot.barh(figsize=(10,8), subplots=True)

Rating: 1 out of 5.

Leave a Reply