如何在seaborn散点图中自定义颜色图例标记

问题描述 投票:0回答:1

我有一个seaborn散点图,其中的数据点通过(1)颜色和(2)标记来区分。这是生成绘图的最少代码:

d = {'x': [1, 2, 3, 4], 'y': [2,4,6,8], 'Set': ["Set 1", "Set 1 ", "Set 2", "Set 2"], "Test_Type": ["Direct", "Natural","Direct", "Natural"]}
df=pd.DataFrame(data=d, index=[0, 1, 2, 3])

sns.scatterplot(data=df, x="x", y="y", hue="Set", style="Test_Type")

plt.axis(ymin=0)
plt.xlabel("x values")
plt.ylabel("y values")
plt.legend()

plt.show()

“Set”图例标记是圆形(根据数据框中的“Set”列着色),但我希望它们是不同的东西,比如正方形。当然,我希望“Test_Type”标记仍然是原来的样子:十字、圆圈等等。我不想改变这一点。

我得到的与我想要得到的:

What I get vs What I'd like to get

我检查了 seaborn scatterplotmatplotlibmarkers 文档,但无济于事。

python matplotlib seaborn scatter-plot
1个回答
0
投票

您需要手动更改图例:

ax = sns.scatterplot(data=df, x="x", y="y", hue="Set", style="Test_Type")

handles, labels =  ax.get_legend_handles_labels()

change = [1, 2, 3]
for i in change:
    handles[i] = plt.Line2D([], [], color=handles[i].get_facecolor(),
                            marker='s', linestyle='')
ax.legend(handles, labels)

输出:

© www.soinside.com 2019 - 2024. All rights reserved.