No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Plot Bar Graph with Python and matplotlib

by Khaleel O.
July 27, 2021
in Python
Reading Time: 5 mins read
A A
plot bar graph python matplotlib
plot bar graph python matplotlib

In this tutorial we will plot a bar graph with Python and matplotlib. Remember that histograms are used to show distributions of variables while bar graphs are used to compare variables. In this example, our bar graph will compare categories of variables by count.

First, let us install the library (if you don’t already have it):

python -m pip install -U matplotlib

Now, let’s write our starter code:

import matplotlib.pyplot as plt
import pandas as pd
  
df = pd.DataFrame({'CLASS_TYPES': ['A','A','A','B','B',
       'C','C','C','D','E',
       'E','F','F','F','F',
       'G','G','G','G','G']})

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
classTypes = ['A','B','C','D','E','F','G']
classCount = [len(df[df.CLASS_TYPES == 'A']),
              len(df[df.CLASS_TYPES == 'B']),
              len(df[df.CLASS_TYPES == 'C']),
              len(df[df.CLASS_TYPES == 'D']),
              len(df[df.CLASS_TYPES == 'E']),
              len(df[df.CLASS_TYPES == 'F']),
              len(df[df.CLASS_TYPES == 'G'])]

ax.bar(classTypes,classCount)
plt.show()

Let’s explain what’s going on here:

  1. matplotlib.pyplot is mainly intended for interactive plots and simple cases of programmatic plot generation in python.
  2. df is our sample test dataframe that we will use to build our bar plot. We have one column of classes/categories called CLASS_TYPES. There are 7 classes in our dataset: A, B, C, D, E, F and G. Each of these classes will appear more than once in our dataset.
  3. plt.figure() is the top level container for all the plot elements.
  4. fig.add_axes([0,0,1,1]) adds axes to the figure. The parameter supplied, [0,0,1,1], is a sequence of float that represents the dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
  5. classTypes will be our individual bars or categories on the plot. This will appear on the x axis. They are our variables.
  6. classCount is the counts of each category or variable that will appear on the y axis.
  7. ax.bar(classTypes,classCount) makes the bar plot/bar graph. classTypes will appear on the x or horizontal axis and our counts of each category or class will appear on the y or vertical axis.

Once we execute our simple script, we get our bar plot/bar graph:

plot bar graph python matplotlib
A Simple Bar Graph with matplotlib

At a glance, we can easily compare the counts of our classes/categories/variables. The ability to do this is one main advantage of bar graphs. On the x-axis we have the categories and on the y-axis we have counts of each category.

We can actually improve this bar graph by adding data labels to the bars so that consumers of the data don’t have to guess each count of each category. We can re-write our code as the following to achieve this:

import matplotlib.pyplot as plt
import pandas as pd
  
df = pd.DataFrame({'CLASS_TYPES': ['A','A','A','B','B',
       'C','C','C','D','E',
       'E','F','F','F','F',
       'G','G','G','G','G']})

fig = plt.figure()
ax = fig.add_axes([0,0,1.5,1.5])
classTypes = ['A','B','C','D','E','F','G']
classCount = [len(df[df.CLASS_TYPES == 'A']),
              len(df[df.CLASS_TYPES == 'B']),
              len(df[df.CLASS_TYPES == 'C']),
              len(df[df.CLASS_TYPES == 'D']),
              len(df[df.CLASS_TYPES == 'E']),
              len(df[df.CLASS_TYPES == 'F']),
              len(df[df.CLASS_TYPES == 'G'])]

ax.bar(classTypes,classCount)

for x,y in zip(classTypes,classCount): #to add data labels

    label = "{:.2f}".format(y)

    plt.annotate(label, # label text
                 (x,y), # The point (x, y) to annotate
                 textcoords="offset points", # offset (in points) from the xy value
                 xytext=(0,10), # position (x, y) to place the text at. 
                 ha='center') # horizontal alignment is center in this case
            
plt.show()

Everything is the same except that we added a FOR-loop that will apply the data labels to the top center of each bar in our plot.

  1. The plt.annotate() method allows us to annotate the point provided with text.
  2. In this case, we choose to annotate with the data label but it can be anything else.
  3. The FOR loop allows us to add annotation to each bar in our bar plot one after the other.
  4. The plt.annotate() method requires that we supply the label text, the point to annotate and a few other parameters in order to show the intended result. We will place the data labels a little above each bar.

Now we have:

plot bar graph python matplotlib
A Simple Bar Graph with matplotlib with Data Labels

A little better right? ✨✨ Now we can go even further and add color to our bar graph so that we can differentiate the classes. Using the same color gets repetitive after a while. Fortunately, this is simple! By changing one line in our code we can add some color to our graph:

ax.bar(classTypes,classCount,color=['#ffadad', '#ffd6a5', '#fdffb6', '#caffbf', '#ffc6ff','#9bf6ff','#a0c4ff'])

By adding the color parameter to the ax.bar() method we can change the color of the bar faces. Now we have:

plot bar graph python matplotlib
A Simple Bar Graph with matplotlib with Data Labels with Color

Please check our other tutorial on Python Bar Plots.

You can find the full source code at GitHub HERE. Thanks for reading! Good luck 👌👌👌.

Tags: bar graphbar plotmatplotlib
Previous Post

Python List Comprehension Nested For Loops

Next Post

Stacked Bar Plot with Python

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy