Home » Tutorial on Creating Bar Graphs in Matplotlib

Tutorial on Creating Bar Graphs in Matplotlib

Spring Framework Basics Video Course
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

Bar graphs are a versatile and commonly used plot type in data visualization.

They are useful for comparing categorical data, showing distribution, or illustrating changes over time.

Matplotlib’s bar function provides a lot of customization options for creating both vertical and horizontal bar graphs, grouped and stacked bar charts, and customizations with color, patterns, and error bars.

In this tutorial, we’ll explore how to create and customize bar graphs in Matplotlib with examples covering the basics as well as more advanced features.

1. Basic Vertical Bar Graph

The simplest bar graph can be created using the bar function, which takes two main arguments: the x-coordinates and the heights of the bars.

import matplotlib.pyplot as plt
import numpy as np

# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values = [5, 7, 2, 9, 6]

# Create a basic vertical bar graph
plt.figure(figsize=(8, 5))
plt.bar(categories, values, color='skyblue')
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Basic Vertical Bar Graph")
plt.show()

In this example:

  • The bar function takes categories for the x-axis and values for the height of each bar.
  • color='skyblue' sets the color of the bars.

2. Horizontal Bar Graph

A horizontal bar graph can be created using the barh function. This is useful when you have long category names or when displaying a rank-based comparison.

# Create a basic horizontal bar graph
plt.figure(figsize=(8, 5))
plt.barh(categories, values, color='coral')
plt.xlabel("Values")
plt.ylabel("Categories")
plt.title("Basic Horizontal Bar Graph")
plt.show()

In this example:

  • The barh function is used instead of bar, placing categories on the y-axis and values on the x-axis.

3. Adding Colors, Patterns, and Labels to Bars

You can customize the appearance of each bar individually by using a list of colors or adding patterns, and you can add value labels on top of each bar.

# Custom colors and patterns
colors = ['skyblue', 'orange', 'green', 'purple', 'red']

plt.figure(figsize=(8, 5))
bars = plt.bar(categories, values, color=colors, edgecolor='black', hatch='/')

# Add value labels on top of each bar
for bar in bars:
    plt.text(bar.get_x() + bar.get_width() / 2, bar.get_height() - 0.5,
             str(bar.get_height()), ha='center', color='white')

plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Graph with Custom Colors, Patterns, and Labels")
plt.show()

In this example:

  • color=colors applies a different color to each bar.
  • edgecolor='black' and hatch='/' add a black border and diagonal pattern to the bars.
  • plt.text() places value labels near the top of each bar.

4. Grouped Bar Graph

A grouped bar graph is useful when you want to compare multiple series for each category. Here’s how to create a grouped bar chart with two data series.

# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values1 = [5, 7, 2, 9, 6]
values2 = [4, 3, 8, 5, 7]

x = np.arange(len(categories))  # Create a range of values for the x-axis
width = 0.35  # Width of each bar

# Create grouped bar chart
plt.figure(figsize=(10, 6))
plt.bar(x - width/2, values1, width, label='Series 1', color='lightblue')
plt.bar(x + width/2, values2, width, label='Series 2', color='salmon')

plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Grouped Bar Graph")
plt.xticks(x, categories)  # Set the x-tick labels
plt.legend()
plt.show()

In this example:

  • Two bars are plotted for each category by offsetting the x positions (x – width/2 and x + width/2).
  • width=0.35 controls the width of each bar, and plt.xticks(x, categories) sets the category names as x-axis labels.

5. Stacked Bar Graph

A stacked bar graph shows the total value for each category with portions corresponding to different series.

# Create stacked bar chart
plt.figure(figsize=(10, 6))
plt.bar(categories, values1, label='Series 1', color='lightgreen')
plt.bar(categories, values2, bottom=values1, label='Series 2', color='coral')

plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Stacked Bar Graph")
plt.legend()
plt.show()

In this example:

  • The bottom=values1 argument in the second bar function stacks values2 on top of values1.
  • This approach shows the cumulative values while allowing comparison within each category.

6. Adding Error Bars to Bar Graphs

