在Seaborn折线图(sns)上标注标记值

7
有没有办法在Seaborn线图上注释标记值? 这是我的实际线图:
a4_dims = (20, 10)
fig, ax = plt.subplots(figsize=a4_dims)
p1 = sns.lineplot(x='NBags', y='value', hue='variable', style="variable", markers=True, dashes=False, 
             data=pd.melt(df_knn1, ['NBags']))

enter image description here

这是我想要的内容: 在此输入图片描述 每个标记上的数字值是该行标记本身的值。
1个回答

9

是的,您可以使用ax.text(...)实现,注释文本默认颜色为黑色。如果您想对标签进行着色分组,则可能的方法是通过ax.text(...)循环进行groupby(使用预定义的颜色调色板),如下所示,

导入库并创建示例数据框

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12345)
x = np.random.rand(15,3)
y = np.random.binomial(2, 0.5, (15,1))
z = np.concatenate((x,y),axis=1)

df = pd.DataFrame(z,columns=['x','y','mark_value','label'])
df['label'] = df['label'].astype(int)
print(df)
#            x         y  mark_value  label
# 0   0.929616  0.316376    0.183919      1
# 1   0.204560  0.567725    0.595545      1
# 2   0.964515  0.653177    0.748907      1
# 3   0.653570  0.747715    0.961307      1
# 4   0.008388  0.106444    0.298704      0
# 5   0.656411  0.809813    0.872176      1
# 6   0.964648  0.723685    0.642475      0
# 7   0.717454  0.467599    0.325585      2
# 8   0.439645  0.729689    0.994015      2
# 9   0.676874  0.790823    0.170914      1
# 10  0.026849  0.800370    0.903723      0
# 11  0.024676  0.491747    0.526255      1
# 12  0.596366  0.051958    0.895090      1
# 13  0.728266  0.818350    0.500223      2
# 14  0.810189  0.095969    0.218950      2

绘图代码

a4_dims = (20, 10)
fig, ax = plt.subplots(figsize=a4_dims)

palette = ['r','b','g']

p1 = sns.lineplot(x='x', y='y', hue='label', style='label', markers=True, dashes=False, 
             data=df, palette=palette)

for item, color in zip(df.groupby('label'),palette):
    #item[1] is a grouped data frame
    for x,y,m in item[1][['x','y','mark_value']].values:
        ax.text(x,y,f'{m:.2f}',color=color)

输出 在此输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接