【问题标题】:Python & Matplotlib: How to create a meshgrid to plot surf?Python & Matplotlib:如何创建网格来绘制冲浪?
【发布时间】:2015-09-08 02:39:50
【问题描述】:

我想绘制概率密度函数z=f(x,y)。 我在Color matplotlib plot_surface command with surface gradient中找到了绘制冲浪的代码

但我不知道如何将 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()

绘制z的原始方法是通过网格生成。但就我而言,拟合模型无法以grid-like 样式返回结果,所以问题是如何生成grid-style z 值并绘制它?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果我理解正确,您基本上有一个函数z,它在一个列表中接受两个标量值x,y,并返回另一个标量z_val。换句话说z_val = z([x,y]),对吧?

    如果是这种情况,您可以执行以下操作(请注意,这不是为了提高效率而编写的,而是关注可读性):

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

    如果您想使用plot_surface,请按照以下方式进行操作:

    X, Y = np.meshgrid(X, Y)
    ax.plot_surface(X, Y, Z.T)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多