![](/img/trans.png)
[英]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.