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:
1234567891011121314151617181920212223242526import 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()
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:
1234567891011121314151617181920212223242526272829import 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()
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):
1234567891011121314151617181920212223242526import 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()
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.
1234567891011121314151617181920212223242526import 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 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'
.
Puoi approfondire consultando la documentazione di legend()
Swipe to start coding
- Etichettare le barre più basse come
'primary sector'
specificando l'argomento keyword appropriato. - Etichettare le barre centrali come
'secondary sector'
specificando l'argomento keyword appropriato. - Etichettare le barre superiori come
'tertiary sector'
specificando l'argomento keyword appropriato. - Posizionare la legenda sul lato destro, centrata verticalmente.
Soluzione
Grazie per i tuoi commenti!
single
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 3.85
Aggiunta della Legenda
Scorri per mostrare il menu
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:
1234567891011121314151617181920212223242526import 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()
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:
1234567891011121314151617181920212223242526272829import 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()
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):
1234567891011121314151617181920212223242526import 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()
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.
1234567891011121314151617181920212223242526import 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 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'
.
Puoi approfondire consultando la documentazione di legend()
Swipe to start coding
- Etichettare le barre più basse come
'primary sector'
specificando l'argomento keyword appropriato. - Etichettare le barre centrali come
'secondary sector'
specificando l'argomento keyword appropriato. - Etichettare le barre superiori come
'tertiary sector'
specificando l'argomento keyword appropriato. - Posizionare la legenda sul lato destro, centrata verticalmente.
Soluzione
Grazie per i tuoi commenti!
Awesome!
Completion rate improved to 3.85single