matplotlib Legend Markers Only Once

PythonMatplotlib

Python Problem Overview


I often plot a point on a matplotlib plot with:

x = 10
y = 100
plot(x, y, "k*", label="Global Optimum")
legend()

However, this causes the legend to put a star in the legend twice, such that it looks like:

* * Global Optimum

when I really want it to look like:

 *  Global Optimum

How do I do this?

Python Solutions


Solution 1 - Python

This should work:

legend(numpoints=1)

BTW, if you add the line

legend.numpoints     : 1      # the number of points in the legend line

to your matplotlibrc file, then this will be the new default.

[See also scatterpoints, depending on your plot.]

API: Link to API docs

Solution 2 - Python

I like to change my matplotlib rc parameters dynamically in every python script. To achieve this goal I simply use somthing like that at the beginning of my python files.

from pylab import *
rcParams['legend.numpoints'] = 1

This will apply to all plots generated from my python file.

EDIT: For those who do not like to import pylab, the long answer is

import matplotlib as mpl
mpl.rcParams['legend.numpoints'] = 1

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
QuestioncarlView Question on Stackoverflow
Solution 1 - PythonDSMView Answer on Stackoverflow
Solution 2 - PythonmcgagnonView Answer on Stackoverflow