Home  >  Article  >  Backend Development  >  How to Display Bar Values on a Matplotlib Horizontal Bar Chart?

How to Display Bar Values on a Matplotlib Horizontal Bar Chart?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-20 14:08:14309browse

How to Display Bar Values on a Matplotlib Horizontal Bar Chart?

Displaying Bar Values on Horizontal Bars

When creating a horizontal bar plot, it may be desirable to display the value of each bar on top of it. This guide provides a solution to achieve this functionality.

Consider the code snippet below that generates a bar plot without the values:

import matplotlib.pyplot as plt

x = ['INFO', 'CUISINE', 'TYPE_OF_PLACE', 'DRINK', 'PLACE', 'MEAL_TIME', 'DISH', 'NEIGHBOURHOOD']
y = [160, 167, 137, 18, 120, 36, 155, 130]

plt.barh(x, y, color='blue')
plt.yticks(x)
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')

To display the bar values on the plot, add the following code:

for i, v in enumerate(y):
    plt.text(v + 3, i, str(v), color='blue', fontweight='bold', verticalalignment='center')

In this code, the for loop iterates through the values in the y-list. For each value, it uses the plt.text function to display the value as a string at a specific position on the plot. The position is calculated by adding 3 to the value to space it slightly away from the bar and using i as the y-location.

The resulting plot will have the bar values displayed on top of each bar, as shown in the figure below:

[Image of the bar plot with values displayed on top]

The above is the detailed content of How to Display Bar Values on a Matplotlib Horizontal Bar Chart?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn