手动设置seaborn/matplotlib散点图连续变量图例中显示的值

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

当图例包含连续变量(色调)时,有没有办法手动设置seaborn(或matplotlib)散点图图例中显示的值?

例如,在下面的图中,我可能想显示与

[0, 1, 2, 3]
的值相对应的颜色,而不是
[1.5, 3, 4.5, 6, 7.5]

np.random.seed(123)
x = np.random.randn(500)
y = np.random.randn(500)
z = np.random.exponential(1, 500)

fig, ax = plt.subplots()
hue_norm = (0, 3)
sns.scatterplot(
    x=x,
    y=y,
    hue=z,
    hue_norm=hue_norm,
    palette='coolwarm',
)

ax.grid()
ax.set(xlabel="x", ylabel="y")
ax.legend(title="z")
sns.despine()

python matplotlib plot seaborn visualization
1个回答
0
投票

您正在寻找的是

plt.legend(*scatter.legend_elements(num=[1, 2, 3, 4]))

这是我的完整代码(我只使用了 matplotlib)

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123)
x = np.random.randn(500)
y = np.random.randn(500)
z = np.random.exponential(1, 500)

fig, ax = plt.subplots()
scatter = plt.scatter(x=x, y=y, c=z)

ax.grid()
ax.set(xlabel="x", ylabel="y")
ax.legend(title="z")
plt.legend(*scatter.legend_elements(num=[1, 2, 3, 4]))
plt.tight_layout()
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.