我正在尝试使固定在三角形前面的线的旋转动画(想想超声速流动中楔形物上的冲击波)。我可以使三角形与线一起出现,但是当我移动滑块时,出现以下错误:
fig.canvas.draw_idle()
NameError: name 'fig' is not defined
代码在下面。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation
from matplotlib.widgets import Slider # import the Slider widget
#rect = [left, bottom, width, height].
# A new axes is added with dimensions rect in normalized (0, 1)
# units using add_axes on the current figure.
axcolor = 'lightgoldenrodyellow'
main_ax = plt.axes([0, .2, 10, 15])
slider_ax = plt.axes([0.2, 0.05, .7, .03], facecolor=axcolor)
#Slider min max
s_min = 20
s_max = 60
s_init = 45
#Some constants
torad = np.pi/180
WAngle = 20.
xmax = 10
# set the current plot to main_ax
plt.sca(main_ax)
#Define and plot the triangle
plt.axes() #Select the main axis
x1 = 0
y1 = 0
x2 = xmax
y2 = y1
x3 = x2
y3 = x3*np.tan(WAngle * torad)
points = [[x1,y1],[x2,y2],[x3,y3]]
plt.title('test')
plt.xlim(x1,xmax)
plt.ylim(y1,y3)
polygon = plt.Polygon(points, facecolor='0.9', edgecolor='0.5')
plt.gca().add_patch(polygon)
#Now define the line, only need the second point, first point 0,0
Beta = 30
Bx = x3
By = x3*np.tan(Beta * torad)
# Draw line and add to plot
line = plt.Line2D((x1,Bx),(y1,By),lw=1.0, color='r') #(x1,x2),(y1,y2)
plt.gca().add_line(line)
# Now define slider info
svalue = Slider(slider_ax, 'angle', s_min, s_max, valinit=s_init)
def update(val):
Beta = svalue.val
Bx = x3
By = x3*np.tan(Beta * torad)
line.set_xdata(Bx)
line.set_ydata(By)
fig.canvas.draw_idle()
svalue.on_changed(update)
plt.axis('scaled')
#plt.axis('off')
plt.show()
答案 0 :(得分:0)
您尚未创建图形变量,因此在调用fclose()
时找不到该变量。尝试放
update
在导入之后,位于顶部的某个位置。然后,在fig = plt.figure()
本身中,设置update
的x和y数据,但是在这里犯了一个小错误。您将它们设置为单个点,但是还必须在此处包括起点。因此将其更改为
line
一切正常!