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:
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()
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:
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()
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):
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()
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.
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()
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'
.
Puedes explorar más en legend()
documentación
Swipe to start coding
- Etiquetar las barras más bajas como
'primary sector'
especificando el argumento de palabra clave correspondiente. - Etiquetar las barras del medio como
'secondary sector'
especificando el argumento de palabra clave correspondiente. - Etiquetar las barras superiores como
'tertiary sector'
especificando el argumento de palabra clave correspondiente. - Colocar la leyenda en el lado derecho, centrada verticalmente.
Solución
¡Gracias por tus comentarios!
single
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 3.85
Agregar Leyenda
Desliza para mostrar el menú
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:
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()
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:
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()
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):
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()
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.
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()
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'
.
Puedes explorar más en legend()
documentación
Swipe to start coding
- Etiquetar las barras más bajas como
'primary sector'
especificando el argumento de palabra clave correspondiente. - Etiquetar las barras del medio como
'secondary sector'
especificando el argumento de palabra clave correspondiente. - Etiquetar las barras superiores como
'tertiary sector'
especificando el argumento de palabra clave correspondiente. - Colocar la leyenda en el lado derecho, centrada verticalmente.
Solución
¡Gracias por tus comentarios!
Awesome!
Completion rate improved to 3.85single