Legende Hinzufügen
Wenn mehrere Elemente in einem Diagramm vorhanden sind, ist es oft hilfreich, diese zur besseren Übersicht zu kennzeichnen. Die Legende erfüllt diesen Zweck, indem sie einen kompakten Bereich bereitstellt, der die verschiedenen Komponenten des Diagramms erklärt.
Im Folgenden werden drei gängige Methoden zur Erstellung einer Legende in matplotlib
vorgestellt.
Erste Möglichkeit
Das folgende Beispiel verdeutlicht das Konzept:
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 der oberen linken Ecke erläutert eine Legende die verschiedenen Balken im Diagramm. Diese Legende wird mit der Funktion plt.legend()
erstellt, wobei eine Liste von Beschriftungen als erstes Argument übergeben wird—häufig als labels
bezeichnet.
Zweite Option
Eine weitere Möglichkeit besteht darin, den Parameter label
bei jedem Aufruf der Plot-Funktion anzugeben, wie zum Beispiel bei bar in unserem Beispiel:
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 bestimmt plt.legend()
automatisch die Elemente, die der Legende hinzugefügt werden, sowie deren Beschriftungen; alle Elemente mit angegebenem label-Parameter werden einbezogen.
Dritte Option
Tatsächlich gibt es noch eine weitere Möglichkeit, indem die Methode set_label()
auf das Artist-Objekt (in unserem Beispiel bar
) angewendet wird:
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()
Legendenposition
Ein weiteres wichtiges Schlüsselwortargument der Funktion legend()
ist loc
, das die Position der Legende angibt. Der Standardwert ist best
, wodurch matplotlib
automatisch die beste Position für die Legende auswählt, um eine Überlappung mit den Daten zu vermeiden.
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 diesem Beispiel ist die Legende im oberen Zentrum des Diagramms positioniert. Weitere gültige Werte für den Parameter loc
sind:
'upper right'
,'upper left'
,'lower left'
;'lower right'
,'right'
;'center left'
,'center right'
,'lower center'
,'center'
.
Weitere Informationen finden Sie in der legend()
Dokumentation
Swipe to start coding
- Die niedrigsten Balken als
'primary sector'
beschriften, indem das entsprechende Schlüsselwortargument angegeben wird. - Die mittleren Balken als
'secondary sector'
beschriften, indem das entsprechende Schlüsselwortargument angegeben wird. - Die obersten Balken als
'tertiary sector'
beschriften, indem das entsprechende Schlüsselwortargument angegeben wird. - Die Legende rechts, vertikal zentriert, platzieren.
Lösung
Danke für Ihr Feedback!