Rafed Muhammad Yasir
Rafed Muhammad Yasir

Reputation: 469

Draw average line of scatter plot with matplotlib python

Im trying to fit an average line in a scatter plot with matplotlib. All im getting is this.

enter image description here

But I want it like this green line

enter image description here

I have tried the following two snippets for fitting the curve:

z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r-")

and

def func(x, a, b, c):
  return a * np.exp(-b * x) + c
popt, pcov = curve_fit(func, x, residual)
plt.plot(x, func(x, *popt), 'r-', label='fit')

Upvotes: 1

Views: 6718

Answers (1)

gustavovelascoh
gustavovelascoh

Reputation: 1228

As you no provide data I made my own and I've tried this:

N = 10000
xr = np.linspace(-1,6,N)
yr = -1*(np.ones(N)-1+xr) + 10*np.random.rand(N)
x = np.concatenate((xr[0:3800],xr[4900:]))
y = np.concatenate((yr[0:3800],yr[4900:]))

z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r-")
plt.scatter(x,y, s=2)

plt.show()

```

and this is the output I have, which is the expected output:

Scatter and plot

If you can share a piece of your data I could test it as well.

Upvotes: 4

Related Questions