Struggling to make matplotlib slider work

Question:

I’m very new to coding so this may be a very simple question

I’m attempting to code a basic ‘falling under gravity’ rocket simulation using matplotlib. I have the basic object falling with the desired physics, but I’m trying to add a matplotlib slider to change the ‘thrust’ of the rocket during the simulation. I have the slider appearing on the screen, but I’m struggling to make the slider actually alter the thrust inside the loop. I’m aware of the need to use a ‘slider callback’ function but am at a loss as to how to implement this. Code below. Many thanks to anyone who can help.

import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

fig=plt.figure(figsize=(10,8))
ax=plt.axes([0.1,0.2,0.6,0.7])
ax.set_facecolor('black')

sax=plt.axes([0.12,0.05,0.55,0.03])
sliderHandle=widgets.Slider(sax, 'Thrust', 0,3,valinit=0)

t=0
x=100
v=0
g=-9.81
thrust=0

while x>0:
    ax.cla()
    ax.plot(0,x,'w^', markersize='20')
    ax.set_xlim(-10,10)
    ax.set_ylim(0,110)
    plt.pause(0.001)
    t=t+0.001
    v=v+((thrust+g)*t)
    x=x+(v*t)
Asked By: XBlake97

||

Answers:

the callback function can just change the global value of thrust as follows.

import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

fig=plt.figure(figsize=(10,8))
ax=plt.axes([0.1,0.2,0.6,0.7])
ax.set_facecolor('black')

sax=plt.axes([0.12,0.05,0.55,0.03])
sliderHandle=widgets.Slider(sax, 'Thrust', 0,20,valinit=0)

t=0
x=100
v=0
g=-9.81
thrust=0

def callback_fun(val):
    global thrust
    current_v = int(sliderHandle.val)
    thrust = current_v
sliderHandle.on_changed(callback_fun)

while x>0:
    ax.cla()
    ax.plot(0,x,'w^', markersize='20')
    ax.set_xlim(-10,10)
    ax.set_ylim(0,110)
    plt.pause(0.001)
    t=t+0.001
    v=v+((thrust+g)*t)
    x=x+(v*t)

Ps: you need to implement wind resistance. (drag)

Answered By: Ahmed AEK
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.