【问题标题】:Annotate markers values on Seaborn line plot (sns)在 Seaborn 线图 (sns) 上注释标记值
【发布时间】:2020-03-18 08:14:38
【问题描述】:

有没有办法在 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']))

这就是我想要的:

其中每个标记上的数值是行上标记本身的值。

【问题讨论】:

    标签: pandas matplotlib jupyter-notebook data-visualization seaborn


    【解决方案1】:

    是的,ax.text(...) 可以,默认情况下带注释的文本颜色为黑色。如果您想对标签进行颜色分组,那么一种可能的方法是执行 groupby ax.text(...) 循环(使用您预定义的调色板),如下所示,

    导入库并创建示例数据框

    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)
    

    输出

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2018-07-27
      • 1970-01-01
      • 2016-12-03
      • 2021-03-18
      • 2019-01-31
      • 2017-01-23
      • 1970-01-01
      相关资源
      最近更新 更多