241

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?

carl
  • 49,756
  • 17
  • 74
  • 82
  • 48
    I wish I could upvote this question multiple times. I HATE the default `numpoints=2` convention and was relieved to see someone had already taken the time to ask about it and get an answer. – Chris Redford Aug 14 '11 at 15:33
  • 24
    Mind: the option for scatterplots is `scatterpoints=1` – Marcos Alex Mar 06 '14 at 16:05

2 Answers2

255

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

K.-Michael Aye
  • 5,465
  • 6
  • 44
  • 56
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 7
    Thanks. I ran into this today also. Why is this not the default? – saltycrane May 27 '11 at 06:45
  • Could you add a link to the api? http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.legend I could just edit it in myself, but that seems rude. – tacaswell Sep 23 '13 at 18:20
  • ignore my deleted comments about why the default is what it is, they are wrong. – tacaswell Sep 23 '13 at 18:28
  • 2
    Is there any way to reduce the area the point take on the legend? – Yotam Jan 03 '14 at 09:13
  • @MarcosAlex: the last line of the answer says "See also scatterpoints, depending on your plot." – DSM Mar 06 '14 at 16:06
  • 3
    @DMS: I had not seen that. My mistake. You should also highlight it as code in order to make it more visible. – Marcos Alex Mar 07 '14 at 08:41
  • 2
    At long last, there are plans for numpoints=1 to be default in matplotlib 2.0! Huzzah! https://github.com/matplotlib/matplotlib/issues/4854 – DanHickstein Oct 28 '15 at 17:01
  • @Yotam I use handletextpad=0, which minimizes the distance between the point and its label (hence, reducing the area). I use it as in here: legend(frameon=False,fontsize=12,numpoints=1,handletextpad=0) I found it by printing mpl.rcParams and searching the "legend" options inside. – Leonardo Portes Dec 08 '16 at 12:29
24

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
mcgagnon
  • 346
  • 4
  • 8