Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Lavorare con la Legenda | Sezione
Visualizzazione dei Dati con Matplotlib

bookLavorare con la Legenda

Quando un grafico contiene più elementi, aggiungere una legenda aiuta a chiarire cosa rappresenta ciascun elemento. matplotlib offre diversi modi per creare una legenda.

Prima opzione

È possibile definire tutte le etichette direttamente all'interno di plt.legend():

123456789101112131415161718
import numpy as np import matplotlib.pyplot as plt 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]) positions = np.arange(len(questions)) width = 0.3 for i in range(len(answers)): plt.bar(positions + width * i, answers[i], width) plt.xticks(positions + width*(len(answers)-1)/2, questions) plt.legend(['positive answers', 'negative answers']) plt.show()
copy

Questo crea una legenda nell'angolo in alto a sinistra passando una lista di etichette a plt.legend().

Seconda opzione

È anche possibile assegnare le etichette direttamente all'interno delle funzioni di visualizzazione utilizzando il parametro label=:

1234567891011121314151617181920
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 = [yes_answers, no_answers] labels = ['positive answers', 'negative answers'] width = 0.3 for i in range(len(answers)): plt.bar(positions + width*i, answers[i], width, label=labels[i]) plt.xticks(positions + width*(len(answers)-1)/2, questions) plt.legend() plt.show()
copy

Qui, plt.legend() raccoglie automaticamente le etichette dagli elementi tracciati.

Terza opzione

È possibile impostare le etichette anche utilizzando il metodo set_label() dell'artista restituito:

12345678910111213141516171819202122
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 = [yes_answers, no_answers] width = 0.3 labels = ['positive answers', 'negative answers'] for i in range(len(answers)): bar = plt.bar(positions + width*i, answers[i], width) bar.set_label(labels[i]) center_positions = positions + width*(len(answers)-1)/2 plt.xticks(center_positions, questions) plt.legend(loc='upper center') plt.show()
copy

Posizione della legenda

L'argomento loc controlla dove appare la legenda. Il valore predefinito 'best' chiede a matplotlib di scegliere automaticamente una posizione ottimale.

12345678910111213141516171819202122
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 = [yes_answers, no_answers] labels = ['positive answers', 'negative answers'] width = 0.3 for i, label in enumerate(labels): bars = plt.bar(positions + width*i, answers[i], width) bars.set_label(label) center_positions = positions + width*(len(answers)-1)/2 plt.xticks(center_positions, questions) plt.legend(loc='upper center') plt.show()
copy

I valori validi per loc includono:

'upper left'

'upper center'

'upper right'

'center left'

'center'

'center right'

'lower left'

'lower center'

'lower right'

È possibile utilizzare anche l'opzione 'best', che posiziona automaticamente la legenda nella posizione con la minore sovrapposizione ai dati tracciati. Inoltre, l'utilizzo di 'right' produce lo stesso risultato di 'center right'.

Note
Approfondisci

Puoi approfondire nella 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

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 10
single

single

Chieda ad AI

expand

Chieda ad AI

ChatGPT

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

close

bookLavorare con la Legenda

Scorri per mostrare il menu

Quando un grafico contiene più elementi, aggiungere una legenda aiuta a chiarire cosa rappresenta ciascun elemento. matplotlib offre diversi modi per creare una legenda.

Prima opzione

È possibile definire tutte le etichette direttamente all'interno di plt.legend():

123456789101112131415161718
import numpy as np import matplotlib.pyplot as plt 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]) positions = np.arange(len(questions)) width = 0.3 for i in range(len(answers)): plt.bar(positions + width * i, answers[i], width) plt.xticks(positions + width*(len(answers)-1)/2, questions) plt.legend(['positive answers', 'negative answers']) plt.show()
copy

Questo crea una legenda nell'angolo in alto a sinistra passando una lista di etichette a plt.legend().

Seconda opzione

È anche possibile assegnare le etichette direttamente all'interno delle funzioni di visualizzazione utilizzando il parametro label=:

1234567891011121314151617181920
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 = [yes_answers, no_answers] labels = ['positive answers', 'negative answers'] width = 0.3 for i in range(len(answers)): plt.bar(positions + width*i, answers[i], width, label=labels[i]) plt.xticks(positions + width*(len(answers)-1)/2, questions) plt.legend() plt.show()
copy

Qui, plt.legend() raccoglie automaticamente le etichette dagli elementi tracciati.

Terza opzione

È possibile impostare le etichette anche utilizzando il metodo set_label() dell'artista restituito:

12345678910111213141516171819202122
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 = [yes_answers, no_answers] width = 0.3 labels = ['positive answers', 'negative answers'] for i in range(len(answers)): bar = plt.bar(positions + width*i, answers[i], width) bar.set_label(labels[i]) center_positions = positions + width*(len(answers)-1)/2 plt.xticks(center_positions, questions) plt.legend(loc='upper center') plt.show()
copy

Posizione della legenda

L'argomento loc controlla dove appare la legenda. Il valore predefinito 'best' chiede a matplotlib di scegliere automaticamente una posizione ottimale.

12345678910111213141516171819202122
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 = [yes_answers, no_answers] labels = ['positive answers', 'negative answers'] width = 0.3 for i, label in enumerate(labels): bars = plt.bar(positions + width*i, answers[i], width) bars.set_label(label) center_positions = positions + width*(len(answers)-1)/2 plt.xticks(center_positions, questions) plt.legend(loc='upper center') plt.show()
copy

I valori validi per loc includono:

'upper left'

'upper center'

'upper right'

'center left'

'center'

'center right'

'lower left'

'lower center'

'lower right'

È possibile utilizzare anche l'opzione 'best', che posiziona automaticamente la legenda nella posizione con la minore sovrapposizione ai dati tracciati. Inoltre, l'utilizzo di 'right' produce lo stesso risultato di 'center right'.

Note
Approfondisci

Puoi approfondire nella 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 1. Capitolo 10
single

single

some-alt