matplotlib图例标记仅一次

问题:matplotlib图例标记仅一次

我经常使用以下命令在matplotlib图上绘制点:

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

但是,这会导致图例两次在图例中放置一颗星星,如下所示:

* * Global Optimum

当我真的希望它看起来像:

 *  Global Optimum

我该怎么做呢?

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?


回答 0

这应该工作:

legend(numpoints=1)

顺便说一句,如果您添加行

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

到您的matplotlibrc文件,那么这将是新的默认设置。

[另请参见散点图,具体取决于您的情节。]

API:链接到API文档

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


回答 1

我喜欢在每个python脚本中动态更改matplotlib rc参数。为了实现这个目标,我只是在python文件的开头使用了类似的东西。

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

这将适用于从我的python文件生成的所有图。

编辑:对于那些谁不喜欢导入pylab,长答案是

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

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