在python的一个图(覆盖图)中绘制两个轮廓

问题描述 投票:0回答:1

我正在尝试在python中绘制两个轮廓:

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()

但是我只得到一个轮廓,即红色的轮廓。如果我评论红色的,我会得到蓝色的,但我不会两者兼而有之!我想念什么?

python matplotlib contour
1个回答
0
投票
然后,将轮廓添加到窗口中并显示它们。

# Add contours to the window ax0.contourf(x1, x2, p1, 100, cmap=cm.Blues) ax1.contourf(x1, x2, p2, 100, cmap=cm.Reds) # Show! plt.show()

您可以在此documentation中查看详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.