Sé que si cambio el ancho de línea de una línea, eso se actualiza automáticamente en la leyenda. Sin embargo, me gustaría simplemente cambiar el ancho de línea de la leyenda sin afectar la trama.aumentar el ancho de línea de las líneas de leyenda en matplotlib
Respuesta
Aquí está un ejemplo sencillo de cómo hacerlo:
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
p1 = plt.plot(x, y1, 'b-', linewidth=1.0)
p2 = plt.plot(x, y2, 'r-', linewidth=1.0)
# make a legend for both plots
leg = plt.legend([p1, p2], ['sin(x)', 'cos(x)'], loc=1)
# set the linewidth of each legend object
for legobj in leg.legendHandles:
legobj.set_linewidth(2.0)
plt.show()
Si desea cambiar todas las líneas en una trama, que podría ser útil para definir su propia leyenda manejador:
import matplotlib.pyplot as plt
from matplotlib import legend_handler
from matplotlib.lines import Line2D
import numpy as np
class MyHandlerLine2D(legend_handler.HandlerLine2D):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize,
trans):
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = ((height-ydescent)/2.)*np.ones(xdata.shape, float)
legline = Line2D(xdata, ydata)
self.update_prop(legline, orig_handle, legend)
#legline.update_from(orig_handle)
#legend._set_artist_props(legline) # after update
#legline.set_clip_box(None)
#legline.set_clip_path(None)
legline.set_drawstyle('default')
legline.set_marker("")
legline.set_linewidth(10)
legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
self.update_prop(legline_marker, orig_handle, legend)
#legline_marker.update_from(orig_handle)
#legend._set_artist_props(legline_marker)
#legline_marker.set_clip_box(None)
#legline_marker.set_clip_path(None)
legline_marker.set_linestyle('None')
if legend.markerscale != 1:
newsz = legline_marker.get_markersize()*legend.markerscale
legline_marker.set_markersize(newsz)
# we don't want to add this to the return list because
# the texts and handles are assumed to be in one-to-one
# correpondence.
legline._legmarker = legline_marker
return [legline, legline_marker]
plt.plot([0, 1], [0, 1], '-r', lw=1, label='Line')
plt.legend(handler_map={Line2D:MyHandlerLine2D()})
plt.show()
El método de @Brendan Wood usa la API proporcionada por pyplot
. En matplotlib, el object oriented style using axes is prefered. A continuación, se muestra cómo puede lograr esto usando el método axes
.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y1, linewidth=1.0, label='sin(x)')
ax.plot(x, y2, linewidth=1.0, label='cos(x)')
leg = ax.legend()
for line in leg.get_lines():
line.set_linewidth(4.0)
plt.show()
Por defecto, la leyenda contiene las líneas mismos. Por lo tanto, cambiar el ancho de línea de las líneas en el lienzo también cambiará las líneas en la leyenda (y viceversa, ya que son esencialmente el mismo objeto).
Una posible solución es usar una copia del artista del lienzo y cambiar solo el ancho de línea de la copia.
import numpy as np
import matplotlib.pyplot as plt
import copy
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1',linewidth=1.0)
ax.plot(x, y2, c='r', label='y2')
# obtain the handles and labels from the figure
handles, labels = ax.get_legend_handles_labels()
# copy the handles
handles = [copy.copy(ha) for ha in handles ]
# set the linewidths to the copies
[ha.set_linewidth(7) for ha in handles ]
# put the copies into the legend
leg = plt.legend(handles=handles, labels=labels)
plt.savefig('leg_example')
plt.show()
Una opción diferente sería utilizar una y una función de actualización handler_map
. Esto es de alguna manera automático, especificando que el mapa del manejador automáticamente haría que cualquier línea en la leyenda tenga 7 puntos de ancho.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1',linewidth=1.0)
ax.plot(x, y2, c='r', label='y2')
linewidth=7
def update(handle, orig):
handle.update_from(orig)
handle.set_linewidth(7)
plt.legend(handler_map={plt.Line2D : HandlerLine2D(update_func=update)})
plt.show()
El resultado es el mismo que el anterior.
- 1. Java2D: aumentar el ancho de línea
- 2. Las líneas más largas en la leyenda()
- 3. manipulación del ancho de línea para incubar en matplotlib
- 4. ¿Cómo establecer el ancho de línea de las mayúsculas de la barra de error en matplotlib?
- 5. ¿Aumentar el tamaño de letra en la leyenda de octava?
- 6. líneas más gruesas en la leyenda de gnuplot
- 7. matplotlib - Leyenda en subtrama separada
- 8. ¿Cómo aumentar el grosor de las líneas en los gráficos de líneas?
- 9. Matplotlib: el ancho de línea se agrega a la longitud de una línea
- 10. ¿Cómo aumentar el espacio entre líneas en CSS?
- 11. Gráficos de líneas transparentes Matplotlib
- 12. Creación de una leyenda de mapa de color en Matplotlib
- 13. Alineación de texto en una leyenda de Matplotlib
- 14. matplotlib - Global leyenda y el título de lado subtramas
- 15. ¿cómo hago una sola leyenda para muchas subtramas con matplotlib?
- 16. Cómo crear una leyenda arrastrable en matplotlib?
- 17. Eliminar la leyenda en una figura matplotlib
- 18. aumentar el grosor de la línea de geom_smooth
- 19. leyenda de matplotlib que muestra barras de error dobles
- 20. ¿Cómo configurar el ancho de la leyenda de Google Charts en JavaScript?
- 21. Cambiar el estilo de línea matplotlib gráfico medio
- 22. Matplotlib imshow() estirar para "ajustar el ancho"
- 23. Extracción de líneas dentro de la leyenda de fill.contour
- 24. Cuadro de texto con envoltura de línea en matplotlib?
- 25. Cómo dibujar una línea fuera de un eje en matplotlib (en las coordenadas de la figura)?
- 26. Cómo aumentar ninguna de las líneas (nivel de registro) en Logcat
- 27. Dibujar líneas con un ancho de línea que varía continuamente en el lienzo HTML
- 28. matplotlib - aumentar la resolución para ver detalles
- 29. Cómo eliminar líneas en un gráfico Matplotlib
- 30. ¿Cómo aumentar la altura de la línea en NetBeans 7?
bueno, estaba buscando esto antes. Espero que sea aceptado aquí;] – Alnitak
@Alnitak He actualizado esta respuesta con una opción diferente. – ImportanceOfBeingErnest