Home >Backend Development >Python Tutorial >How to Annotate Horizontal Bar Plot Values Directly onto the Bars?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 11:35:03877browse

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')

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)

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!

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