如何向seaborn 的线图添加趋势线?

lui*_*fer 5 python data-visualization matplotlib seaborn

这是我试图在 Seaborn 中重新创建的内容(这是使用 Matplotlib 完成的)

在此输入图像描述

我在 Seaborn 中看到您可以使用 a regplot(),但这个用于散点图。无论如何,如果我尝试使用它,它不会工作,因为它们是xdatetime所以我混合了Seaborn和Matplotlib,它可以工作,但我不喜欢它,我认为必须有更好的方法,只有Seaborn 。

x = range(0, len(hom.fecha))

plt.figure(figsize=(12, 9))
plt.style.use('fivethirtyeight')

chart = sns.lineplot(x='fecha', y='n', data=df, 
                     hue='sexo', markers=True)
chart.set(title='Personas Migrantes', ylabel='# Personas', xlabel="Fecha")

# Linear regressions for each sex
z = np.polyfit(x, hom.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="b", ls=":")

z = np.polyfit(x, muj.n, 1)
p = np.poly1d(z)
plt.plot(hom.fecha, p(x), c="r", ls=':')
Run Code Online (Sandbox Code Playgroud)

我得到这张照片:

在此输入图像描述

我认为这比第一个更令人愉快,但我只是不知道如何仅使用seaborn 添加趋势线。

任何想法?

===编辑===

如果我使用regplot()它会引发异常...

sns.regplot(x="fecha", y="n", data=df)
Run Code Online (Sandbox Code Playgroud)

这个......(它绘制了一些东西,比如带有点的散点图)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-0f60957abc3f> in <module>
----> 1 sns.regplot(x="fecha", y="n", data=df)

blah blah blah

TypeError: unsupported operand type(s) for *: 'Timestamp' and 'float'
Run Code Online (Sandbox Code Playgroud)

int*_*ryx 3

我发现这已经有一年了,但我刚刚遇到并解决了类似的问题,所以我将解决方案留在这里。

regplot 的问题是您使用列名称作为 x 轴,但是(我假设)“fecha”实际上是索引的名称,而不是列的名称。如果你要走这条线:

sns.regplot(x="fecha", y="n", data=df)
Run Code Online (Sandbox Code Playgroud)

并将其更改为:

sns.regplot(x=df.index, y="n", data=df)
Run Code Online (Sandbox Code Playgroud)

然后我希望它能起作用。您可能还想取出默认绘制的置信区间(添加参数 ci=False)并将颜色更改为红色或蓝色或其他。

我知道现在帮助你可能已经太晚了,但我希望它能帮助别人!