用python在一个绘图(覆盖)中绘制两个等高线
我试图用python绘制两条等高线:用python在一个绘图(覆盖)中绘制两个等高线,python,matplotlib,contour,Python,Matplotlib,Contour,我试图用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
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()
但是我只得到一个轮廓,它是红色的。如果我评论红色的,我会得到蓝色的,但我不会两者都得到!我遗漏了什么?如果希望在同一窗口中显示两个轮廓,请在代码开头添加这一行
#将窗口分成两部分(垂直)
图(ax0,ax1)=plt.子批次(nrows=2)
然后,将轮廓添加到窗口并使其显示
#将轮廓添加到窗口
ax0.contourf(x1,x2,p1,100,cmap=cm.Blues)
ax1.contourf(x1,x2,p2,100,cmap=cm.Reds)
#表演!
plt.show()
您可以在这里看到详细信息。谢谢,但我希望它们在一个绘图中!相互重叠。我自己通过使用alpha找到了一个解决方案