Reputation:
I have a matrix of data (Xa.shape = 100x2) related to class A and another one for class B. I created both using the code below and I want to make a contour plot of the data. But what I tried doesn't work and just creates a blue picture. How do I create a proper contour plot of such data?
N = 1000
mean_a = [0, 0]
cov_a = [[1, 0], [0, 100]] # diagonal covariance
mean_b = [5, 0]
cov_b = [[5, 0], [0, 500]] # diagonal covariance
Xa = np.random.multivariate_normal(mean_a, cov_a, N)
Xb = np.random.multivariate_normal(mean_b, cov_b, N)
fig, ax3 = plt.subplots(nrows=1,ncols=1,figsize=(15,8))
ax3.contourf(Xa)
Upvotes: 0
Views: 2285
Reputation: 23637
Input: two-dimensional data points - Xa
is of shape [N, 2]. These are N poins in 2D space.
Desired output: contour plot in two dimensions. countourf
is the right tool for that, but take note of the documentation. This function draws the contour of a height map.
Missing step: turning individual data points into a height map.
The question is about distributions. To plot a distribution in 1D we would generate a histogram. To do so in 2D, well.. let's create a 2D histogram! numpy.histogram2d
will do just that for us. It creates a height map suitable for contourf
by dividing the space into regular bins and counting the number of data points that fall into each bin.
Here we go:
N = 1000
mean_a = [0, 0]
cov_a = [[2, 1], [1, 2]]
Xa = np.random.multivariate_normal(mean_a, cov_a, N)
fig, ax3 = plt.subplots(nrows=1,ncols=1,figsize=(15,8))
(counts, x_bins, y_bins) = np.histogram2d(Xa[:, 0], Xa[:, 1])
ax3.contourf(counts, extent=[x_bins[0], x_bins[-1], y_bins[0], y_bins[-1]])
Upvotes: 3