Home >Backend Development >Python Tutorial >How to Annotate Pandas Bar Plots with Rounded Numerical Values?

How to Annotate Pandas Bar Plots with Rounded Numerical Values?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 01:33:09316browse

How to Annotate Pandas Bar Plots with Rounded Numerical Values?

Annotating Pandas Bar Plots with Rounded Numerical Values

In a Pandas bar plot, annotating bars with the corresponding numerical values can enhance data visualization and provide insight into the plot's data. To address this, let's consider a DataFrame with random values:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': np.random.rand(2), 'B': np.random.rand(2)}, index=['value1', 'value2'])

Challenge: How can we annotate the bars with rounded numerical values, similar to the example image?

Solution:

Directly access the axes' patches to retrieve the bar height:

import matplotlib.pyplot as plt

ax = df.plot(kind='bar')
for p in ax.patches:
    height = p.get_height()
    label = round(height, 2)
    ax.annotate(label, (p.get_x() * 1.005, p.get_height() * 1.005))

This method obtains the bar's height from the patch object and annotates the bar with the rounded value. Adjust string formatting and offsets to center the annotations as desired.

Code Example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': np.random.rand(2), 'B': np.random.rand(2)}, index=['value1', 'value2'])
ax = df.plot(kind='bar')
for p in ax.patches:
    height = p.get_height()
    label = round(height, 2)
    ax.annotate(label, (p.get_x() * 1.005, p.get_height() * 1.005))

plt.show()

The above is the detailed content of How to Annotate Pandas Bar Plots with Rounded Numerical Values?. 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