Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Aggiunta della Legenda | Personalizzazione Dei Grafici
Visualizzazione Definitiva con Python

Scorri per mostrare il menu

book
Aggiunta della Legenda

Quando sono presenti più elementi in un grafico, è spesso utile etichettarli per maggiore chiarezza. La legenda svolge questa funzione fornendo un'area compatta che spiega i diversi componenti del grafico.

Di seguito sono riportati tre modi comuni per creare una legenda in matplotlib.

Prima opzione

Considera il seguente esempio per chiarire il concetto:

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

Nell'angolo in alto a sinistra, una legenda spiega le diverse barre presenti nel grafico. Questa legenda viene creata utilizzando la funzione plt.legend(), a cui viene passato un elenco di etichette come primo argomento—comunemente denominato labels.

Seconda opzione

Un'altra opzione consiste nello specificare il parametro label in ogni chiamata della funzione di tracciamento, come ad esempio bar nel nostro caso:

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

Qui, plt.legend() determina automaticamente gli elementi da aggiungere alla legenda e le loro etichette; tutti gli elementi con il parametro label specificato sono inclusi.

Terza opzione

In realtà, esiste anche un'ulteriore opzione utilizzando il metodo set_label() sull'artista (bar nel nostro esempio):

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

Posizione della legenda

Esiste un altro argomento chiave importante della funzione legend(), loc, che specifica la posizione della legenda. Il suo valore predefinito è best, che "indica" a matplotlib di scegliere automaticamente la posizione migliore per la legenda al fine di evitare sovrapposizioni con i dati.

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

In questo esempio, la legenda è posizionata nella parte superiore centrale del grafico. Altri valori validi per il parametro loc includono:

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

  • 'lower right', 'right';

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

Note
Approfondisci

Puoi approfondire consultando la documentazione di legend()

Compito

Swipe to start coding

  1. Etichettare le barre più basse come 'primary sector' specificando l'argomento keyword appropriato.
  2. Etichettare le barre centrali come 'secondary sector' specificando l'argomento keyword appropriato.
  3. Etichettare le barre superiori come 'tertiary sector' specificando l'argomento keyword appropriato.
  4. Posizionare la legenda sul lato destro, centrata verticalmente.

Soluzione

Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 2

Chieda ad AI

expand
ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

book
Aggiunta della Legenda

Quando sono presenti più elementi in un grafico, è spesso utile etichettarli per maggiore chiarezza. La legenda svolge questa funzione fornendo un'area compatta che spiega i diversi componenti del grafico.

Di seguito sono riportati tre modi comuni per creare una legenda in matplotlib.

Prima opzione

Considera il seguente esempio per chiarire il concetto:

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

Nell'angolo in alto a sinistra, una legenda spiega le diverse barre presenti nel grafico. Questa legenda viene creata utilizzando la funzione plt.legend(), a cui viene passato un elenco di etichette come primo argomento—comunemente denominato labels.

Seconda opzione

Un'altra opzione consiste nello specificare il parametro label in ogni chiamata della funzione di tracciamento, come ad esempio bar nel nostro caso:

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

Qui, plt.legend() determina automaticamente gli elementi da aggiungere alla legenda e le loro etichette; tutti gli elementi con il parametro label specificato sono inclusi.

Terza opzione

In realtà, esiste anche un'ulteriore opzione utilizzando il metodo set_label() sull'artista (bar nel nostro esempio):

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

Posizione della legenda

Esiste un altro argomento chiave importante della funzione legend(), loc, che specifica la posizione della legenda. Il suo valore predefinito è best, che "indica" a matplotlib di scegliere automaticamente la posizione migliore per la legenda al fine di evitare sovrapposizioni con i dati.

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

In questo esempio, la legenda è posizionata nella parte superiore centrale del grafico. Altri valori validi per il parametro loc includono:

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

  • 'lower right', 'right';

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

Note
Approfondisci

Puoi approfondire consultando la documentazione di legend()

Compito

Swipe to start coding

  1. Etichettare le barre più basse come 'primary sector' specificando l'argomento keyword appropriato.
  2. Etichettare le barre centrali come 'secondary sector' specificando l'argomento keyword appropriato.
  3. Etichettare le barre superiori come 'tertiary sector' specificando l'argomento keyword appropriato.
  4. Posizionare la legenda sul lato destro, centrata verticalmente.

Soluzione

Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 2
Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Siamo spiacenti che qualcosa sia andato storto. Cosa è successo?
some-alt