更改图例标签时,Matplotlib图例颜色会更改

2024-06-28 20:18:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白我在这里做错了什么。我想将图例中的0和1更改为“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()

Plot 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(labels = ['zero', 'one'])

Plot 2

正如你所看到的,在第二张图片中,传奇故事的标题发生了变化,但颜色不再与情节的颜色相匹配


Tags: numbercoordinatedata颜色图片axhue图例
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)]

据我所知,您需要在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)

enter image description here

另一种方法:

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'])

enter image description here

相关问题 更多 >