Skip to content Skip to sidebar Skip to footer

How To Get The Associated Axis Of A Bar Chart In Python Matplotlib

I am learning Matplotlib through practice and have created 2 subplots in a figure and drew two bar charts. I tried adding the height using text function using 2 nested for loops. H

Solution 1:

You can use ax.text(x, y, s, ...) (see here) directly:

rns = np.random.randn(50)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6))
barg = ax1.bar(range(50), rns)
barg2 = ax2.bar(range(50), rns**2)


for x, y inzip(range(50), rns):
    ax1.text(x, y, str(np.round(y, 1)) + '%', ha='center', rotation='vertical', fontsize='small')
    ax2.text(x, y**2, str(np.round(y, 1)) + '%', ha='center', rotation='vertical', fontsize='small')

will get you

enter image description here

You could now increase the figsize and then change the fontsize accordingly to get a better looking figure (if you click on it):

# Parameters for picture below:
figsize=(20, 12)
fontsize='large'str(np.round(y, 2)) + '%'

enter image description here

Solution 2:

I am not sure if that is possible, because the object matplotlib.patches.Rectange (that is a single bar) would need to have a class relation upwards in hierarchy (figure => axes => lines)

The standard procedure is to know the axis:

import matplotlib.pyplot as plt
import numpy as np
# create dummy data
rns = np.random.randn(50)
# open figure
fig,(ax1,ax2) = plt.subplots(2,1,figsize=(10,6))
# bar charts
barg1 = ax1.bar(range(50),rns)
barg2 = ax2.bar(range(50),rns**2)

# define functiondefanotateBarChart(ax,BargChart):
    for bar in BargChart:
        reading = round(bar.get_height(),2)
        ax.annotate(str(reading)+'%',(bar.get_x(),reading))

# call defined function
anotateBarChart(ax1,barg1)
anotateBarChart(ax2,barg2)

I have created a small function, so that you don't need to concatenate the lines + loop over them but can just call a function on each axis object. Further, I recommend to use annotate rather than text, but is just a hint

enter image description here

Post a Comment for "How To Get The Associated Axis Of A Bar Chart In Python Matplotlib"