Site icon FSIBLOG

Create a Colored Bar Graph Using Matplotlib in Python

Create a Colored Bar Graph Using Matplotlib in Python

Welcome to this coding tutorial! I am going to walk you through how to create a colored bar graph using Matplotlib in Python. We will start with the basics and then enhance our code to add more practical features.

Breakdown Project

Importing Matplotlib

First, we need to import the matplotlib.pyplot module, which will allow us to create visualizations.

import matplotlib.pyplot as plt

This imports pyplot from Matplotlib and assigns it an alias plt for easy reference.

Defining Data

Next, we define our categories and their corresponding values. We also define a list of colors to differentiate the bars.

categories = ['A', 'B', 'C', 'D', 'E']
values = [10, 15, 7, 12, 20]
colors = ['red', 'blue', 'green', 'orange', 'purple']

Creating the Bar Graph

Now, let’s create the bar graph using the plt.bar() function.

plt.bar(categories, values, color=colors)

Adding Labels and Title

To make our graph more informative, we add axis labels and a title.

plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Colored Bar Graph')

Displaying the Graph

Finally, we display the graph using:

plt.show()

This renders the graph on the screen.

Enhancing the Code with Practical Features

Now, let’s make our bar chart even more useful by adding the following features:

Improved Code with Additional Features

import matplotlib.pyplot as plt

# Define data
categories = ['A', 'B', 'C', 'D', 'E']
values = [10, 15, 7, 12, 20]
colors = ['red', 'blue', 'green', 'orange', 'purple']

# Sort bars by values (optional)
sorted_data = sorted(zip(values, categories, colors), reverse=True)
values, categories, colors = zip(*sorted_data)

# Create the bar chart
plt.figure(figsize=(8, 5))  # Adjust figure size
plt.bar(categories, values, color=colors)

# Add labels above each bar
for i, value in enumerate(values):
    plt.text(i, value + 0.5, str(value), ha='center', fontsize=12, fontweight='bold')

# Adding grid lines
plt.grid(axis='y', linestyle='--', alpha=0.7)

# Labels and Title
plt.xlabel('Categories', fontsize=12)
plt.ylabel('Values', fontsize=12)
plt.title('Enhanced Colored Bar Graph', fontsize=14)

# Show the graph
plt.show()

New Features Added:

Sorting the bars based on values (highest to lowest). Adding value labels on top of each bar. Custom figure size for better visualization. Grid lines for better readability. Bold labels and title for better presentation.

Alternate Horizontal Bar Graph

If you have long category names, a horizontal bar chart is a better option:

plt.barh(categories, values, color=colors)
for i, value in enumerate(values):
    plt.text(value + 1, i, str(value), va='center', fontsize=12, fontweight='bold')

plt.xlabel('Values', fontsize=12)
plt.ylabel('Categories', fontsize=12)
plt.title('Enhanced Horizontal Bar Graph', fontsize=14)
plt.grid(axis='x', linestyle='--', alpha=0.7)

plt.show()

Practical Use Cases

Business Analysis – Compare product sales, expenses, or market trends. Educational Purposes – Visualize student performance, survey results, or statistics. Scientific Research – Represent experimental data, growth trends, or categorical data.

Conclusion

I showed you how to create and enhance a colored bar graph using Matplotlib in Python. We started with a simple bar chart and then added practical features like sorting, labels, grid lines, and different graph types.

Exit mobile version