Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Agregar Leyenda | Personalización de Gráficos
Visualización Definitiva con Python

Desliza para mostrar el menú

book
Agregar Leyenda

Cuando hay múltiples elementos presentes en un gráfico, a menudo es útil etiquetarlos para mayor claridad. La leyenda cumple esta función al proporcionar un área compacta que explica los diferentes componentes del gráfico.

A continuación se presentan tres formas comunes de crear una leyenda en matplotlib.

Primera opción

Considere el siguiente ejemplo para aclarar el concepto:

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

En la esquina superior izquierda, una leyenda explica las diferentes barras en el gráfico. Esta leyenda se crea utilizando la función plt.legend(), pasando una lista de etiquetas como primer argumento, comúnmente denominada labels.

Segunda opción

Otra opción consiste en especificar el parámetro label en cada llamada a la función de graficado, como bar en nuestro ejemplo:

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

Aquí, plt.legend() determina automáticamente los elementos que se agregarán a la leyenda y sus etiquetas; se incluyen todos los elementos con el parámetro label especificado.

Tercera opción

De hecho, existe una opción más utilizando el método set_label() en el artista (bar en nuestro ejemplo):

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

Ubicación de la leyenda

Existe otro argumento clave importante en la función legend(), loc, que especifica la ubicación de la leyenda. Su valor predeterminado es best, lo que "indica" a matplotlib que elija automáticamente la mejor ubicación para la leyenda y así evitar que se superponga con los datos.

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

En este ejemplo, la leyenda se posiciona en la parte superior central de la gráfica. Otros valores válidos para el parámetro loc incluyen:

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

  • 'lower right', 'right';

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

Note
Estudiar más

Puedes explorar más en legend() documentación

Tarea

Swipe to start coding

  1. Etiquetar las barras más bajas como 'primary sector' especificando el argumento de palabra clave correspondiente.
  2. Etiquetar las barras del medio como 'secondary sector' especificando el argumento de palabra clave correspondiente.
  3. Etiquetar las barras superiores como 'tertiary sector' especificando el argumento de palabra clave correspondiente.
  4. Colocar la leyenda en el lado derecho, centrada verticalmente.

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 2

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

book
Agregar Leyenda

Cuando hay múltiples elementos presentes en un gráfico, a menudo es útil etiquetarlos para mayor claridad. La leyenda cumple esta función al proporcionar un área compacta que explica los diferentes componentes del gráfico.

A continuación se presentan tres formas comunes de crear una leyenda en matplotlib.

Primera opción

Considere el siguiente ejemplo para aclarar el concepto:

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

En la esquina superior izquierda, una leyenda explica las diferentes barras en el gráfico. Esta leyenda se crea utilizando la función plt.legend(), pasando una lista de etiquetas como primer argumento, comúnmente denominada labels.

Segunda opción

Otra opción consiste en especificar el parámetro label en cada llamada a la función de graficado, como bar en nuestro ejemplo:

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

Aquí, plt.legend() determina automáticamente los elementos que se agregarán a la leyenda y sus etiquetas; se incluyen todos los elementos con el parámetro label especificado.

Tercera opción

De hecho, existe una opción más utilizando el método set_label() en el artista (bar en nuestro ejemplo):

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

Ubicación de la leyenda

Existe otro argumento clave importante en la función legend(), loc, que especifica la ubicación de la leyenda. Su valor predeterminado es best, lo que "indica" a matplotlib que elija automáticamente la mejor ubicación para la leyenda y así evitar que se superponga con los datos.

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

En este ejemplo, la leyenda se posiciona en la parte superior central de la gráfica. Otros valores válidos para el parámetro loc incluyen:

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

  • 'lower right', 'right';

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

Note
Estudiar más

Puedes explorar más en legend() documentación

Tarea

Swipe to start coding

  1. Etiquetar las barras más bajas como 'primary sector' especificando el argumento de palabra clave correspondiente.
  2. Etiquetar las barras del medio como 'secondary sector' especificando el argumento de palabra clave correspondiente.
  3. Etiquetar las barras superiores como 'tertiary sector' especificando el argumento de palabra clave correspondiente.
  4. Colocar la leyenda en el lado derecho, centrada verticalmente.

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 2
Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
Lamentamos que algo salió mal. ¿Qué pasó?
some-alt