matplotlib widgets slider on object (Ellipse)

我是研究僧i 提交于 2020-01-06 05:35:06

问题


I want that the x-position (=d_in) of my object (the Ellipse) is changed by changing the slider d_in. This is what I got:

from numpy import pi, sin
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
from matplotlib.patches import Ellipse
from scipy.optimize import fsolve
import pylab


axis_color = 'lightgoldenrodyellow'
#variable
d_in=80

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.35)
x = np.arange(0.0, 300, 0.01)


# object ellipse
Spiegel = Ellipse(xy=(d_in, 0), width=2, height=73.2,
                        edgecolor='black', fc='#808080', lw=1)
ax.add_patch(Spiegel)


#Draw d_in slider
d_in_slider_ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axis_color)
d_in_slider = Slider(d_in_slider_ax, 'd_in', 1, 150, valinit=d_in)


#axis range
ax.set_xlim([0, 300])
ax.set_ylim([-40, 40])

plt.show()

How can I tell the slider to change the position of the Ellipse?

Thank you


回答1:


You need to register a callback for when the slider values changes,

slider.on_changed(callback)

and inside that callback, update the position of the ellipse

ellipse.center = new_center

Here, this could look as follows

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.patches import Ellipse

#variable
d_in=80

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.35)
x = np.arange(0.0, 300, 0.01)


# object ellipse
Spiegel = Ellipse(xy=(d_in, 0), width=2, height=73.2,
                  edgecolor='black', fc='#808080', lw=1)
ax.add_patch(Spiegel)


#Draw d_in slider
d_in_slider_ax = fig.add_axes([0.25, 0.1, 0.65, 0.03])
d_in_slider = Slider(d_in_slider_ax, 'd_in', 1, 150, valinit=d_in)

def update(val):
    Spiegel.center = (val,0)

d_in_slider.on_changed(update)


#axis range
ax.set_xlim([0, 300])
ax.set_ylim([-40, 40])

plt.show()


来源:https://stackoverflow.com/questions/51649131/matplotlib-widgets-slider-on-object-ellipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!