Adicionando Legenda
Quando múltiplos elementos estão presentes em um gráfico, muitas vezes é útil rotulá-los para maior clareza. A legenda cumpre esse papel ao fornecer uma área compacta que explica os diferentes componentes do gráfico.
A seguir, estão três maneiras comuns de criar uma legenda no matplotlib
.
Primeira Opção
Considere o exemplo a seguir para esclarecer o conceito:
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()
No canto superior esquerdo, uma legenda explica as diferentes barras no gráfico. Essa legenda é criada utilizando a função plt.legend()
, com uma lista de rótulos passada como primeiro argumento—comumente chamada de labels
.
Segunda Opção
Outra opção envolve especificar o parâmetro label
em cada chamada da função de plotagem, como bar em nosso exemplo:
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()
Aqui, plt.legend()
determina automaticamente os elementos a serem adicionados à legenda e seus rótulos; todos os elementos com o parâmetro label especificado são incluídos.
Terceira Opção
Na verdade, existe ainda mais uma opção utilizando o método set_label()
no artista (bar
em nosso exemplo):
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()
Localização da Legenda
Existe outro argumento importante na função legend()
, o loc
, que especifica a localização da legenda. O valor padrão é best
, que "informa" ao matplotlib
para escolher automaticamente a melhor posição para a legenda, evitando sobreposição com os dados.
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()
Neste exemplo, a legenda está posicionada no centro superior do gráfico. Outros valores válidos para o parâmetro loc
incluem:
'upper right'
,'upper left'
,'lower left'
;'lower right'
,'right'
;'center left'
,'center right'
,'lower center'
,'center'
.
Você pode explorar mais em legend()
documentação
Swipe to start coding
- Rotule as barras mais baixas como
'primary sector'
, especificando o argumento de palavra-chave apropriado. - Rotule as barras do meio como
'secondary sector'
, especificando o argumento de palavra-chave apropriado. - Rotule as barras superiores como
'tertiary sector'
, especificando o argumento de palavra-chave apropriado. - Posicione a legenda no lado direito, centralizada verticalmente.
Solução
Obrigado pelo seu feedback!