Diagramme à barres

Un diagramme à barre est un graphique qui présente des catégories avec des barres rectangulaires. La taille du rectangle est proportionnelle à la valeur. Les barres peuvent être tracées horizontalement ou verticalement.

Les commandes pour des barres horizontales/verticales sont similiares:

  • bar(x, height, width=0.8)

  • barh(y, width, height=0.8)

Barres verticales

Voici un graph vertical avec la fonction bar.

labels = ['Jim', 'Kim', 'Lee', 'Tim', 'Edy']
a = [2, 4, 3, 5, 1]
plt.bar(labels, a);
plt.title('vertical')
Text(0.5, 1.0, 'vertical')
../_images/bar_5_1.png

Barres horizontales

Voici un graphe horizontal avec la fonction barh.

plt.barh(labels, a)
plt.title('horizontal');
../_images/bar_7_0.png

Barres d’erreur

errors = [0.5, 0.5, 0.2, 0.7, 0.2]
plt.bar(labels, a, yerr=errors)
plt.title("Avec barre d'erreur");
Text(0.5, 1.0, "Avec barre d'erreur")
../_images/bar_9_1.png

Épaisseur des barres

plt.bar(labels, a, 0.5, yerr=errors);
../_images/bar_11_0.png
width = [0.1, 0.2, 0.4, 0.8, 0.2]
plt.bar(labels, a, width, yerr=errors);
../_images/bar_12_0.png

Alignement des barres

L’alignement peut être center ou edge

plt.bar(labels, a, align='edge');
../_images/bar_14_0.png

Étiquette

plt.bar(labels, a, yerr=errors, label='A');
plt.legend();
../_images/bar_16_0.png

Graphes juxtaposés

plt.barh(labels, a, label='A');
plt.barh(labels, b, left = 6, label='B');
plt.legend();
../_images/bar_18_0.png
plt.barh(labels, a, label='A');
plt.barh(labels, b, left = a, label='B');
plt.legend();
../_images/bar_19_0.png

Ajouter un texte

En haut de chaque colonne ou au centre nous pouons placer la valeur numérique.

plt.bar(labels, a)
for x, y in enumerate(a):
    plt.text(x, y, y)
../_images/bar_21_0.png
plt.bar(labels, a)
for x, y in enumerate(a):
    plt.text(x, y/2, y, fontsize=16, color='white', ha='center', va='center')
../_images/bar_22_0.png

Barres empilées

b = [1, 2, 3, 2, 1]
plt.bar(labels, a, label='A');
plt.bar(labels, b, bottom = 6, label='B');
plt.legend();
../_images/bar_24_0.png
plt.bar(labels, a, label='A');
plt.bar(labels, b, bottom = a, label='B');
plt.legend();
../_images/bar_25_0.png

Barres groupées

Nous pouvons déplacer les deux courbes pour créer un graphique avec multiple

x = np.arange(5)
w = 0.4
plt.bar(x-w/2, a, w, label='A')
plt.bar(x+w/2, b, w, label='B')
plt.legend()
plt.xticks(x)
plt.gca().set_xticklabels(labels);
../_images/bar_28_0.png
plt.barh(x-w/2, a, w, label='A')
plt.barh(x+w/2, b, w, label='B')
plt.legend()
plt.yticks(x)
plt.gca().set_yticklabels(labels);
../_images/bar_29_0.png

Barres en 2 directions

n = 12
X = np.arange(n)
Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)

plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')

for x,y in zip(X,Y1):
    plt.text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')

plt.ylim(-1.25,+1.25)
plt.show()
../_images/bar_31_0.png