Bar graph/chart is a common type of visualization used to present categorical data using rectangular bars. Bar charts come in different types such as vertical, horizontal, stacked (either vertical or horizontal), grouped and 100% stacked bar charts. It is used to compare the relative sizes between two or more categories of data. In this post we will look at Bar Graphs and how to create Bar Graph With Matplotlib.

matplotlib-logo

When to Use Bar Graph

  1. Compare between two or more different groups in data.
  2. Track change over time. Note: Suitable when the changes are too large otherwise use line graph.

How to Use Bar Graph

  1. Bars should be of same type. Avoid mixing 3D and 2-D bars.
  2. The scale of values should always start from zero unless otherwise.
  3. Select the colours to use carefully.
  4. Order the bars with some criteria that best presents the insights.
  5. To maximise the visibility and appearance of all components use different variations of bar charts (vertical, horizontal, grouped etc.).
  6. Include values in the bars for users to make actual comparison between groups.

Bar Graph in Matplotlib

Create DataFrame

                    

# Load required libraries

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

plt.style.use(‘ggplot’) # Other sytles to use; fivethirtyeight

score_df = pd.DataFrame(
    {
        "Students": ["Tom", "Peter","Simon", "Mary", "Jane","King","Hillary","Ethan","Page"],
        "Math": [79.00, 67.00,80.00, 84.00, 70.00,60.00,90.00,76.00,75],
        "Physics":[63.00, 98, 60.00, 90,84.00, 77.00,55.00,70,66.00],
        "Computer":[84.00,78.00, 57.00, 88.00, 75.00,93.00,92.00,98.00,90.00],
    },
    index=["Tom", "Peter","Simon", "Mary", "Jane","King","Hillary","Ethan","Page"]
)

score_df['Total']=score_df[['Math','Physics','Computer']].apply(np.sum,axis=1)
score_df

matplotlib-data

Simple Bar Graph

                    

plt.figure(figsize=(20,10)) # Set figure size
plt.bar(score_df['Students'],score_df['Total'],color='skyblue')
plt.title('Students Score',fontsize=24)
plt.xticks(rotation=45)
plt.xlabel('Students',fontsize=24)
plt.ylabel('Score',fontsize=24)
plt.show()

matplotlib-simple-bar-chart

Add Labels

                    

def addlabels(x,y):
    for i in range(len(x)):
        plt.text(i, y[i], y[i], ha = 'center') 
    
plt.figure(figsize=(20,10)) # Set figure size
plt.bar(score_df['Students'],score_df['Total'],color='skyblue')
addlabels(score_df['Students'],score_df['Total'])
plt.title('Students Score',fontsize=24)
plt.xticks(rotation=45)
plt.xlabel('Students',fontsize=24)
plt.ylabel('Score',fontsize=24)
plt.show()

matplotlib-simple-bar-chart-with-top-labels

Add Labels at the middle

                    

def addlabels(x,y):
    for i in range(len(x)):
        plt.text(i, y[i]//2, y[i], ha = 'center')
    
plt.figure(figsize=(20,10)) # Set figure size
plt.bar(score_df['Students'],score_df['Total'],color='skyblue')
addlabels(score_df['Students'],score_df['Total'])
plt.title('Students Score',fontsize=24)
plt.xticks(rotation=45)
plt.xlabel('Students',fontsize=24)
plt.ylabel('Score',fontsize=24)
plt.show()

matplotlib-simple-bar-chart-with-center-labels

Horizontal Simple Bar Graph

                    

plt.figure(figsize=(20,15)) # Set figure size
plt.barh(score_df['Students'],score_df['Total'],color='skyblue')
plt.title('Students Score',fontsize=24)
plt.xticks(rotation=45)
plt.xlabel('Students',fontsize=24)
plt.ylabel('Score',fontsize=24)
plt.show()

matplotlib-simple-horizontal-bar-chart

Grouped Bar Chart

                    

score_df[['Math','Physics','Computer']].plot(kind="bar",figsize=(20, 10))

plt.title('Students Score',fontsize=24)
plt.xticks(rotation=45)
plt.xlabel('Students',fontsize=24)
plt.ylabel('Score',fontsize=24)
plt.show()

matplotlib-grouped-vertical-bar-chart

Stacked Bar Chart

                    

score_df[['Math','Physics','Computer']].plot(kind="bar",stacked=True,figsize=(20, 10))
plt.title('Students Score',fontsize=24)
plt.xticks(rotation=45)
plt.xlabel('Students',fontsize=24)
plt.ylabel('Score',fontsize=24)
plt.show()

matplotlib-stacked-vertical-bar-chart

For complete code check the jupyter notebook here.

Conclusion

Bar charts are important type of visualizations for presenting data with discrete groups. They are used to compare relative relationship between categories with bars. They are also useful in showing trend between large time intervals. In this post we have looked at what’s bar chart, when to use them and how to use them with Matplotlib. In the next post we will look at Pie Charts and how to use them in Matplotlib. To learn about line graph check our previous post here.

Bar Graph With Matplotlib

Post navigation


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x