Draw a horizontal bar chart with Matplotlib
×


Draw a horizontal bar chart with Matplotlib

772

Visualizing Data with Horizontal Bar Charts in Matplotlib

Matplotlib is a powerful library in Python that allows you to create a wide variety of static, animated, and interactive plots. One of the most common visualizations is the bar chart, which is useful for comparing quantities across different categories. While vertical bar charts are widely used, horizontal bar charts can be more effective when dealing with long category names or when you want to emphasize the comparison between categories.

Creating a Basic Horizontal Bar Chart

To create a horizontal bar chart in Matplotlib, you can use the barh() function. Here's a simple example:

import matplotlib.pyplot as plt

categories = ['Apple', 'Banana', 'Cherry', 'Date']
values = [10, 15, 7, 5]

plt.barh(categories, values)
plt.xlabel('Quantity')
plt.ylabel('Fruit')
plt.title('Fruit Quantities')
plt.show()

In this example, the categories list contains the names of the fruits, and the values list contains the corresponding quantities. The barh() function creates a horizontal bar chart, and the xlabel(), ylabel(), and title() functions add labels to the x-axis, y-axis, and the chart title, respectively.

Customizing the Appearance

Matplotlib provides several options to customize the appearance of your bar chart. You can change the color of the bars, add a grid, or adjust the width of the bars. Here's an example with some customizations:

plt.barh(categories, values, color='skyblue', edgecolor='black')
plt.xlabel('Quantity')
plt.ylabel('Fruit')
plt.title('Fruit Quantities')
plt.grid(True, axis='x', linestyle='--', alpha=0.7)
plt.show()

In this example, the color parameter sets the color of the bars, and the edgecolor parameter sets the color of the bar borders. The grid() function adds a grid to the x-axis with a dashed line style and a transparency level of 0.7.

Adding Data Labels

Adding data labels to your bar chart can make it easier for viewers to understand the exact values represented by each bar. Here's how you can add data labels:

bars = plt.barh(categories, values, color='lightgreen', edgecolor='black')
plt.xlabel('Quantity')
plt.ylabel('Fruit')
plt.title('Fruit Quantities')

for bar in bars:
    plt.text(bar.get_width() - 0.5, bar.get_y() + bar.get_height() / 2,
             str(bar.get_width()), va='center', ha='right', color='black')

plt.show()

In this example, we iterate over each bar in the chart and use the text() function to add the value at the end of each bar. The get_width() method retrieves the width of the bar (i.e., the value), and the get_y() and get_height() methods determine the position of the label.

Sorting the Bars

Sorting the bars can make your chart more readable, especially when dealing with a large number of categories. Here's how you can sort the bars in descending order:

sorted_categories, sorted_values = zip(*sorted(zip(values, categories), reverse=True))
plt.barh(sorted_categories, sorted_values, color='lightcoral', edgecolor='black')
plt.xlabel('Quantity')
plt.ylabel('Fruit')
plt.title('Fruit Quantities')
plt.show()

In this example, we use the zip() function to pair each value with its corresponding category, then sort these pairs in descending order using the sorted() function. The zip(*sorted(...)) idiom unzips the sorted pairs back into two separate lists: sorted_categories and sorted_values.

Conclusion

Horizontal bar charts are a versatile tool for visualizing categorical data, especially when category names are long or when you want to emphasize the comparison between categories. Matplotlib makes it easy to create and customize these charts to suit your needs. By experimenting with different customizations, you can create clear and informative visualizations that effectively communicate your data.


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat