【问题标题】:setting a legend matching the colours in pyplot.scatter设置与 pyplot.scatter 中的颜色匹配的图例
【发布时间】:2020-05-03 21:23:46
【问题描述】:

假设我的数据按以下方式组织:

x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
colours = [1, 1, 0, 1, -1]
labels = ["a", "a", "b", "a", "c"]

我想用这个做一个散点图:

axis = plt.gca()
axis.scatter(x_values, y_values, c=colours)

我想要一个包含 3 个类别的图例:“a”、“b”和“c”。

鉴于此列表中的类别与colours 列表中点的顺序匹配,我可以使用labels 列表来制作此图例吗?

我需要为每个类别分别运行scatter 命令吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果您想使用颜色图,您可以为colors 列表中的每个唯一条目创建一个图例条目,如下所示。这种方法适用于任意数量的值。图例句柄是 plot 的标记,因此它们与散点匹配。

    import matplotlib.pyplot as plt
    
    x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
    y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
    colors = [1, 1, 0, 1, -1]
    labels = ["a", "a", "b", "a", "c"]
    clset = set(zip(colors, labels))
    
    ax = plt.gca()
    sc = ax.scatter(x_values, y_values, c=colors, cmap="brg")
    
    handles = [plt.plot([],color=sc.get_cmap()(sc.norm(c)),ls="", marker="o")[0] for c,l in clset ]
    labels = [l for c,l in clset]
    ax.legend(handles, labels)
    
    plt.show()
    

    【讨论】:

    • 为什么必须手动使用这种规范化来设置plot中的颜色? scatter 和 plot 中的颜色确定机制不一样吗?这几年我偶尔使用matplotlib,我一直很困惑。
    • 您有一个scatter,但有三个plots。因此,虽然散点图会知道归一化,但每个单独的图都不知道它。但是从某种意义上说,您是正确的,我们不需要手动设置归一化,而是可以重用分散的归一化。我相应地更新了答案。
    【解决方案2】:

    只是一个评论,不完全回答问题:

    如果使用“seaborn”,则完全是一行:

    import seaborn as sns 
    x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
    y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
    #colors = [1, 1, 0, 1, -1]
    labels = ["a", "a", "b", "a", "c"]
    ax = sns.scatterplot(x=x_values, y=y_values, hue=labels)
    

    PS

    但问题是关于 matplotlib,所以。 我们上面有答案,也可以看看: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html 小节:“自动创建图例”。

    但是我觉得将这些示例修改为您需要的内容并不容易。

    【讨论】:

      【解决方案3】:

      您总是可以按如下方式制作自己的图例:

      import matplotlib.pyplot as plt
      import matplotlib.patches as mpatches
      
      x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
      y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
      
      a = 'red'
      b = 'blue'
      c = 'yellow'
      
      colours = [a, a, b, a, c]
      labels = ["a", "a", "b", "a", "c"]
      
      axis = plt.gca()
      axis.scatter(x_values, y_values, c=colours)
      
      # Create a legend
      handles = [mpatches.Patch(color=colour, label=label) for label, colour in [('a', a), ('b', b), ('c', c)]]
      plt.legend(handles=handles, loc=2, frameon=True)
      
      plt.show()
      

      看起来像:

      【讨论】:

      • 我正在尝试理解您的答案,但在plt.legend 的帮助下找不到“handles”关键字。它是如何工作的?我想在这种情况下,“句柄”是绘制图例条目的图形部分的东西(帮助称为“图例艺术家”)。我说的对吗?
      • 相当多的 matplotlib 函数将任何未知关键字传递给子函数来处理,但是这个 link 应该会有所帮助。
      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多