Legenda Toevoegen
Wanneer meerdere elementen aanwezig zijn in een grafiek, is het vaak nuttig om deze te labelen voor duidelijkheid. De legenda vervult dit doel door een compact gebied te bieden dat de verschillende componenten van de grafiek uitlegt.
Hieronder staan drie veelgebruikte methoden om een legenda te maken in matplotlib
.
Eerste optie
Bekijk het volgende voorbeeld ter verduidelijking van het concept:
import matplotlib.pyplot as plt import numpy as np # Define categories and data questions = ['question_1', 'question_2', 'question_3'] yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = np.array([yes_answers, no_answers]) # Set positions and bar width positions = np.arange(len(questions)) width = 0.3 # Create the grouped bar chart for i in range(len(answers)): plt.bar(positions + width * i, answers[i], width) # Adjust x-axis ticks to the center of groups plt.xticks(positions + width * (len(answers) - 1) / 2, questions) # Setting the labels for the legend explicitly plt.legend(['positive answers', 'negative answers']) plt.show()
In de linkerbovenhoek verduidelijkt een legenda de verschillende balken op de grafiek. Deze legenda wordt aangemaakt met de functie plt.legend()
, waarbij een lijst met labels als eerste argument wordt meegegeven—gewoonlijk aangeduid als labels
.
Tweede optie
Een andere mogelijkheid is het specificeren van de parameter label
bij elke aanroep van de plotfunctie, zoals bar in ons voorbeeld:
import matplotlib.pyplot as plt import numpy as np # Define x-axis categories and their positions questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) # Define answers for each category yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = np.array([yes_answers, no_answers]) labels = ['positive answers', 'negative answers'] # Set the width for each bar width = 0.3 # Plot each category with a label for i in range(len(answers)): plt.bar(positions + width * i, answers[i], width, label=labels[i]) # Set x-axis ticks and labels at the center of each group plt.xticks(positions + width * (len(answers) - 1) / 2, questions) # Automatically create legend from label parameters plt.legend() plt.show()
Hier bepaalt plt.legend()
automatisch welke elementen aan de legenda worden toegevoegd en welke labels ze krijgen; alle elementen waarvoor de label-parameter is opgegeven, worden opgenomen.
Derde optie
Er is zelfs nog een extra optie met de methode set_label()
op het artist-object (bar
in ons voorbeeld):
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'] # Plot bars for each category with labels for i in range(len(answers)): bar = plt.bar(positions + width * i, answers[i], width) bar.set_label(labels[i]) # Set x-axis ticks and labels at the center of the grouped bars center_positions = positions + width * (len(answers) - 1) / 2 plt.xticks(center_positions, questions) # Display legend above the plot, centered horizontally plt.legend(loc='upper center') plt.show()
Legende Locatie
Er is een ander belangrijk sleutelargument van de functie legend()
, namelijk loc
, dat de locatie van de legende specificeert. De standaardwaarde is best
, wat matplotlib
"vertelt" om automatisch de beste locatie voor de legende te kiezen om overlapping met de gegevens te voorkomen.
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'] # Plot bars for each category with labels for i, label in enumerate(labels): bars = plt.bar(positions + width * i, answers[i], width) bars.set_label(label) # Set x-axis ticks and labels at the center of the grouped bars center_positions = positions + width * (len(answers) - 1) / 2 plt.xticks(center_positions, questions) # Display legend above the plot, centered horizontally plt.legend(loc='upper center') plt.show()
In dit voorbeeld is de legende gepositioneerd in het bovenste midden van de grafiek. Andere geldige waarden voor de parameter loc
zijn:
'upper right'
,'upper left'
,'lower left'
;'lower right'
,'right'
;'center left'
,'center right'
,'lower center'
,'center'
.
Meer informatie is te vinden in de legend()
documentatie
Swipe to start coding
- Label de laagste balken als
'primary sector'
met het juiste keyword argument. - Label de balken in het midden als
'secondary sector'
met het juiste keyword argument. - Label de bovenste balken als
'tertiary sector'
met het juiste keyword argument. - Plaats de legenda aan de rechterkant, verticaal gecentreerd.
Oplossing
Bedankt voor je feedback!