Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Lägga till Förklaring | Anpassning av Diagram
Ultimat Visualisering med Python

Svep för att visa menyn

book
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:

1234567891011121314151617181920212223242526
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()
copy

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:

1234567891011121314151617181920212223242526272829
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()
copy

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):

1234567891011121314151617181920212223242526
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()
copy

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.

1234567891011121314151617181920212223242526
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()
copy

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'.

Note
Studera vidare

Du kan utforska mer i legend() dokumentation

Uppgift

Swipe to start coding

  1. Märk de lägsta staplarna som 'primary sector' genom att ange lämpligt nyckelordsargument.
  2. Märk staplarna i mitten som 'secondary sector' genom att ange lämpligt nyckelordsargument.
  3. Märk de översta staplarna som 'tertiary sector' genom att ange lämpligt nyckelordsargument.
  4. Placera förklaringen på högra sidan, centrerad vertikalt.

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

book
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:

1234567891011121314151617181920212223242526
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()
copy

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:

1234567891011121314151617181920212223242526272829
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()
copy

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):

1234567891011121314151617181920212223242526
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()
copy

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.

1234567891011121314151617181920212223242526
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()
copy

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'.

Note
Studera vidare

Du kan utforska mer i legend() dokumentation

Uppgift

Swipe to start coding

  1. Märk de lägsta staplarna som 'primary sector' genom att ange lämpligt nyckelordsargument.
  2. Märk staplarna i mitten som 'secondary sector' genom att ange lämpligt nyckelordsargument.
  3. Märk de översta staplarna som 'tertiary sector' genom att ange lämpligt nyckelordsargument.
  4. Placera förklaringen på högra sidan, centrerad vertikalt.

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2
Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Vi beklagar att något gick fel. Vad hände?
some-alt