How to remove lines from markers in the legend

Question:

I’ve plotted some data as error bars linked by lines, as you can see from the
picture.

I would like to show only the markers in the legend (I don’t want to show the lines in the middle of the markers). I don’t want to remove the lines from the diagram, only in the legend.

I tried the code below from this thread:

handles, labels = ax.get_legend_handles_labels()
for h in handles: h.set_linestyle("")
ax.legend(handles, labels)

It removed the lines also from the diagram.

Is there a way to do it?

Asked By: Djova

||

Answers:

Updating…
There is a specific option to do this…

import numpy as np
import matplotlib.pyplot as plt

# dummy data
x = np.arange(10)
y1 = 2*x
y2 = 3*x

fig, ax = plt.subplots()

line1, = ax.plot(x, y1, c='blue', marker='x')
line2, = ax.plot(x, y2, c='red', marker='o')

ax.legend([line1, line2], ['data1', 'data2'], handlelength=0.)
plt.show()

enter image description here

Answered By: Joao_PS

Instead of drawing the graph twice, which might come with some overhead, you could use matplotlib.rcParams['legend.handlelength'] = 0. This is a global parameter, which means it would affect every other graph after the fact.

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

matplotlib.rcParams['legend.handlelength'] = 0


x = np.linspace(-np.pi/2, np.pi/2, 31)
y = np.cos(x)**3

# 1) remove points where y > 0.7
x2 = x[y <= 0.7]
y2 = y[y <= 0.7]

# 2) mask points where y > 0.7
y3 = np.ma.masked_where(y > 0.7, y)

# 3) set to NaN where y > 0.7
y4 = y.copy()
y4[y3 > 0.7] = np.nan

plt.plot(x*0.1, y, 'o-', color='lightgrey', label='No mask')
plt.plot(x2*0.4, y2, 'o-', label='Points removed')
plt.plot(x*0.7, y3, 'o-', label='Masked values')
plt.plot(x*1.0, y4, 'o-', label='NaN values')
plt.legend()
plt.title('Masked and NaN data')
plt.show()

plot image without line

If you want to only use it for one graph, you can wrap the code responsible for the graph with:

with plt.rc_context({"legend.handlelength": 0,}):

EDIT: the other answer has a better solution for per graph legends.

Answered By: imad.nyc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.