Chakradhar Kalla
Chakradhar Kalla

Reputation: 21

How to place the values on the bar plot (some vertically and some horizontally)?

WHAT I HAVE WHAT I WANT

I want the values to be inserted on the bars and they should be adjusted accordingly so that they appear clear. ( Some of them should be vertical and some of them should be horizontal )

x2 = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
y3 = []
for value in x2:
    y3.append((df[value].sum())/(len(df[value])))

plt.bar(x2,y3,color=('lightblue','salmon'))

for i,v in enumerate(y3):
    plt.text(i-.25,v+1,str(v),fontsize=6)

plt.show()

Upvotes: 1

Views: 49

Answers (1)

MuhammedYunus
MuhammedYunus

Reputation: 5065

Consider the layout below, which is similar to the suggestion by @rehaqds.

enter image description here

You can also hide labels, like the smaller values - see this question.

Reproducible example

Many arguments are optional (like colours, font size, etc), but I included them to reveal how you can easily tune the layout to your preferences.

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

# Data for testing
months = pd.date_range(start='Jan 2024', end='Dec 2024', freq='MS')
month_names = months.strftime('%b').tolist()

rainfall = np.array([2, 3, 4, 5, 7, 14, 25, 21, 14, 7, 4, 2]) * 10 + np.random.randn(12) * 2
mean_rainfall = rainfall.mean()

#
#Plot
#

#Create ax to plot on
f, ax = plt.subplots(figsize=(7, 3), layout='tight')

#Bar plot
bars = ax.bar(month_names, rainfall, color='lightblue', edgecolor='black', linewidth=0.5)

#Label the bars using bar_label
ax.bar_label(
    bars,
    rotation=45, label_type='edge', padding=2,
    fontsize=8, fontweight='bold', color='tab:blue', 
    fmt='{:.0f}'
)

#Mean
ax.axhline(mean_rainfall, linestyle=':', lw=1, color='darkred', label='mean rainfall')
ax.legend()

#Formatting
ax.set(xlabel='Month', ylabel='Rainfall (mm)', title='Average Monthly Rainfall\n')
ax.spines[['top', 'right']].set_visible(False)

Upvotes: 0

Related Questions