Matplotlib散点图图例:自定义控制柄,使其看起来像小散点图

Matplotlib散点图图例:自定义控制柄,使其看起来像小散点图,matplotlib,Matplotlib,我在matplotlib中绘制了两个带有图例的散点图。标记尺寸很小,因此很难在图例控制柄中仅绘制几个示例点。相反,我希望将图例控制柄的格式设置为微小的散点图(即点的小圆形云) 我知道在调用图例时可以更改scatterpoints关键字,如图(下图和代码)所示,这样做是我想要的,但是句柄似乎是沿着半水平线分组的,我希望它们看起来更随机 我已经寻找了另一个主题,但运气不太好。我知道这将涉及到创建一个自定义的艺术家,这条线索提供了一些见解: 提前感谢您的帮助 import matplotlib.py

我在matplotlib中绘制了两个带有图例的散点图。标记尺寸很小,因此很难在图例控制柄中仅绘制几个示例点。相反,我希望将图例控制柄的格式设置为微小的散点图(即点的小圆形云)

我知道在调用图例时可以更改scatterpoints关键字,如图(下图和代码)所示,这样做是我想要的,但是句柄似乎是沿着半水平线分组的,我希望它们看起来更随机

我已经寻找了另一个主题,但运气不太好。我知道这将涉及到创建一个自定义的艺术家,这条线索提供了一些见解:

提前感谢您的帮助

import matplotlib.pyplot as mp
import numpy

a = numpy.random.rand(1000)
b = numpy.random.rand(1000)
c = numpy.random.rand(1000)
d = numpy.random.rand(1000)

fontsize=12
fig = mp.figure(figsize=(3,3))
ax = fig.add_subplot(111)
ax.scatter(a, b, color='0.25', s=1, label='label1')
ax.scatter(c, d, color='firebrick', s=1, label='label2')
ax.tick_params(labelsize=fontsize)

handles, labels = ax.get_legend_handles_labels()
leg = ax.legend(handles, labels, fontsize=fontsize, scatterpoints=10, bbox_to_anchor=(1.03,1.0), bbox_transform=ax.transAxes, loc='upper left', borderaxespad=0, labelspacing=0.25, fancybox=False, edgecolor='0', framealpha=0, borderpad=0.25, handletextpad=0.5, markerscale=1, handlelength=0)

图例有一个
scatteryoffsets
参数。您可以提供y坐标的列表。这些值应介于0和1之间

yoffsets = [.1,.7,.3,.1,.8,.4,.2,.6,.7,.5]
plt.legend(scatteryoffsets=yoffsets, scatterpoints=len(yoffsets) )


我感谢你的帮助!我从来都不知道这个漫无目的的补偿选项,我很高兴我可以避开创建自定义艺术家。
import matplotlib.pyplot as plt
import numpy
import matplotlib.legend_handler
import matplotlib.collections

a = numpy.random.rand(1000)
b = numpy.random.rand(1000)
c = numpy.random.rand(1000)
d = numpy.random.rand(1000)

fontsize=12
fig = plt.figure(figsize=(3,3))
ax = fig.add_subplot(111)
sc  = ax.scatter(a, b, color='0.25', s=1, label='label1')
sc2 = ax.scatter(c, d, color='firebrick', s=1, label='label2')
ax.tick_params(labelsize=fontsize)

yoffsets = [.1,.7,.3,.1,.8,.4,.2,.6,.7,.5]
plt.legend(scatteryoffsets=yoffsets, scatterpoints=len(yoffsets),
           framealpha=1)

plt.show()