【问题标题】:Python - Seaborn kdeplot set point markPython - Seaborn kdeplot 设置点标记
【发布时间】:2021-06-17 17:57:10
【问题描述】:

我正在尝试做这样的事情 (Draw a point at the mean peak of a distplot or kdeplot in Seaborn)。我需要用值 13.72 标记点。

但是: 列表索引超出范围

字符串:x = ax.lines[0].get_xdata()

int_rate = df['int_rate']
ax = sns.kdeplot(int_rate, shade = True)

x = ax.lines[0].get_xdata()
y = ax.lines[0].get_ydata()
maxid = np.where(x == 13.72)
plt.plot(x[maxid],y[maxid], 'bo', ms=10)

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    问题在于设置shading = True seaborn 会绘制matplotlib.PolyCollection 而不是matplotlib.lines.Line2D 对象,因此ax.lines 是一个空列表(ax 不包含任何行)。

    您可以将阴影设置为 False 并按照您给定的示例进行操作,它会起作用,或者如果您想保留阴影并仍然通过访问该点的坐标来绘制最高点,您需要从 PolyCollection 对象中获取它。

    根据this stackoverflow question,您可以通过 PolyCollection 的get_paths() 方法来实现。

    如果你替换你的代码:

    x = ax.lines[0].get_xdata()
    y = ax.lines[0].get_ydata()
    maxid = np.where(x == 13.72)
    plt.plot(x[maxid],y[maxid], 'bo', ms=10)
    

    与:

    x, y = ax.get_children()[0].get_paths()[0].vertices.T
    maxid = y.argmax()
    plt.plot(x[maxid], y[maxid], 'bo', ms=10)
    

    您将获得标有最高点的阴影 kde 图:

    注意:使用的数据是来自 seaborn 的提示数据集。

    编辑: 看到你需要标记一个特定的 x 值,PolyCollection.get_paths()ax.lines[0].get_xdata() 不一定返回绘制的数据集中包含的精确 x 值,你可能想要在通过np.where(np.round(x,2) == 13.72)查找索引之前尝试对这些数组进行四舍五入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 2020-08-31
      • 2016-05-25
      • 1970-01-01
      相关资源
      最近更新 更多