当图例包含连续变量(色调)时,有没有办法手动设置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()
您正在寻找的是
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()