Exemple de comment ajouter du texte sur diagramme en baton avec matplotlib (source)

import matplotlib.pyplot as pltfig, 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()
Si le texte est trop long, on peut changer l'orientation rot=90 par exemple:

import matplotlib.pyplot as pltfig, 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()
On peut changer la position du texte sur le bâton, par exemple 0.5*height dans la fonction ax.text()

import matplotlib.pyplot as pltfig, 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()
Références
| Liens | Site |
|---|---|
| bar | matplotlib doc |
| api example code: barchart_demo.py | matplotlib doc |
| Adding value labels on a matplotlib bar chart | stackoverflow |
| Aligning rotated xticklabels with their respective xticks | stackoverflow |
