首页 文章

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

提问于
浏览
3

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

我知道在调用图例时可以更改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 回答

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

相关问题