Remove line through marker in matplotlib legend

PythonMatplotlibLegend

Python Problem Overview


I have a matplotlib plot generated with the following code:

import matplotlib.pyplot as pyplot

Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
    ['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
    ax.plot(i+1, i+1, color=color,
            marker=mark,
            markerfacecolor='None',
            markeredgecolor=color,
            label=i)

ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend()

with this as the generated figure: matplotlib generated figure

I don't like the lines through the markers in the legend. How can I get rid of them?

Python Solutions


Solution 1 - Python

You can specify linestyle="None" as a keyword argument in the plot command:

import matplotlib.pyplot as pyplot

Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
    ['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
    ax.plot(i+1, i+1, color=color,
            marker=mark,
            markerfacecolor='None',
            markeredgecolor=color,
            linestyle = 'None',
            label=`i`)

ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(numpoints=1)
pyplot.show()

enter image description here

Since you're only plotting single points, you can't see the line attribute except for in the legend.

Solution 2 - Python

You can set the rcparams for the plots:

import matplotlib
matplotlib.rcParams['legend.handlelength'] = 0
matplotlib.rcParams['legend.numpoints'] = 1

enter image description here

All the legend.* parameters are available as keywords if you don't want the setting to apply globally for all plots. See matplotlib.pyplot.legend documentation and this related question:

https://stackoverflow.com/questions/19528579/legend-setting-numpoints-and-scatterpoints-in-matplotlib-does-not-work

Solution 3 - Python

To simply remove the lines once the data has been plotted:

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

Solution 4 - Python

You should use a scatterplot here

import matplotlib.pyplot as pyplot

Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
    ['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
    ax.scatter(i+1, i+1, color=color,
            marker=mark,
            facecolors='none',
            label=i)

ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(scatterpoints=1)

pyplot.show()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjlconlinView Question on Stackoverflow
Solution 1 - Pythontom10View Answer on Stackoverflow
Solution 2 - PythonHookedView Answer on Stackoverflow
Solution 3 - PythonblaltermanView Answer on Stackoverflow
Solution 4 - PythonM4rtiniView Answer on Stackoverflow