我希望通过更改滑块d_in来更改对象(椭圆形)的x位置(= d_in)。这就是我得到的:
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()
如何告诉滑块更改椭圆的位置?
谢谢
答案 0 :(得分:0)
您需要在滑块值更改时注册一个回调,
slider.on_changed(callback)
并在该回调函数中,更新椭圆的位置
ellipse.center = new_center
在这里,它可能如下所示
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()