我试图动画一条线的旋转,这条线被钉在三角形的前面(想象一下超音速流动中楔形上的激波)。我可以让三角形与线一起出现,但当我移动滑块时,会出现以下错误:
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()发布于 2019-12-05 07:45:38
您还没有创建图形变量,因此在调用update时找不到它。试着
fig = plt.figure()就在你进口之后的最高级的地方。然后,在update本身中,设置line的x和y数据,但这里犯了一个小错误。您正在将它们设置为单个点,但您也必须在这里包含您的起点。所以把它改为
line.set_xdata((x1, Bx))
line.set_ydata((y1, By))一切都应该很好!
https://stackoverflow.com/questions/59188519
复制相似问题