设M和N为整数。一个给出一个大小为(M,1)的向量s,一个大小为(N,1)的向量p和一个大小为(M,N)的矩阵u0。
假设有人希望将3D绘图(s,p)作为网格,将u0作为绘制函数(z轴)。当一个人写道:
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(s, p, u0, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
终端显示以下错误消息:
ValueError: shape mismatch: objects cannot be broadcast to a single shape
然而,尺寸匹配!有没有一种方法在网格(s,p)上对u0进行3D绘图而不使用网格的arange函数(参见https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#d-plots-in-3d中过多的重复示例)?
编辑:这是一个MCVE。原始问题正是以下示例遇到的问题。
import math
from math import *
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from pylab import plot, axis, savefig, show, title, meshgrid, cm, imshow, contour, clabel, colorbar
from numpy import exp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#
M = 10
N = 20
h = 1/float(M)
l = 1/float(N)
#
s = np.zeros((M + 1, 1))
p = np.zeros((N + 1, 1))
for j in range(0, M + 1):
s[j] = 0.0 + 5.0*j*h
for k in range(0, N + 1):
p[k] = 0.0 + 20.0*k*l
#
u0 = np.zeros((M + 1, N + 1))
for j in range(0, M):
for k in range(0, N):
u0[j, k] = exp(-(s[j] + p[k] - 10)**2)
#
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(p, s, u0, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()