【问题标题】:Matplotlib Legend colors change when changing legend labels更改图例标签时,Matplotlib 图例颜色会发生变化
【发布时间】:2021-04-10 13:00:27
【问题描述】:

我不明白我在这里做错了什么。我想将图例中的 0 和 1 更改为“零”和“一”,但不知何故这也会改变图例中的颜色。

这是我得到第一张照片的方式:

sns.scatterplot(ax = axes, data = data_pcoa, x = "Coordinate 0", 
                y = "Coordinate 1", hue = "Number", palette = ["orange", "blue"])
axes.set(xlabel = "1st PCo", ylabel = "2nd PCo")
axes.legend()

这就是我获得第二张图片的方式:

sns.scatterplot(ax = axes, data = data_pcoa, x = "Coordinate 0", 
                y = "Coordinate 1", hue = "Number", palette = ["orange", "blue"])
axes.set(xlabel = "1st PCo", ylabel = "2nd PCo")
axes.legend(labels = ['zero', 'one'])

如您所见,在第二张图片中,图例标题已更改,但颜色不再与情节匹配。

【问题讨论】:

    标签: python matplotlib colors legend


    【解决方案1】:

    据我了解,您需要在 scatterplot 中自定义标签名称。

    这是回答您问题的小例子。

    import seaborn as sns
    import matplotlib.pyplot as plt
    tips = sns.load_dataset("tips")
    
    g = sns.lmplot(
        x="total_bill", 
        y="tip", 
        hue="smoker", 
        data=tips,  
        legend=False
    )
    
    plt.legend(title='My Title', loc='upper left', labels=['Zero', 'One'])
    plt.show(g)
    

    另一种方法:

    sns.scatterplot(data = tips, x = "total_bill", 
                    y = "tip", hue = "smoker", palette = ["orange", "blue"])
    ax = plt.gca()
    ax.set(xlabel = "1st PCo", ylabel = "2nd PCo")
    ax.legend(labels = ['zero', 'one'])
    

    【讨论】:

    • 您好,杰伊,非常感谢您的回复。我编辑了我的帖子,因为我已经尝试过了,很遗憾没有成功。
    • 不工作是什么意思? Seaborn 在技术上是 matplotlib 的包装。我还在我的回答中加入了另一种方法。
    【解决方案2】:

    我通过创建自定义图例解决了这个问题。这不是很优雅,但可以完成工作。不过这很奇怪,因为当我在类似的数据集上使用 axes.legend(labels = ["zero", "one"] 时,它确实有效。无论如何,这解决了我的问题(但我很想知道一个更优雅的解决方案):

    legend_elements = [Line2D([0], [0], color = 'w', markerfacecolor = 'b', marker = 'o', label='one',  markersize=8),
                       Line2D([0], [0], color = 'w', markerfacecolor = 'orange',  marker='o', label='zero', markersize=8)]
    

    【讨论】:

      猜你喜欢
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 2021-08-16
      • 2018-02-15
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多