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

例如,在下面的图中,我可能会显示对应于值[0, 1, 2, 3]而不是[1.5, 3, 4.5, 6, 7.5]的 colored颜色

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()

enter image description here

推荐答案

Seaborn创建散点图与matplotlib有点不同.这样,散点图可以以更多的方式定制.对于图例,Seaborn 0.13使用自定义的Line2D个元素(旧版本的Seaborn使用PathCollection).

以下方法:

  • 用一个等价的matplotlib范数替换Seaborn的hue_norm=(0, 3)
  • 创建虚拟Line2D个元素作为图例句柄
  • 复制所有属性(大小、边缘 colored颜色 、...)Seaborn创建的图例句柄
  • 然后根据规范和 colored颜色 映射改变标记 colored颜色

如果散点图不同,方法可能需要一些调整.该代码已经使用Matplotlib 3.8.3和Seaborn 0.13.2(和0.12.2)进行了测试.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from matplotlib.lines import Line2D

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 = plt.Normalize(vmin=0, vmax=3)
sns.scatterplot(x=x, y=y, hue=z, hue_norm=hue_norm, palette='coolwarm', ax=ax)

legend_keys = [0, 1, 2, 3]
handles = [Line2D([], []) for _ in legend_keys]
cmap = plt.get_cmap('coolwarm')
for h, key in zip(handles, legend_keys):
    if type(ax.legend_.legend_handles[0]) == Line2D:
        h.update_from(ax.legend_.legend_handles[0])
    else:
        h.set_linestyle('')
        h.set_marker('o')
        h.set_markeredgecolor(ax.legend_.legend_handles[0].get_edgecolor())
        h.set_markeredgewidth(ax.legend_.legend_handles[0].get_linewidth())
    h.set_markerfacecolor(cmap(hue_norm(key)))
    h.set_label(f'{key}')
ax.legend(handles=handles, title='z')
sns.despine()
plt.show()

seaborn scatterplot with custom legend

Python相关问答推荐

根据不同列的值在收件箱中移动数据

当多个值具有相同模式时返回空

将特定列信息移动到当前行下的新行

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

max_of_three使用First_select、second_select、

对某些列的总数进行民意调查,但不单独列出每列

如何访问所有文件,例如环境变量

Mistral模型为不同的输入文本生成相同的嵌入

在Python中管理打开对话框

try 将一行连接到Tensorflow中的矩阵

在np数组上实现无重叠的二维滑动窗口

如何设置视频语言时上传到YouTube与Python API客户端

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

使用Python从rotowire中抓取MLB每日阵容

从旋转的DF查询非NaN值

为什么Python内存中的列表大小与文档不匹配?

如何在Gekko中使用分层条件约束

操作布尔值的Series时出现索引问题

当lambda函数作为参数传递时,pyo3执行

将时间序列附加到数据帧