Я пытаюсь построить два контура в питоне:
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm # Colormaps
import matplotlib.gridspec as gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable
import seaborn as sns
sns.set_style('darkgrid')
np.random.seed(42)
plt.style.use('seaborn') # pretty matplotlib plots
plt.rcParams['figure.figsize'] = (12, 8)
x1 = [0,0.5,1,1,1.5,1.5,2,2,2.5]
y1= [1,2,1,3,0,2,1,3,2]
x2=[-2,-1.5,-1.5,-1,-0.5,0.5,0.5,1,1.5,1.5]
y2=[-1,0,1,-1,0.5,0.5,-0.5,-1,0.5,-0.5]
d1=np.stack((x1,y1))
print(d1)
d2=np.stack((x2,y2))
m1=d1.mean(1)
m1=m1.reshape(2,-1)
m2=d2.mean(1)
m2=m2.reshape(2,-1)
cov1 =np.cov(d1)
cov2 =np.cov(d2)
print(np.shape(m1))
print(cov2)
#plt.scatter(x1,y1)
#from scipy.stats import multivariate_normal
#var.pdf([1,0])
def multivariate_normal(x, d, mean, covariance):
"""pdf of the multivariate normal distribution."""
x_m = x - mean
return (1. / (np.sqrt((2 * np.pi)**d * np.linalg.det(covariance))) *
np.exp(-(np.linalg.solve(covariance, x_m).T.dot(x_m)) / 2))
# Plot bivariate distribution
def generate_surface(mean, covariance, d):
"""Helper function to generate density surface."""
nb_of_x = 100 # grid size
x1s = np.linspace(-5, 5, num=nb_of_x)
x2s = np.linspace(-5, 5, num=nb_of_x)
x1, x2 = np.meshgrid(x1s, x2s) # Generate grid
pdf = np.zeros((nb_of_x, nb_of_x))
# Fill the cost matrix for each combination of weights
for i in range(nb_of_x):
for j in range(nb_of_x):
pdf[i,j] = multivariate_normal(
np.matrix([[x1[i,j]], [x2[i,j]]]),
d, mean, covariance)
return x1, x2, pdf # x1, x2, pdf(x1,x2)
# subplot
# fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(16,8))
d = 2 # number of dimensions
x1, x2, p1 = generate_surface(m1, cov1, d)
x1, x2, p2 = generate_surface(m2, cov2, d)
# Plot bivariate distributions
plt.contourf(x1, x2, p1, 100, cmap=cm.Blues)
plt.contourf(x1, x2, p2, 100, cmap=cm.Reds)
plt.show()
Однако я получаю только один контур - красный. Если я прокомментирую красный, я получу синий, но не получу оба! Что я пропустил?