【问题标题】:matplotlib add legend with multiple entries for a single scatter plotmatplotlib 为单个散点图添加具有多个条目的图例
【发布时间】:2020-05-20 05:17:16
【问题描述】:

我正在为如下所示的数据集制作散点图:

x = [1, 1, 2, 2, 3, 3, 4, 4]
y = [1, 2, 3, 4, 1, 2, 3, 4]
labels = [1, 3, 0, 2, 2, 1, 0, 3]

colors = np.array(plt.rcParams['axes.prop_cycle'].by_key()['color'])

plt.scatter(x, y, color=colors[labels])

如果我调用plt.legend,对于整个数据集,将只显示一个条目,并带有第一个符号。如何创建一个包含所有四个元素的图例,就像我绘制了四个单独的数据集一样显示?

可能相关:Matplotlib histogram with multiple legend entries
基于:Matplotlib, how to loop?

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    您可以为标签集绘制空列表:

    for l in set(labels):
        plt.scatter([],[], color=colors[l], label=l)
    plt.legend()
    

    【讨论】:

    • 这绝对是个好主意。如果我不标记原始数据集,它就不会出现在图例中。
    • 我想我找到了一个可以说比这更有效的内置方法。
    【解决方案2】:

    我认为整体上最简单的解决方案是将所有工作委托给 matplotlib。该方法在此处描述:https://matplotlib.org/gallery/lines_bars_and_markers/scatter_with_legend.html#automated-legend-creation。对于这种简化的方法,只需使用 PathCollection's legend_elements 方法即可:

    s = plt.scatter(x, y, c=labels)
    plt.legend(*s.legend_elements())
    

    更改颜色图或将标签替换为其他内容(例如文本)很简单:

    text_labels = ['one', 'two', 'three', 'four']
    s = plt.scatter(x, y, c=labels, cmap='jet', vmin=0, vmax=4)
    plt.legend(s.legend_elements()[0], text_labels)
    

    如果labels 还不是[0-n) 范围内元素的排序数组,则可以使用np.unique 轻松获得:

    labels = ['b', 'd', 'a', 'c', 'c', 'b', 'a', 'd']
    text_labels, labels = np.unique(labels, return_inverse=True)
    

    【讨论】:

      【解决方案3】:

      只是实现预期结果的另一种方式。我使用this 解决方案消除了重复项

      for i, j, l in zip(x, y, labels):
          plt.scatter(i, j, c=colors[l], label=l)
      
      handles, labels = plt.gca().get_legend_handles_labels()
      by_label = dict(zip(labels, handles))
      plt.legend(by_label.values(), by_label.keys())
      

      【讨论】:

      • 技术上是的,但我真的试图避免将每个点放在单独的对象中。我觉得这不会很好地扩展。
      • 我想我找到了一个内置的方法。我从来不知道 matplotlib 会为你做到这一点。
      猜你喜欢
      • 2019-03-22
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2021-01-28
      • 2017-10-14
      • 1970-01-01
      • 2019-08-22
      相关资源
      最近更新 更多