Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make a bar chart in matplotlib

Understanding Bar Charts

Before we dive into the code, let's understand what a bar chart is. Imagine a bar chart as a group of vertical or horizontal rectangles where the length or height of each rectangle is proportional to the value it represents. It's like looking at a city skyline where each building's height tells you how tall it is - the taller the building, the higher the value.

Setting Up Your Environment

To start creating bar charts, you need to set up your programming environment. If you haven't already, you'll need to install Python and then add the matplotlib library, which is a collection of command-style functions that make matplotlib work like MATLAB (a high-level language and interactive environment for numerical computation, visualization, and programming).

You can install matplotlib by running the following command in your terminal or command prompt:

pip install matplotlib

Your First Bar Chart

Let's create a simple bar chart. We'll need some data to represent. For instance, let's say we want to visualize the popularity of different programming languages.

Here's how you could set up your data:

languages = ['Python', 'Java', 'C++', 'JavaScript', 'C#']
popularity = [100, 90, 80, 95, 85]

And here's the basic code to generate a bar chart:

import matplotlib.pyplot as plt

# Data
languages = ['Python', 'Java', 'C++', 'JavaScript', 'C#']
popularity = [100, 90, 80, 95, 85]

# Creating the bar chart
plt.bar(languages, popularity)

# Displaying the bar chart
plt.show()

When you run this code, a window will pop up displaying your bar chart.

Customizing the Chart

The chart we've just made is pretty basic. Let's add a title, and labels to our x-axis and y-axis to make it more informative.

# Creating the bar chart with titles and labels
plt.bar(languages, popularity)

# Adding a title
plt.title('Programming Language Popularity')

# Adding labels
plt.xlabel('Languages')
plt.ylabel('Popularity Score')

# Displaying the bar chart
plt.show()

Now, when you run the code, you'll see the chart with a title and labeled axes.

Changing Bar Colors and Patterns

A bar chart with different colors or patterns can be more visually appealing and can also help differentiate between bars. Let's change the colors of our bars.

# Creating the bar chart with different colors
colors = ['blue', 'green', 'red', 'purple', 'orange']
plt.bar(languages, popularity, color=colors)

# Adding a title and labels
plt.title('Programming Language Popularity')
plt.xlabel('Languages')
plt.ylabel('Popularity Score')

# Displaying the bar chart
plt.show()

Adding Text Labels on Bars

Sometimes, you might want to display the actual value on top of each bar. This can be done by iterating over each bar and using the text function.

# Creating the bar chart
bars = plt.bar(languages, popularity, color=colors)

# Adding text labels on each bar
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2, yval + 1, yval, ha='center', va='bottom')

# Adding a title and labels
plt.title('Programming Language Popularity')
plt.xlabel('Languages')
plt.ylabel('Popularity Score')

# Displaying the bar chart
plt.show()

Horizontal Bar Charts

Sometimes, a horizontal bar chart can be more appropriate, especially if you have long category names. Here's how you can create a horizontal bar chart:

# Creating the horizontal bar chart
plt.barh(languages, popularity, color=colors)

# Adding a title and labels
plt.title('Programming Language Popularity')
plt.xlabel('Popularity Score')
plt.ylabel('Languages')

# Displaying the bar chart
plt.show()

Making Your Chart Interactive

matplotlib also allows you to make your charts interactive. You can zoom in, pan the chart, or even save it as an image. This functionality is built-in and requires no additional code. When you display the chart using plt.show(), you can use the interactive tools in the toolbar that appears in the window.

Understanding the Code

Let's break down the code we've been using. We import matplotlib.pyplot as plt, which is a module in matplotlib that contains functions that allow you to create, customize, and display different kinds of plots and charts. We then create a list of languages and their corresponding popularity scores, which serve as our data. The plt.bar() function is then used to create the bar chart, with languages as the x-axis and popularity as the y-axis values. Finally, we use plt.show() to display the chart.

Conclusion

Creating bar charts with matplotlib is like building with LEGO blocks. You start with the basic structure and keep adding pieces until it looks exactly how you want it. We've gone through setting up your environment, creating a basic bar chart, customizing it with colors, labels, and text, and even changing its orientation. By now, you should feel confident in your ability to visualize data with bar charts.

Remember, the key to learning programming is practice. So, go ahead and experiment with different datasets, styles, and configurations. Try to visualize the data in a way that tells a story or highlights the information you find most interesting. With each new chart you create, you'll be building not just bars, but your programming skills as well. Happy coding!