gpt4 book ai didi

python - 3D绘图: smooth plot on x axis

转载 作者:行者123 更新时间:2023-12-01 17:56:56 25 4
gpt4 key购买 nike

我有一个 3D 多边形图,并希望在 y 轴上平滑该图(即我希望它看起来像“曲面图的切片”)。

考虑这个 MWE(取自 here ):

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np
from scipy.stats import norm

fig = plt.figure()
ax = fig.gca(projection='3d')

xs = np.arange(-10, 10, 2)
verts = []
zs = [0.0, 1.0, 2.0, 3.0]

for z in zs:
ys = np.random.rand(len(xs))
ys[0], ys[-1] = 0, 0
verts.append(list(zip(xs, ys)))

poly = PolyCollection(verts, facecolors=[mcolors.to_rgba('r', alpha=0.6),
mcolors.to_rgba('g', alpha=0.6),
mcolors.to_rgba('b', alpha=0.6),
mcolors.to_rgba('y', alpha=0.6)])
poly.set_alpha(0.7)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlabel('X')
ax.set_xlim3d(-10, 10)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 4)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 1)
plt.show()

现在,我想用正态分布替换这四个图(以理想地形成连续线)。

我在这里创建了发行​​版:

def get_xs(lwr_bound = -4, upr_bound = 4, n = 80):
""" generates the x space betwee lwr_bound and upr_bound so that it has n intermediary steps """
xs = np.arange(lwr_bound, upr_bound, (upr_bound - lwr_bound) / n) # x space -- number of points on l/r dimension
return(xs)

xs = get_xs()

dists = [1, 2, 3, 4]

def get_distribution_params(list_):
""" generates the distribution parameters (mu and sigma) for len(list_) distributions"""
mus = []
sigmas = []
for i in range(len(dists)):
mus.append(round((i + 1) + 0.1 * np.random.randint(0,10), 3))
sigmas.append(round((i + 1) * .01 * np.random.randint(0,10), 3))
return mus, sigmas

mus, sigmas = get_distribution_params(dists)

def get_distributions(list_, xs, mus, sigmas):
""" generates len(list_) normal distributions, with different mu and sigma values """
distributions = [] # distributions

for i in range(len(list_)):
x_ = xs
z_ = norm.pdf(xs, loc = mus[i], scale = sigmas[0])
distributions.append(list(zip(x_, z_)))
#print(x_[60], z_[60])

return distributions

distributions = get_distributions(list_ = dists, xs = xs, mus = mus, sigmas = sigmas)

但是将它们添加到代码中(使用 poly = PolyCollection(distributions, ...)ax.add_collection3d(poly, zs=distributions, zdir='z') code> 抛出 ValueError (ValueError:输入操作数的维度超过轴重新映射允许的维度)我无法解析。

最佳答案

该错误是由于传递 distributions 引起的至zs哪里zs预计当 vertsPolyCollection形状为 MxNx2 的对象传递给 zs形状为M。所以当它到达这个检查

cpdef ndarray broadcast_to(ndarray array, shape):
# ...
if array.ndim < len(shape):
raise ValueError(
'input operand has more dimensions than allowed by the axis '
'remapping')
# ...

在底层 numpy 代码中,它失败了。我相信发生这种情况是因为预期的维度数 ( array.ndim ) 小于 zs 的维度数(len(shape))。它需要一个形状为 (4,) 的数组。但收到形状为 (4, 80, 2) 的数组.

可以通过使用正确形状的数组来解决此错误 - 例如zs来自原始示例或 dists从你的代码。使用zs=dists并将轴限制调整为 [0,5]对于 x , y ,和z给出

enter image description here

这看起来有点奇怪,有两个原因:

  1. z_ = norm.pdf(xs, loc = mus[i], scale = sigmas[0]) 有拼写错误它赋予所有分布相同的西格玛,它应该是 z_ = norm.pdf(xs, loc = mus[i], scale = sigmas[i])
  2. 观察几何:分布为正 xz平面作为他们的基础,这也是我们正在透过的平面。

通过 ax.view_init 更改查看几何形状将产生更清晰的情节:

enter image description here

<小时/>

编辑

这是生成所示绘图的完整代码,

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from scipy.stats import norm

np.random.seed(8)
def get_xs(lwr_bound = -4, upr_bound = 4, n = 80):
return np.arange(lwr_bound, upr_bound, (upr_bound - lwr_bound) / n)

def get_distribution_params(list_):
mus = [round((i+1) + 0.1 * np.random.randint(0,10), 3) for i in range(len(dists))]
sigmas = [round((i+1) * .01 * np.random.randint(0,10), 3) for i in range(len(dists))]
return mus, sigmas

def get_distributions(list_, xs, mus, sigmas):
return [list(zip(xs, norm.pdf(xs, loc=mus[i], scale=sigmas[i] if sigmas[i] != 0.0
else 0.1))) for i in range(len(list_))]

dists = [1, 2, 3, 4]
xs = get_xs()
mus, sigmas = get_distribution_params(dists)
distributions = get_distributions(dists, xs, mus, sigmas)

fc = [mcolors.to_rgba('r', alpha=0.6), mcolors.to_rgba('g', alpha=0.6),
mcolors.to_rgba('b', alpha=0.6), mcolors.to_rgba('y', alpha=0.6)]

poly = PolyCollection(distributions, fc=fc)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.add_collection3d(poly, zs=np.array(dists).astype(float), zdir='z')
ax.view_init(azim=115)
ax.set_zlim([0, 5])
ax.set_ylim([0, 5])
ax.set_xlim([0, 5])

我根据您在问题中提供的代码编写了它,但为了简洁起见并进行了一些修改,以便与通常的样式更加一致。

<小时/>

注意   -   您提供的示例代码将失败,具体取决于 np.random.seed() ,为了确保它正常工作,我在对 norm.pdf 的调用中添加了一个检查确保比例非零:scale = sigma[i] if sigma[i] != 0.0 else 0.1

关于python - 3D绘图: smooth plot on x axis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com