【问题标题】:Label Points in Seaborn lmplot (python) with multiple plots在 Seaborn lmplot (python) 中使用多个绘图标记点
【发布时间】:2019-05-07 06:47:29
【问题描述】:

我正在尝试为我的 lmplot 中的每个数据点添加标签。我想通过索引标记每个数据点。现在我的代码如下:

p1=sns.lmplot(x="target", y="source", col="color", hue="color", 
              data=ddf, col_wrap=2, ci=None, palette="muted",
              scatter_kws={"s": 50, "alpha": 1})

def label_point(x, y, val, ax):
    a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
    for i, point in a.iterrows():
    ax.text(point['x']+.02, point['y'], str(point['val']))

label_point(ddf.target, ddf.source, ddf.chip, plt.gca())

这会将所有标签绘制到最后一个图上。

lmplot with labels

我尝试label_point(ddf.target, ddf.source, ddf.chip, plt.gcf()) 改为使用整个图形而不是当前轴,但随后它会引发错误。

ValueError: Image size of 163205x147206 pixels is too large. 
It must be less than 2^16 in each direction.

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    问题是,如果将整个数据集传递给它,标记函数应该如何知道要标记哪个图?!

    例如,您可以使用 pandas 的 .groupby 循环遍历独特的颜色并为每个颜色创建一个 seaborn.regplot。然后很容易单独标记每个轴。

    import matplotlib.pyplot as plt
    import numpy as np; np.random.seed(42)
    import pandas as pd
    import seaborn as sns
    
    def label_point(df, ax):
        for i, point in df.iterrows():
            ax.annotate("{:.1f}".format(point['val']), xy = (point['x'], point['y']),
                        xytext=(2,-2), textcoords="offset points")
    
    df = pd.DataFrame({"x": np.sort(np.random.rand(50)),
                       "y": np.cumsum(np.random.randn(50)),
                       "val" : np.random.randint(10,31, size=50),
                       "color" : np.random.randint(0,3,size=50 )})
    colors = ["crimson", "indigo", "limegreen"]
    
    fig, axes = plt.subplots(2,2, sharex=True, sharey=True)
    
    for (c, grp), ax in zip(df.groupby("color"), axes.flat):
        sns.regplot(x="x", y="y", data=grp, color=colors[c], ax=ax,
                    scatter_kws={"s": 25, "alpha": 1})
        label_point(grp, ax)
    
    axes.flatten()[-1].remove()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2020-11-09
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2020-03-07
      • 2019-08-29
      • 2014-07-17
      • 2018-02-28
      相关资源
      最近更新 更多