Pandas Plotting – How to Create a Bar Chart in pandas.

Create a Bar Chart in Pandas –

Read a dataset to work with.

import pandas as pd
df.head()

Let’s group the data by Method of Payment.

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

To plot the a bar chart in pandas, we use the DataFrame.plot.bar() method.

payment_sales.plot.bar(x='Method of Payment', y='Net Sales', figsize=(10,7));

You can also use the DataFrame.plot() method to create a Bar chart in pandas. All you have to do is set the kind parameter to bar

payment_sales.plot(x='Method of Payment', y='Net Sales',kind='bar', figsize=(10,7));

If you want, you can also change the color of the bars using the color parameter.

bar_colors = ['red','blue','seagreen','crimson','gold']
payment_sales.plot.bar(x='Method of Payment', y='Net Sales',
color=bar_colors, figsize=(10,7));

Grouped Bar Chart –

You can also create a Grouped Bar chart in pandas.

url ="https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
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 create a Grouped Bar chart to visualize this data.

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

Stacked Bar Chart –

To create a stacked bar chart all you have to do is set stacked=True

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

Subplots –

To create subplots set subplots=True

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

Rating: 1 out of 5.