How to add text on a bar with matplotlib ?

Published: January 29, 2019

DMCA.com Protection Status

Example of how to add text on a bar with matplotlib (source)

Ajouter du texte sur diagramme en baton avec matplotlib
Ajouter du texte sur diagramme en baton avec matplotlib

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

bar_x = [1,2,3,4,5,6,7]
bar_height = [12,14,17,11,12,9,12]
bar_tick_label = ['C1','C2','C3','C4','C5','C6','C7']
bar_label = [12,14,17,11,12,9,12]

bar_plot = plt.bar(bar_x,bar_height,tick_label=bar_tick_label)

def autolabel(rects):
    for idx,rect in enumerate(bar_plot):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                bar_label[idx],
                ha='center', va='bottom', rotation=0)

autolabel(bar_plot)

plt.ylim(0,20)

plt.title('Add text for each bar with matplotlib')

plt.savefig("add_text_bar_matplotlib_01.png", bbox_inches='tight')
plt.show()

If the text is too long, it can be rotated, rot=90 for instance

Ajouter du texte sur diagramme en baton avec matplotlib
Ajouter du texte sur diagramme en baton avec matplotlib

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

bar_x = [1,2,3,4,5,6,7]
bar_height = [12,14,17,11,12,9,12]
bar_tick_label = ['C1','C2','C3','C4','C5','C6','C7']
bar_label = [12.0001,14.0001,17.0001,11.0001,12.0001,9.0001,12.0001]

bar_plot = plt.bar(bar_x,bar_height,tick_label=bar_tick_label)

def autolabel(rects):
    for idx,rect in enumerate(bar_plot):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                bar_label[idx],
                ha='center', va='bottom', rotation=90)

autolabel(bar_plot)

plt.ylim(0,20)

plt.title('Add text for each bar with matplotlib')

plt.savefig("add_text_bar_matplotlib_02.png", bbox_inches='tight')
plt.show()

Text position on the bar can also be changed, for example 0.5*height in ax.text() function

Ajouter du texte sur diagramme en baton avec matplotlib
Ajouter du texte sur diagramme en baton avec matplotlib

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

bar_x = [1,2,3,4,5,6,7]
bar_height = [12,14,17,11,12,9,12]
bar_tick_label = ['C1','C2','C3','C4','C5','C6','C7']
bar_label = [12.0001,14.0001,17.0001,11.0001,12.0001,9.0001,12.0001]

bar_plot = plt.bar(bar_x,bar_height,tick_label=bar_tick_label)

def autolabel(rects):
    for idx,rect in enumerate(bar_plot):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 0.5*height,
                bar_label[idx],
                ha='center', va='bottom', rotation=90)

autolabel(bar_plot)

plt.ylim(0,20)

plt.title('Add text for each bar with matplotlib')

plt.savefig("add_text_bar_matplotlib_03.png", bbox_inches='tight')
plt.show()

References

Image

of