python - 在python中的一个绘图(叠加)中绘制两个轮廓
问题描述
我正在尝试在 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()
但是我只得到一个轮廓,即红色轮廓。如果我评论红色的,我会得到蓝色的,但我不会同时得到!我错过了什么?
解决方案
如果您希望在同一窗口中显示两个轮廓,请在代码开头添加此行。
# Seperate window into two parts(vertically)
fig, (ax0, ax1) = plt.subplots(nrows=2)
然后,将轮廓添加到窗口并显示出来。
# 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()
您可以在本文档中查看详细信息。
推荐阅读
- php - 回显 20 到 1000 之间的奇数,并使用 php 将数字 23、33、43、63、193、213、333、453、693、793、813、883、963 加粗
- python - 尝试第二次运行时 Python tkinter 应用程序崩溃
- python - 使用重复 ID 的最大值(Pandas DataFrame)
- scala - 用于生成图中所有拓扑排序的尾递归算法
- .htaccess - 如何强制 htaccess 删除最后一个破折号 (-}
- r - 如何过滤多个条件
- validation - 在 react-native 中针对多个相同的单词验证电子邮件
- javascript - 如何使用ajax将多个点发送到php文件
- angular7 - 将角度元素包含到表达式引擎 cms 网站中
- laravel - 'return $next($request)' 在 Laravel 中间件中有什么作用?