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!