How to Annotate Horizontal Bar Plot Values Directly onto the Bars?

Linda Hamilton
Release: 2024-11-19 11:35:03
Original
803 people have browsed it

How to Annotate Horizontal Bar Plot Values Directly onto the Bars?

Annotating Bar Plot Values on Bars Horizontally

In visualization, it is often desirable to display the values of data elements on associated graphical representations. When working with horizontal bar plots, you may encounter the need to display the value of each bar directly on the bar itself. This can provide clarity and facilitate easy interpretation of data.

To address this need, you can incorporate additional code into your Matplotlib script. Here's how to achieve it based on your code snippet.

Update your code with the following lines:

# Calculate the x-coordinate for each bar value
x_values = y + 3

# Add text annotations to each bar
for i, v in enumerate(y):
    ax.text(x_values[i], i, str(v), color='blue', fontweight='bold', verticalalignment='center')
Copy after login

These code modifications add a loop that calculates the x-coordinate for each bar value, ensuring that the text labels are positioned correctly. The resulting plot will now display the values of each bar directly on the bars.

New in Matplotlib 3.4.0:

Matplotlib version 3.4.0 introduced a dedicated method for labeling bars directly:

bars = ax.barh(ind, y, width, color="blue")
ax.bar_label(bars, padding=3)
Copy after login

This method eliminates the need for custom annotations, providing a convenient and consistent way to label bars on a horizontal bar plot.

The above is the detailed content of How to Annotate Horizontal Bar Plot Values Directly onto the Bars?. 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