简体   繁体   English

带有滑块和固定几何图形的交互式 matplotlib

[英]Interactive matplotlib with slider and fixed geometric figure

I'm trying to animate the rotation of a line that is pinned to the front of a triangle (think a shock wave on a wedge in supersonic flow).我正在尝试为固定在三角形前面的线的旋转设置动画(想想超音速流中楔子上的冲击波)。 I can get the triangle to appear along with the line, but when I move the slider I get the following error:我可以让三角形与线一起出现,但是当我移动滑块时,出现以下错误:

fig.canvas.draw_idle()
NameError: name 'fig' is not defined

The code is below.代码如下。

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()

You haven't created a figure variable, therefore it is not found when update gets called.您尚未创建图形变量,因此在调用update时找不到它。 Try to put试着放

fig = plt.figure()

somewhere at the very top, right after your imports.在最顶端的某个地方,就在您的导入之后。 Then, in update itself, you set the x- and y-data of line but you made a small mistake here.然后,在update自己,你设置的X和Y的数据line ,但你在这里犯了个小错误。 You are setting them to a single point, but you also have to include your start point here.您将它们设置为一个点,但您还必须在此处包含您的起点。 So change it to所以改成

line.set_xdata((x1, Bx))
line.set_ydata((y1, By))

and everything should work fine!一切正常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM