'How can you add a trendline to a seaborn's lineplot?

Here's what I'm trying to recreate in Seaborn (this was done with Matplotlib)

enter image description here

I see in Seaborn you could use a regplot() but this one is for scatter charts. Anyway, if I try to use it, it won't work because the x are datetime, so I did a mixture of Seaborn and Matplotlib, it works, but I don't like it, I think there must be a better way, Seaborn only.

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=':')

I get this picture:

enter image description here

Which I think is much more pleasant than the first one, but I just don't get how to add the trend lines using only seaborn.

Any idea?

=== EDIT ===

If I use regplot() it throws an exception...

sns.regplot(x="fecha", y="n", data=df)

This one... (it plots something tho, like a scatter chart, with points)

---------------------------------------------------------------------------
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'


Solution 1:[1]

I see this is a year old, but I just ran into and solved a similar problem so I'll leave the solution here.

The issue with your regplot is that you are using a column name as your x-axis, but (I assume), "fecha" is actually the name of your index and not the name of a column. If you were to take this line:

sns.regplot(x="fecha", y="n", data=df)

and change it to:

sns.regplot(x=df.index, y="n", data=df)

Then I would expect it to work. You may also want to take out the confidence interval which is drawn by default (add paramter ci=False) and change the color to be red or blue or whatever.

I know it's probably too late to help you, but I hope it helps someone!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 inteoryx