Lägga till Förklaring
När flera element finns i ett diagram är det ofta hjälpsamt att märka dem för tydlighetens skull. Legenden fyller denna funktion genom att tillhandahålla ett kompakt område som förklarar olika komponenter i diagrammet.
Följande är tre vanliga sätt att skapa en legend i matplotlib
.
Första alternativet
Följande exempel förtydligar konceptet:
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()
I det övre vänstra hörnet förklarar en förklaring de olika staplarna i diagrammet. Denna förklaring skapas med funktionen plt.legend()
, där en lista med etiketter skickas som första argument—vanligtvis kallad labels
.
Andra alternativet
Ett annat alternativ innebär att ange parametern label
i varje anrop av plottfunktionen, såsom bar i vårt exempel:
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()
Här bestämmer plt.legend()
automatiskt vilka element som ska läggas till i förklaringen och deras etiketter; alla element med angiven label-parameter inkluderas.
Tredje alternativet
Det finns faktiskt ytterligare ett alternativ med metoden set_label()
på konstobjektet (bar
i vårt exempel):
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()
Legendens placering
Det finns ett annat viktigt nyckelargument för funktionen legend()
, loc
, som anger var legenden ska placeras. Standardvärdet är best
, vilket "instruerar" matplotlib
att automatiskt välja den bästa placeringen för legenden för att undvika överlappning med data.
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()
I detta exempel är legenden placerad i övre mitten av diagrammet. Andra giltiga värden för parametern loc
inkluderar:
'upper right'
,'upper left'
,'lower left'
;'lower right'
,'right'
;'center left'
,'center right'
,'lower center'
,'center'
.
Du kan utforska mer i legend()
dokumentation
Swipe to start coding
- Märk de lägsta staplarna som
'primary sector'
genom att ange lämpligt nyckelordsargument. - Märk staplarna i mitten som
'secondary sector'
genom att ange lämpligt nyckelordsargument. - Märk de översta staplarna som
'tertiary sector'
genom att ange lämpligt nyckelordsargument. - Placera förklaringen på högra sidan, centrerad vertikalt.
Lösning
Tack för dina kommentarer!