Home > Backend Development > Python Tutorial > How Can I Display Values on a Horizontal Bar Plot in Matplotlib?

How Can I Display Values on a Horizontal Bar Plot in Matplotlib?

Mary-Kate Olsen
Release: 2024-11-27 17:16:12
Original
390 people have browsed it

How Can I Display Values on a Horizontal Bar Plot in Matplotlib?

Displaying Values on Horizontal Bars

To display the value of each bar in a horizontal bar plot, you can use the following method:

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

Explanation:

  1. Iterate through the y-values.
  2. For each y-value, plot text to the right of the bar by adding 3 to the y-value.
  3. Use the index of each y-value as the y-coordinate for the text.
  4. Set the text to be the y-value as a string.
  5. Style the text as desired (e.g., blue color, bold weight, centered vertically).

Example:

# Update the x and y values from the original example
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 code to display the values on the bars
for i, v in enumerate(y):
    ax.text(v + 3, i, str(v), color='blue', fontweight='bold', verticalalignment='center')

# Display the plot
plt.show()
Copy after login

This will produce a horizontal bar plot with the values displayed on top of each bar.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template