Matplotlib散点图图例:自定义手柄看起来像微小的散点图

时间:2017-07-11 17:31:26

标签: matplotlib

我在matplotlib中制作了几个带有图例的散点图。标记大小很小,因此很难看到在图例句柄中绘制几个示例点。相反,我想格式化图例句柄看起来像微小的散点图(即点的小圆点云)。

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

HERE

我已经找到了涵盖这个主题的另一个主题但是没有多少运气。我知道这将涉及创建一个自定义艺术家,这个帖子提供了一些洞察力:How to make custom legend in matplotlib

提前感谢您的帮助。

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)

1 个答案:

答案 0 :(得分:1)

图例有scatteryoffsets个参数。您可以提供y坐标列表。那些应该在0和1之间。

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

enter image description here

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()