Matplotlib 3d曲面图输入数组

时间:2017-12-19 12:46:54

标签: python numpy matplotlib

我正在尝试使用3个numpy数组创建表面图:

  • x_deflections [形状:(10,)]
  • y_alphas [形状:(12,)]
  • z_height_at_target [形状:(120,)]
提供了

x_deflectionsy_alphas,并使用其中的2个来计算z_height_at_target

i = 0
for x in x_deflections:
    for y in y_alphas:
        exit_v = spring_calc.do_calc(k, x)
        # Only care about x_dist and h here
        vX, vY, x_dist, h = traj_calc.do_calc(exit_v, y, stop_at=target_dist)
        try:
            if max(x_dist) < target_dist:
                raise StopIteration
            else:
                target_dist_index = find_nearest(x_dist, target_dist, 0.04)
        except StopIteration:
            print('Target Distance not achieved')
            continue
        z_height_at_target[i] = h[target_dist_index]
        i += 1

这可以像我期望的那样工作,并在z_height_at_target中给出合理的值,但是我似乎无法弄清楚如何从中创建一个合适的曲面图。我目前的方法给了我充满尖峰的乱码图:

fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(x_deflections, np.rad2deg(y_alphas), indexing='xy')
Z = z_height_at_target.reshape((len(x_deflections), len(y_alphas)))
ax.plot_surface(X, Y, Z, color='b')
ax.set_xlabel('Spring Deflection [m]')
ax.set_ylabel('Launch Angle [deg]')
ax.set_zlabel('Height at Target Distance [m]')
pl.show()

我知道问题在于以下其中一行,但我似乎无法理解它:

X, Y = np.meshgrid(x_deflections, np.rad2deg(y_alphas), indexing='xy')
Z = z_height_at_target.reshape((len(x_deflections), len(y_alphas)))

这当前抛出一个错误,说错误的形状,这是正确的,但转置Z给出了胡言乱语。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

解决了这个问题,使用了@Uvar关于转置z_height_at_target的建议,并将值放在2维中,而不是之后重新整形(这实际上与前面的代码相同):

i = 0
x_count = 0
miss_count = 0
for x in x_deflections:
    y_count = 0
    for y in y_alphas:
        exit_v = spring_calc.do_calc(k, x, y)
        # only need h here but the rest of can come along for the ride as well
        vX, vY, x_dist, h = traj_calc.do_calc(exit_v, y, stop_at=target_dist)
        try:
            if max(x_dist) < target_dist:
                raise StopIteration
            else:
                target_dist_index = find_nearest(x_dist, target_dist, 0.04)
        except StopIteration:
            print('Target Distance not achieved')
            miss_count += 1
            continue
        z_height_at_target[x_count, y_count] = h[target_dist_index]
        print('Completed iter', i+1)
        # print('{}, {}, {}'.format(exit_v, h[target_dist_index], np.rad2deg(y)))
        i += 1
        y_count += 1
    x_count += 1

fig = pl.figure()
ax = fig.add_subplot(121, projection='3d')
# ax = fig.gca(projection='3d')
X, Y = np.meshgrid(x_deflections, np.rad2deg(y_alphas), indexing='xy')
Z = z_height_at_target.T