How to Create a Horizontal Bar Chart in Matplotlib

Spread the love

plt.barh() –

Let’s 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()

Now, calculate the total sales by Method of Payment.

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

To create a horizontal bar chart in matplotlib, we use the plt.barh() method.

import matplotlib.pyplot as plt
plt.figure(figsize=(10,8))
plt.barh(pay_sale['Method of Payment'], pay_sale['Net Sales'])
plt.xlabel('Total Sales', fontsize=14)
plt.ylabel('Method of Payment', fontsize=14)
plt.title('Total Sales By Payment Method', fontsize=16)
plt.show()

If you want to color the bars with different colors, use the color parameter.


bar_color = ['red','blue','green','crimson','yellow']
plt.figure(figsize=(10,8))
plt.barh(pay_sale['Method of Payment'], pay_sale['Net Sales'], color=bar_color)
plt.xlabel('Total Sales', fontsize=14)
plt.ylabel('Method of Payment', fontsize=14)
plt.title('Total Sales By Payment Method', fontsize=16)
plt.show()

And If you want you can also use different style sheets to make your plot look nicer.

plt.style.use('ggplot')

plt.figure(figsize=(10,8))
plt.barh(pay_sale['Method of Payment'], pay_sale['Net Sales'])
plt.xlabel('Total Sales', fontsize=14)
plt.ylabel('Method of Payment', fontsize=14)
plt.title('Total Sales By Payment Method', fontsize=16)
plt.show()

There are several styles that you can use which can be found here – Matplotlib style sheet

Rating: 1 out of 5.

Leave a Reply