Reputation: 894
I've tried multiple ways of fitting a gaussian to this scatterplot, but nothing has worked for me. Any help would be greatly appreciated. Thanks!
from numpy import *
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
data = loadtxt("/home/***/****/***")
t,q = data[:,2], data[:,3]
t,q = loadtxt("/home/***/****/***", usecols = (2,3), unpack=True)
plt.scatter(t,q, marker='.', s=20)
plt.show()
Upvotes: 1
Views: 1883
Reputation: 9
This is coming a bit late! But the error message about too many values to to unpack can be fixed by including the option unpack=True
when loading data i.e.
data = np.loadtxt("/home/***/****/***", unpack=True, usecols=(2, 3))
Upvotes: 0
Reputation: 7602
It seems like you can just use the definitions of the mean and covariance parameters to fit them using maximum likelihood estimates from your data, right ?
import numpy as np
data = np.loadtxt("/home/***/****/***", usecols=(2, 3))
mu = data.mean(axis=0)
sigma = np.cov(data, rowvar=0)
In my understanding, this is what "fitting" means. However, it sounds like you're then looking to show these quantities on a plot. This can be a little trickier, but only because you need to use some linear algebra to find the eigenvectors of the estimated covariance matrix, and then use those to draw the covariance ellipse.
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
# compute eigenvalues and associated eigenvectors
vals, vecs = np.linalg.eigh(sigma)
# compute "tilt" of ellipse using first eigenvector
x, y = vecs[:, 0]
theta = np.degrees(np.arctan2(y, x))
ax = plt.subplot(111)
# eigenvalues give length of ellipse along each eigenvector
w, h = 2 * np.sqrt(vals)
ax.add_artist(Ellipse(mu, w, h, theta))
# show data on top of ellipse
ax.scatter(data[:, 0], data[:, 1])
plt.show()
Upvotes: 1