簡體   English   中英

帶有滑塊和固定幾何圖形的交互式 matplotlib

[英]Interactive matplotlib with slider and fixed geometric figure

我正在嘗試為固定在三角形前面的線的旋轉設置動畫(想想超音速流中楔子上的沖擊波)。 我可以讓三角形與線一起出現,但是當我移動滑塊時,出現以下錯誤:

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

您尚未創建圖形變量,因此在調用update時找不到它。 試着放

fig = plt.figure()

在最頂端的某個地方,就在您的導入之后。 然后,在update自己,你設置的X和Y的數據line ,但你在這里犯了個小錯誤。 您將它們設置為一個點,但您還必須在此處包含您的起點。 所以改成

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

一切正常!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM