我正在使用以下代码绘制通过原点的 3d 随机平面。
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Number of hyperplanes
n = 20
#Dimension of space
d = 3
plt3d = plt.figure().gca(projection='3d')
for i in xrange(n):
#Create random point on unit sphere
v = np.random.normal(size = d)
v = v/np.sqrt(np.sum(v**2))
# create x,y
xx, yy = np.meshgrid(range(-5,5), range(-5,5))
z = (-v[0] * xx - v[1] * yy)/v[2]
# plot the surface
plt3d.plot_surface(xx, yy, z, alpha = 0.5)
plt.show()
但是看图片我不相信他们是统一选择的。我做错了什么?
最佳答案
您的代码生成的平面具有随机分布的法线。它们只是看起来不像那样,因为 z 尺度比 x 和 y 尺度大得多。
您可以通过生成点来生成更好看的图像 均匀分布在平面上。为此,请根据以下参数对平面进行参数化 新坐标 (u, v),然后在均匀间隔的网格上对平面进行采样 (u,v) 点。然后将这些 (u,v) 点转换为 (x,y,z) 空间中的点。
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import itertools as IT
def points_on_sphere(dim, N, norm=np.random.normal):
"""
http://en.wikipedia.org/wiki/N-sphere#Generating_random_points
"""
normal_deviates = norm(size=(N, dim))
radius = np.sqrt((normal_deviates ** 2).sum(axis=0))
points = normal_deviates / radius
return points
# Number of hyperplanes
n = 10
# Dimension of space
d = 3
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
points = points_on_sphere(n, d).T
uu, vv = np.meshgrid([-5, 5], [-5, 5], sparse=True)
colors = np.linspace(0, 1, len(points))
cmap = plt.get_cmap('jet')
for nhat, c in IT.izip(points, colors):
u = (0, 1, 0) if np.allclose(nhat, (1, 0, 0)) else np.cross(nhat, (1, 0, 0))
u /= math.sqrt((u ** 2).sum())
v = np.cross(nhat, u)
u = u[:, np.newaxis, np.newaxis]
v = v[:, np.newaxis, np.newaxis]
xx, yy, zz = u * uu + v * vv
ax.plot_surface(xx, yy, zz, alpha=0.5, color=cmap(c))
ax.set_xlim3d([-5,5])
ax.set_ylim3d([-5,5])
ax.set_zlim3d([-5,5])
plt.show()
或者,您可以使用 Till Hoffmann's pathpatch_2d_to_3d utility function 来避免复杂的数学运算:
for nhat, c in IT.izip(points, colors):
p = patches.Rectangle((-2.5, -2.5), 5, 5, color=cmap(c), alpha=0.5)
ax.add_patch(p)
pathpatch_2d_to_3d(p, z=0, normal=nhat)
ax.set_xlim3d([-5,5])
ax.set_ylim3d([-5,5])
ax.set_zlim3d([-5,5])
plt.show()
关于python - 如何绘制随机平面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26148813/