Error bars represent variability or uncertainty in the data. You can add error bars to each bar in a bar graph.

# Sample data with error margins
errors = [0.5, 0.7, 0.2, 0.4, 0.6]

plt.figure(figsize=(8, 5))
plt.bar(categories, values, yerr=errors, capsize=5, color='lightblue', edgecolor='black')

plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Graph with Error Bars")
plt.show()

In this example:

  • yerr=errors specifies the error values for each bar.
  • capsize=5 adds caps to the error bars, making them more visible.

7. Creating a Bar Graph with Colors Based on Value

You can use conditional formatting to apply different colors based on the value of each bar. This is useful to highlight specific values.

# Color bars based on value
colors = ['green' if value > 5 else 'red' for value in values]

plt.figure(figsize=(8, 5))
plt.bar(categories, values, color=colors)
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Graph with Conditional Colors")
plt.show()

In this example:

  • A list comprehension assigns ‘green' for values greater than 5 and ‘red' otherwise.

8. Horizontal Grouped and Stacked Bar Graphs

You can also create horizontal versions of grouped and stacked bar graphs.

Horizontal Grouped Bar Graph

plt.figure(figsize=(10, 6))
plt.barh(x - width/2, values1, width, label='Series 1', color='lightblue')
plt.barh(x + width/2, values2, width, label='Series 2', color='salmon')

plt.ylabel("Categories")
plt.xlabel("Values")
plt.title("Horizontal Grouped Bar Graph")
plt.yticks(x, categories)
plt.legend()
plt.show()

Horizontal Stacked Bar Graph

plt.figure(figsize=(10, 6))
plt.barh(categories, values1, label='Series 1', color='lightgreen')
plt.barh(categories, values2, left=values1, label='Series 2', color='coral')

plt.xlabel("Values")
plt.ylabel("Categories")
plt.title("Horizontal Stacked Bar Graph")
plt.legend()
plt.show()

In these examples:

  • The barh function is used instead of bar for horizontal orientation.
  • left=values1 in the second bar plots creates a stacked effect in the horizontal orientation.

9. Bar Graph with Custom Ticks and Labels

You can create custom ticks and labels to enhance readability. Here’s an example using rotated labels.

# Sample data with long category names
categories = ['Category A', 'Category B', 'Category C', 'Category D', 'Category E']
values = [5, 7, 2, 9, 6]

plt.figure(figsize=(10, 6))
plt.bar(categories, values, color='teal')
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Graph with Custom Ticks and Labels")
plt.xticks(rotation=45, ha="right")  # Rotate labels for readability
plt.show()

In this example:

  • plt.xticks(rotation=45, ha=”right”) rotates the x-axis labels by 45 degrees and aligns them to the right to make them readable.

10. Adding Annotations and Legends to Bar Graphs

Annotations can help in conveying information clearly by adding labels or values directly on the bars.

# Annotate bars with values and add legend
plt.figure(figsize=(8, 5))
bars = plt.bar(categories, values, color='plum', label="Value")

# Annotate each bar with its value
for bar in bars:
    plt.text(bar.get_x() + bar.get_width() / 2, bar.get_height() - 0.5,
             str(bar.get_height()), ha='center', color='white', fontweight='bold')

plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Graph with Annotations")
plt.legend()
plt.show()

In this example:

  • `plt

.text()` is used to place the value at the top of each bar for annotation.

Summary

In this tutorial, we covered a variety of ways to create and customize bar graphs using Matplotlib:

  1. Basic Vertical and Horizontal Bar Graphs to get started with bar plots.
  2. Adding Colors, Patterns, and Labels for visual customization.
  3. Grouped and Stacked Bar Graphs to compare multiple series in the same chart.
  4. Adding Error Bars to represent variability.
  5. Conditional Colors based on values to highlight specific bars.
  6. Horizontal Grouped and Stacked Bar Graphs to add versatility.
  7. Custom Ticks and Labels for readability.
  8. Annotations to add value labels directly on bars.

These examples demonstrate how bar graphs can be tailored for different data visualization needs, from basic comparisons to detailed, annotated, and interactive representations.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More