Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make horizontal bar graph in matplotlib

Understanding Matplotlib

Before we dive into creating horizontal bar graphs, let's take a moment to understand what Matplotlib is. Matplotlib is a plotting library for the Python programming language that allows you to create a wide variety of static, animated, and interactive visualizations. Think of it as a tool that helps you paint a picture with data.

Setting Up Your Environment

To get started with Matplotlib, you need to have it installed on your computer. If you haven't done so, you can install it using pip, which is the package installer for Python:

pip install matplotlib

Once Matplotlib is installed, you will need to import it in your Python script to use its functions. The most common way to import Matplotlib is like this:

import matplotlib.pyplot as plt

Here, plt is a commonly used alias for matplotlib.pyplot. It's like giving a nickname to a friend to call them more easily.

The Basics of a Horizontal Bar Graph

A horizontal bar graph is a visual representation of data where bars are plotted horizontally, and the length of each bar is proportional to the value it represents. It's like a race track where each runner (bar) starts at the same point, but the distance they run (the length of the bar) depends on their speed (the value of the data).

Creating a Simple Horizontal Bar Graph

Let's start with a simple example. Imagine you have a list of fruits and the number of each fruit you ate last week. You want to visualize this data with a horizontal bar graph.

fruits = ['Apples', 'Bananas', 'Cherries', 'Dates', 'Elderberries']
quantities = [5, 7, 3, 2, 4]

plt.barh(fruits, quantities)

In this code, fruits is a list of fruit names, and quantities is a list of how many of each fruit you ate. The plt.barh() function is where the magic happens: it creates a horizontal bar graph with the data provided. The function then displays the graph.

Customizing Your Graph

The graph you just created is quite basic. Let's add some customizations to make it more informative and appealing.

Adding Labels and Title

plt.barh(fruits, quantities, color='skyblue')
plt.title('Fruit Consumption Last Week')

Here, we've added labels to the x-axis (plt.xlabel()) and y-axis (plt.ylabel()), as well as a title (plt.title()) to the graph. We've also changed the color of the bars to sky blue for a touch of style.

Adjusting the Bar Thickness

Sometimes, you might want the bars to be thicker or thinner. You can adjust the bar thickness by using the height parameter.

plt.barh(fruits, quantities, height=0.5)  # Makes the bars thinner

Sorting the Bars

Sorting the bars can make your graph easier to read, especially when dealing with many data points.

# Combine the fruits and quantities into a list of tuples
combined = list(zip(quantities, fruits))

# Sort the list by the quantity

# Unzip the list back into two lists
quantities_sorted, fruits_sorted = zip(*combined)

plt.barh(fruits_sorted, quantities_sorted)

In this block of code, we first pair each fruit with its corresponding quantity using zip(). We then sort this list of tuples, and finally, we unzip it back into two separate lists, now sorted by quantity. When we plot these, the bars will be sorted in ascending order.

Adding Finishing Touches

Let's add some finishing touches to make our graph look professional.

Adding Value Labels to Bars

It's helpful to have the exact values on the bars themselves:

plt.barh(fruits_sorted, quantities_sorted, color='green')

for index, value in enumerate(quantities_sorted):
    plt.text(value, index, str(value))

Here, we loop through the sorted quantities with enumerate(), which gives us both the index and the value. We then use plt.text() to place the text (the value) on the graph.

Fine-Tuning with Style

Matplotlib comes with various styles that you can use to quickly change the look of your graphs. To set a style, you use'ggplot')
plt.barh(fruits_sorted, quantities_sorted)

Now, your graph will have the 'ggplot' style, which is inspired by the ggplot2 library in the R programming language.


Creating a horizontal bar graph in Matplotlib is like telling a story with your data. With the simple yet powerful tools provided by Matplotlib, you can transform raw numbers into compelling visual narratives that are easy to understand at a glance. Whether you're keeping track of your fruit consumption or analyzing more complex datasets, horizontal bar graphs are a versatile way to present information clearly and effectively.

Remember, the key to a great graph is not just the data it represents, but also how it communicates that data. The customizations and styles available in Matplotlib allow you to fine-tune your graphs to convey your message in the most impactful way possible. So go ahead, play around with the colors, styles, and layouts, and turn your data into a masterpiece that even the least tech-savvy viewer can appreciate.