Home >Backend Development >Python Tutorial >How to Display Data Values on Horizontal Bars in Matplotlib?

How to Display Data Values on Horizontal Bars in Matplotlib?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 13:11:11567browse

How to Display Data Values on Horizontal Bars in Matplotlib?

How to Utilize Text to Display Values on Horizontal Bars

Bar plots are widely used for visual data representation, but sometimes it becomes crucial to display the exact values on each bar for enhanced data interpretation. While matplotlib does not provide an out-of-the-box solution for this, a simple modification to your code can enable this functionality.

To incorporate values on horizontal bars, you can utilize the ax.text() method. By iterating through the data values (y), you can add text to each bar, specifying the x-location (v 3) and y-location (i). Here's the updated code:

import os
import numpy as np
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()    
width = 0.75 # the width of the bars 
ind = np.arange(len(y))  # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')      

# Add text to display values on bars
for i, v in enumerate(y):
    ax.text(v + 3, i, str(v), color='blue', fontweight='bold', verticalalignment='center')

#plt.show()
plt.savefig(os.path.join('test.png'), dpi=300, format='png', bbox_inches='tight') # use format='svg' or 'pdf' for vectorial pictures

This modification will place the values slightly to the right of each bar, providing a clear visual representation of the data.

The above is the detailed content of How to Display Data Values on Horizontal Bars in Matplotlib?. 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