Agregar una leyenda a PyPlot en Matplotlib de la manera más simple posible


TL; DR -> ¿Cómo se puede crear una leyenda para un gráfico de líneas en Matplotlib's PyPlot sin crear ninguna variable adicional?

Por favor considere el script gráfico a continuación:

if __name__ == '__main__':
    PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
                total_lengths, sort_times_ins, 'r-',
                total_lengths, sort_times_merge_r, 'g+',
                total_lengths, sort_times_merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()

Como puedes ver, este es un uso muy básico de matplotlib's PyPlot. Esto idealmente genera un gráfico como el siguiente:

Grafica

Nada especial, lo sé. Sin embargo, no está claro qué datos se están trazando dónde (estoy tratando de trazar los datos de alguna ordenación algoritmos, longitud contra el tiempo tomado, y me gustaría asegurarme de que la gente sepa qué línea es cuál). Por lo tanto, necesito una leyenda, sin embargo, echando un vistazo al siguiente ejemplo a continuación ( desde el sitio oficial):

ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
            key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)

Verás que necesito crear una variable adicional ax. Cómo puedo agregar una leyenda a mi gráfico sin tener que crear esta variable adicional y conservar la simplicidad de mi script actual.

Author: Games Brainiac, 2013-10-02

5 answers

Añadir un label= a cada uno de sus plot() llama, y luego llama legend(loc='upper left').

Considere esta muestra:

import numpy as np
import pylab 
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

pylab.plot(x, y1, '-b', label='sine')
pylab.plot(x, y2, '-r', label='cosine')
pylab.legend(loc='upper left')
pylab.ylim(-1.5, 2.0)
pylab.show()

introduzca la descripción de la imagen aquí Ligeramente modificado de este tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

 209
Author: Robᵩ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-28 18:27:28

Aquí hay un ejemplo para ayudarte ...

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()

introduzca la descripción de la imagen aquí

 6
Author: harrypotter0,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-06 07:00:58

Agregue etiquetas a cada argumento en su llamada a la gráfica correspondiente a la serie que está graficando, es decir, label = "series 1"

Luego simplemente agrega Pyplot.legend() a la parte inferior de tu script y la leyenda mostrará estas etiquetas.

 5
Author: blaklaybul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-01 21:05:42

Puede acceder a la instancia de Axes (ax) con plt.gca(). En este caso, puede utilizar

plt.gca().legend()

Puede hacer esto usando la palabra clave label= en cada una de sus llamadas plt.plot() o asignando sus etiquetas como una tupla o lista dentro de legend, como en este ejemplo de trabajo:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

Sin embargo, si necesita acceder a la instancia de Axes más de una vez, le recomiendo guardarla en la variable ax con

ax = plt.gca()

Y luego llamar a ax en lugar de plt.gca().

 4
Author: cameronroytaylor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-26 18:12:16

Una gráfica simple para las curvas seno y coseno con una leyenda.

Usado matplotlib.pyplot

import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
    x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()

Gráficos de Sin y Coseno (haga clic para ver la imagen)

 0
Author: sajalagrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-03 17:45:25