[英]Python & Matplotlib: How to create a meshgrid to plot surf?
I want to plot the a probability density function z=f(x,y)
. 我想绘制一个概率密度函数
z=f(x,y)
。 I find the code to plot surf in Color matplotlib plot_surface command with surface gradient 我在使用表面渐变的Color matplotlib plot_surface命令中找到了用于绘制冲浪的代码
But I don't know how to conver the z
value into grid
so I can plot it The example code and my modification is below. 但是我不知道如何将
z
值转换为grid
因此我可以将其绘制出来示例代码及其修改如下。
import numpy as np
import matplotlib.pyplot as plt
from sklearn import mixture
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
%matplotlib inline
n_samples = 1000
# generate random sample, two components
np.random.seed(0)
shifted_gaussian = np.random.randn(n_samples, 2) + np.array([20, 5])
sample = shifted_gaussian
# fit a Gaussian Mixture Model with two components
clf = mixture.GMM(n_components=3, covariance_type='full')
clf.fit(sample)
# Plot it
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, .25)
Y = np.arange(-5, 5, .25)
X, Y = np.meshgrid(X, Y)
## In example Code, the z is generate by grid
# R = np.sqrt(X**2 + Y**2)
# Z = np.sin(R)
# In my case,
# for each point [x,y], the probability value is
# z = clf.score([x,y])
# but How can I generate a grid Z?
Gx, Gy = np.gradient(Z) # gradients with respect to x and y
G = (Gx**2+Gy**2)**.5 # gradient magnitude
N = G/G.max() # normalize 0..1
surf = ax.plot_surface(
X, Y, Z, rstride=1, cstride=1,
facecolors=cm.jet(N),
linewidth=0, antialiased=False, shade=False)
plt.show()
The original approach to plot z
is to generate through mesh. 绘制
z
的原始方法是通过网格生成。 But in my case, the fitted model cannot return result in grid-like
style, so the problem is how can I generete the grid-style z
value, and plot it? 但是在我的情况下,拟合模型无法以
grid-like
样式返回结果,所以问题是如何生成grid-style z
值并绘制它?
If I understand correctly, you basically have a function z
that takes a two scalar values x,y
in a list and returns another scalar z_val
. 如果我理解正确,您基本上就有一个函数
z
,该函数在列表中采用两个标量值x,y
并返回另一个标量z_val
。 In other words z_val = z([x,y])
, right? 换句话说
z_val = z([x,y])
,对吗?
If that's the case, the you could do the following (note that this is not written with efficiency in mind, but with focus on readability): 如果是这样,您可以执行以下操作(请注意,编写本文时并未考虑效率,而是着重于可读性):
from itertools import product
X = np.arange(15) # or whatever values for x
Y = np.arange(5) # or whatever values for y
N, M = len(X), len(Y)
Z = np.zeros((N, M))
for i, (x,y) in enumerate(product(X,Y)):
Z[np.unravel_index(i, (N,M))] = z([x,y])
If you want to use plot_surface
, then follow that with this: 如果要使用
plot_surface
,请遵循以下步骤:
X, Y = np.meshgrid(X, Y)
ax.plot_surface(X, Y, Z.T)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.