【发布时间】:2021-03-23 23:02:00
【问题描述】:
我一直在尝试在 Python 上使用 matplotlib 绘制 3d 图。这是代码的副本:
import math
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
#global variable a
a = 1
#time steps = 100
T = 100
#length steps = 50
L = 50
time = [i for i in range(T)]
#checking for 50 points onthe vent only
length = [i for i in range(L)]
#creating the concentration matrix for each point in the vent at each point in time. The innerlists represent the point on the vent. Each such list is the time stamp.
concentration = [ [i for i in range(L)] for j in range(T)]
#Boundary condition at x=0
def h(t):
return (1/(t+(1/a))) + a
#Boundary condition at x=L
def j(t):
return (-1/(t+(1/a))) + a
#Initilal condition is that the temperate is 0 everywhere on the vent. Hence we are setting the concentration to equal 0 at every point in the vent when time is equal to 0
for i in range(5):
concentration[0][i] = 2
for i in range(5,L):
concentration[0][i] = 0
#Setting the boundary conditions
for i in range(T):
concentration[i][0] = h(i)
concentration[i][L-1] = j(i)
#Doing the numerical solution based on the formula in Walter Strauss
for j in range(0,L-1): #j is the position column
for n in range(0,T-1): #n is the time row
concentration[n+1][j] = concentration[n][j+1] + concentration[n][j-1] + (-1)*concentration[n][j]
这部分代码运行良好,没有任何错误。但是,当我尝试使用以下说明绘制数据时:
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.scatter(time, length, concentration, cmap='binary')
ax.set_xlabel('rod')
ax.set_ylabel('time')
ax.set_zlabel('concentration');
我得到一个错误。错误显示:
ValueError Traceback (most recent call last)
<ipython-input-12-321ea987eeb6> in <module>()
53 fig = plt.figure()
54 ax = plt.axes(projection='3d')
---> 55 ax.scatter(time, length, concentration, cmap='binary')
56 ax.set_xlabel('rod')
57 ax.set_ylabel('time')
2 frames
<__array_function__ internals> in broadcast_arrays(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args)
189 # use the old-iterator because np.nditer does not handle size 0 arrays
190 # consistently
--> 191 b = np.broadcast(*args[:32])
192 # unfortunately, it cannot handle 32 or more arguments directly
193 for pos in range(32, len(args), 31):
ValueError: shape mismatch: objects cannot be broadcast to a single shape
有人可以帮助我了解错误的来源吗?我不认为这是代码前半部分的计算错误,因为它运行得很好。浓度矩阵的维度以及长度和时间矩阵都非常匹配。但是 3d 绘图会出错。
【问题讨论】:
标签: python arrays numpy matplotlib