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
Release: 2024-12-26 01:33:09
Original
284 people have browsed it

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'])
Copy after login

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))
Copy after login

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()
Copy after login

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!

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