Slider demo for a contour plot in python

186 Views Asked by At

I am trying to create a slider demo contour for a sinusoidal function using python, but I do not know how to code the line that we will manipulate for a contour plot slider. I appreciate anyone that helps me. Here is my code:

`import matplotlib.pyplot as plt`
`import numpy as np`
`from matplotlib.widgets import Slider, Button`

`plt.style.use('_mpl-gallery-nogrid')`
`# make data`
`t_1, t_2 = np.meshgrid(np.linspace(-2, 2, 256), np.linspace(-2, 2, 256))`


`def f(t_1, t_2, amplitude, frequency):`
    `f = amplitude * np.sin(2 * np.pi * frequency * (t_1 + t_2))`
    `return f`


`init_frequency = 3`
`init_amplitude = 3`

`axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])`
`freq_slider = Slider(`
    `ax=axfreq,`
   ` label='Frequency [Hz]',`
    `valmin=0.1,`
    `valmax=30,`
    `valinit=init_frequency,`
`)`
`# The function to be called anytime a slider's value changes`
`def update(val):`
    `line.set_ydata(f(t_1, t_2, freq_slider.val))`
    `fig.canvas.draw_idle()`

`# register the update function with each slider`
`freq_slider.on_changed(update)`

`# plot`
`fig, ax = plt.subplots()`
`plt.contourf(t_1, t_2, f(t_1, t_2, init_amplitude, init_frequency), 100, cmap='turbo')`
`#create the line that we will manipulate`
`#line, = plt.plot(t_1, t_2, f(t_1, t_2, init_amplitude, init_frequency), lw=2)`
`cbar=plt.colorbar(orientation='vertical');`
`cbar.set_label(label="E_c",size=15)`
`plt.show()`
1

There are 1 best solutions below

0
Artashes On

Here's an example that you can easily adapt to your case:

you can find here bunch of other widgets.

import matplotlib.pyplot as plt
import numpy as np
# from matplotlib.widgets import Slider, Button
import ipywidgets as wg

@wg.interact(freq_slider = wg.FloatSlider(min=0.1, max=30, continuous_update=True, 
                                          description='Frequency [Hz]', 
                                          layout=wg.Layout(width="500px")),
             Check = wg.Checkbox(value=False))
def run(freq_slider, Check): # this is the fiction that uses the sliders
    
    # your code must be here, inside this run function

    x = np.linspace(-7,7,1000)
    
    if(Check==True):
        plt.plot(x, np.sin(freq_slider*x))
    else:
        plt.plot(x, freq_slider*x**2)
    
    plt.xlim(-8,8,)
    plt.ylim(-2,2,)

enter image description here