【问题标题】:Different scatterplot markers with the same label具有相同标签的不同散点图标记
【发布时间】:2015-07-21 13:04:51
【问题描述】:

我遇到了与Matplotlib, legend with multiple different markers with one label 类似的问题。由于这个问题Combine two Pyplot patches for legend,我能够实现以下目标。

fig = pylab.figure()
figlegend = pylab.figure(figsize=(3,2))
ax = fig.add_subplot(111)
point1 = ax.scatter(range(3), range(1,4), 250, marker=ur'$\u2640$', label = 'S', edgecolor = 'green')
point2 = ax.scatter(range(3), range(2,5), 250, marker=ur'$\u2640$', label = 'I', edgecolor = 'red')
point3 = ax.scatter(range(1,4), range(3),  250, marker=ur'$\u2642$', label = 'S', edgecolor = 'green')
point4 = ax.scatter(range(2,5), range(3), 250, marker=ur'$\u2642$', label = 'I', edgecolor = 'red')
figlegend.legend(((point1, point3), (point2, point4)), ('S','I'), 'center',  scatterpoints = 1, handlelength = 1)
figlegend.show()
pylab.show()

但是,我的两个(金星和火星)标记在图例中重叠。我尝试使用句柄长度,但这似乎没有帮助。任何建议或 cmets 都会有所帮助。

【问题讨论】:

    标签: matplotlib label legend scatter-plot markers


    【解决方案1】:

    一种可能的解决方法是在第一列中创建一个带有空白标签的两列图例:

    figlegend.legend((point1, point2, point3, point4), (' ', ' ', 'S', 'I'), 
                     'center',  scatterpoints = 1, ncol = 2)
    

    【讨论】:

    • 您还可以调整列间距以将它们靠得更近。
    【解决方案2】:

    这是我的解决方法 MWE。我实际上绘制了两个额外的“图”,point_g 和point_r,它们具有我们将使用的图例句柄。然后我用白色方形标记覆盖它们。根据需要绘制剩余的图。

    import matplotlib.pyplot as plt
    plt.rc('text', usetex=True)
    plt.rc('text', **{'latex.preamble': '\\usepackage{wasysym}'})
    plt.rc('lines', **{'markersize':20})
    
    fig = plt.figure()
    
    point_g, = plt.plot((0,), (0,), ls='none', marker='$\\male\\female$', mec='g')
    point_r, = plt.plot((0,), (0,), ls='none', marker='$\\male\\female$', mec='r')
    plt.plot((0,), (0,), marker='s', mec='w', mfc='w')
    
    plt.plot(range(3), range(1,4), ls='none', marker='$\\male$', mec='g')
    plt.plot(range(3), range(2,5), ls='none', marker='$\\male$', mec='r')
    plt.plot(range(1,4), range(3), ls='none', marker='$\\female$', mec='g')
    plt.plot(range(2,5), range(3), ls='none', marker='$\\female$', mec='r')
    
    plt.axis([-0.1, 4.1, -0.1, 4.1])
    plt.legend((point_g, point_r), ('Green', 'Red'),  markerscale=1.6, numpoints=1,
               borderpad=0.8, handlelength=3, labelspacing=1)
    
    plt.show()
    

    注意:如果您使用 unicode 符号,则不需要 LaTeX 序言。我无法让它们在我的系统(Linux)上工作,所以我使用了 LaTeX 符号。此方法适用于所有符号,只需删除plt.rc 命令并将\\male 和\\female 更改为您的Unicode 字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2021-09-19
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多