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

2024-02-28

我正在 matplotlib 中用图例制作几个散点图。标记尺寸很小,因此在图例手柄中仅绘制几个示例点将很难看到。相反,我想将图例句柄格式化为看起来像微小的散点图(即,小的圆形点云)。

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

我已经寻找了涵盖该主题的另一个主题,但运气不佳。我知道这将涉及创建一个自定义艺术家,并且该线程对此提供了一些见解:如何在 matplotlib 中制作自定义图例 https://stackoverflow.com/questions/13303928/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)

传说中有一个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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Matplotlib 散点图图例:自定义手柄,使其看起来像微小的散点图 的相关文章

随机推荐