[英]ValueError: shape mismatch: objects cannot be broadcast to a single shape
[英]ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (48000,) and arg 1 with shape (2,)
我尝试使用 PillowWriter 为一个简单的(正弦)^3 函数设置动画,但遇到了这个错误。 下面提到的是我的代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import PillowWriter
def y(x):
z = 3 * np.sin(x)**3
return z
fig = plt.figure()
l, = plt.plot([], [], 'g-')
plt.xlim(-12,12)
plt.ylim(-12,12)
metadata = dict(title="3[sin(x)]^3", artist="Me")
writer = PillowWriter(fps=20, metadata=metadata)
x_axis = np.arange(-12, 12, 0.0005)
y_axis = []
with writer.saving(fig, "y(x).gif", 100):
for x in x_axis:
y_axis.append(y(x))
l.set_data(x_axis, y_axis)
writer.grab_frame()
看来您的y_axis
不够长,所以绘图不知道如何将其与x_axis
数组进行比较。 我建议以下解决方案:
from matplotlib.axis import XAxis
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import PillowWriter
def y(x):
z = 3 * np.sin(x)**3
return z
fig = plt.figure()
l, = plt.plot([], [], 'g-')
plt.xlim(-12,12)
plt.ylim(-12,12)
metadata = dict(title="3[sin(x)]^3", artist="Me")
writer = PillowWriter(fps=20, metadata=metadata)
x_axis = np.arange(-12, 12, 0.05) # 0.0005 causes performance issues
y_axis = np.zeros(len(x_axis))
with writer.saving(fig, "y(x).gif", 100):
for n, x_val in enumerate(x_axis):
y_axis[n] = y(x_val)
l.set_data(x_axis, y_axis)
writer.grab_frame()
解释:它创建一个与x_axis
数组长度相等的y_axis
数组,但用零填充。 然后,对于每一帧,它计算并设置y_axis
数组的下一个值等于函数值。 注意:我降低了x_axis
数组的分辨率,因为它给我带来了性能问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.