Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Adicionando Legenda | Personalização de Gráficos
Visualização Definitiva com Python

Deslize para mostrar o menu

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

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

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:

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

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

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

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.

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

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

Note
Estude Mais

Você pode explorar mais em legend() documentação

Tarefa

Swipe to start coding

  1. Rotule as barras mais baixas como 'primary sector', especificando o argumento de palavra-chave apropriado.
  2. Rotule as barras do meio como 'secondary sector', especificando o argumento de palavra-chave apropriado.
  3. Rotule as barras superiores como 'tertiary sector', especificando o argumento de palavra-chave apropriado.
  4. Posicione a legenda no lado direito, centralizada verticalmente.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 2
Sentimos muito que algo saiu errado. O que aconteceu?

Pergunte à IA

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

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

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

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:

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

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

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

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.

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

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

Note
Estude Mais

Você pode explorar mais em legend() documentação

Tarefa

Swipe to start coding

  1. Rotule as barras mais baixas como 'primary sector', especificando o argumento de palavra-chave apropriado.
  2. Rotule as barras do meio como 'secondary sector', especificando o argumento de palavra-chave apropriado.
  3. Rotule as barras superiores como 'tertiary sector', especificando o argumento de palavra-chave apropriado.
  4. Posicione a legenda no lado direito, centralizada verticalmente.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 2
Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Sentimos muito que algo saiu errado. O que aconteceu?
some-alt