Matplotlib 图例数字点不起作用

Matplotlib legend numpoints don't work

我有这样一段代码:

import matplotlib as mpl
from matplotlib import pyplot as plt

mpl.rcParams['legend.numpoints'] = 1
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=5, mode="expand", numpoints=1, borderaxespad=0.)

但是没用。点的数量仍然是 3。 有任何想法吗?

你图中带有 3 个点的图例句柄来自散点图。您可以使用 scatterpoints kwarg 控制它们。

numpoints 用于使用 plt.plot 创建的对象,而不是 plt.scatter

plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=5, mode="expand", numpoints=1, borderaxespad=0., 
           scatterpoints=1)

或者

mpl.rcParams['legend.scatterpoints'] = 1