Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Ajouter une Légende | Personnalisation des Graphiques
Visualisation Ultime Avec Python

book
Ajouter une Légende

Il arrive souvent que nous ayons plusieurs éléments sur le canevas et qu'il serait préférable de les étiqueter afin de décrire le graphique. C'est là que la légende est utile. Fondamentalement, c'est une zone relativement petite qui décrit différentes parties du graphique.

Nous allons passer en revue trois options possibles pour créer une légende dans matplotlib.

Première Option

Regardons un exemple pour clarifier les choses :

import matplotlib.pyplot as plt
import numpy as np
questions = ['question_1', 'question_2', 'question_3']
positions = np.arange(len(questions))
yes_answers = np.array([500, 240, 726])
no_answers = np.array([432, 618, 101])
answers = np.array([yes_answers, no_answers])
width = 0.3
for i in range(len(answers)):
plt.bar(positions + width * i, answers[i], width)
plt.xticks(positions + width * (len(answers) - 1) / 2, questions)
# Setting the labels for the legend explicitly
plt.legend(['positive answers', 'negative answers'])
plt.show()
1234567891011121314
import matplotlib.pyplot as plt import numpy as np questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = np.array([yes_answers, no_answers]) width = 0.3 for i in range(len(answers)): plt.bar(positions + width * i, answers[i], width) plt.xticks(positions + width * (len(answers) - 1) / 2, questions) # Setting the labels for the legend explicitly plt.legend(['positive answers', 'negative answers']) plt.show()
copy

Dans le coin supérieur gauche, nous avons une légende qui décrit les différentes barres de notre graphique. Pour créer une légende, la fonction plt.legend() est utilisée avec la liste des étiquettes comme premier argument (ce paramètre est également appelé labels).

Deuxième Option

Une autre option consiste à spécifier le paramètre label dans chaque appel de la fonction de traçage (bar() dans notre exemple) :

import matplotlib.pyplot as plt
import numpy as np
questions = ['question_1', 'question_2', 'question_3']
positions = np.arange(len(questions))
yes_answers = np.array([500, 240, 726])
no_answers = np.array([432, 618, 101])
answers = np.array([yes_answers, no_answers])
width = 0.3
labels = ['positive answers', 'negative answers']
for i in range(len(answers)):
# Specifying the label parameter for each of the bar() function calls
plt.bar(positions + width * i, answers[i], width, label=labels[i])
plt.xticks(positions + width * (len(answers) - 1) / 2, questions)
# Automatical detection of the labels
plt.legend()
plt.show()
12345678910111213141516
import matplotlib.pyplot as plt import numpy as np questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = np.array([yes_answers, no_answers]) width = 0.3 labels = ['positive answers', 'negative answers'] for i in range(len(answers)): # Specifying the label parameter for each of the bar() function calls plt.bar(positions + width * i, answers[i], width, label=labels[i]) plt.xticks(positions + width * (len(answers) - 1) / 2, questions) # Automatical detection of the labels plt.legend() plt.show()
copy

Ici, plt.legend() détermine automatiquement les éléments à ajouter à la légende et leurs étiquettes (tous les éléments avec le paramètre label spécifié sont ajoutés).

Troisième Option

En fait, il existe même une option supplémentaire en utilisant la méthode set_label() sur l'artiste (bar dans notre exemple) :

for i in range(len(answers)):
bar = plt.bar(positions + width * i, answers[i], width)
bar.set_label(labels[i])

Emplacement de la Légende

Il existe un autre argument clé important de la fonction legend(), loc, qui spécifie l'emplacement de la légende. Sa valeur par défaut est best qui "indique" à matplotlib de choisir automatiquement le meilleur emplacement pour la légende afin d'éviter le chevauchement avec les données.

import matplotlib.pyplot as plt
import numpy as np
questions = ['question_1', 'question_2', 'question_3']
positions = np.arange(len(questions))
yes_answers = np.array([500, 240, 726])
no_answers = np.array([432, 618, 101])
answers = np.array([yes_answers, no_answers])
width = 0.3
labels = ['positive answers', 'negative answers']
for i in range(len(answers)):
bar = plt.bar(positions + width * i, answers[i], width)
bar.set_label(labels[i])
plt.xticks(positions + width * (len(answers) - 1) / 2, questions)
# Modiying the legend location
plt.legend(loc='upper center')
plt.show()
12345678910111213141516
import matplotlib.pyplot as plt import numpy as np questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = np.array([yes_answers, no_answers]) width = 0.3 labels = ['positive answers', 'negative answers'] for i in range(len(answers)): bar = plt.bar(positions + width * i, answers[i], width) bar.set_label(labels[i]) plt.xticks(positions + width * (len(answers) - 1) / 2, questions) # Modiying the legend location plt.legend(loc='upper center') plt.show()
copy

Ici, nous avons placé la légende au centre supérieur. D'autres valeurs possibles sont les suivantes :

  • 'upper right', 'upper left', 'lower left';
  • 'lower right', 'right';
  • 'center left', 'center right', 'lower center', 'center'.

Vous pouvez explorer plus sur legend() dans la documentation.

Tâche

Swipe to start coding

  1. Étiquetez les barres les plus basses comme 'primary sector' en spécifiant l'argument de mot-clé approprié.
  2. Étiquetez les barres du milieu comme 'secondary sector' en spécifiant l'argument de mot-clé approprié.
  3. Étiquetez les barres du haut comme 'tertiary sector' en spécifiant l'argument de mot-clé approprié.
  4. Utilisez la fonction correcte pour créer une légende.
  5. Placez la légende sur le côté droit, centrée verticalement.

Solution

import matplotlib.pyplot as plt
import numpy as np
countries = ['USA', 'China', 'Japan']
primary_sector = np.array([1.4, 4.8, 0.4])
secondary_sector = np.array([11.3, 6.2, 0.8])
tertiary_sector = np.array([14.2, 8.4, 3.2])
# Set the label for the lowest bars
plt.bar(countries, primary_sector, label='primary sector')
# Set the label for the middle bars
plt.bar(countries, secondary_sector, bottom=primary_sector, label='secondary sector')
# Set the label for the top bars
plt.bar(countries, tertiary_sector, bottom=primary_sector + secondary_sector, label='tertiary sector')
# Create the legend with specifying its location
plt.legend(loc='center right')
plt.show()

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 2
import matplotlib.pyplot as plt
import numpy as np
countries = ['USA', 'China', 'Japan']
primary_sector = np.array([1.4, 4.8, 0.4])
secondary_sector = np.array([11.3, 6.2, 0.8])
tertiary_sector = np.array([14.2, 8.4, 3.2])
# Set the label for the lowest bars
plt.bar(countries, primary_sector, ___=___)
# Set the label for the middle bars
plt.bar(countries, secondary_sector, bottom=primary_sector, ___=___)
# Set the label for the top bars
plt.bar(countries, tertiary_sector, bottom=primary_sector + secondary_sector, ___=___)
# Create the legend with specifying its location
___.___(___=___)
plt.show()
toggle bottom row
some-alt