简体   繁体   中英

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. 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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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