【发布时间】:2018-04-28 01:39:32
【问题描述】:
我正在尝试使用 Python/Matplotlib 创建一个交互式图形,它只是在单击按钮时向右移动一个圆圈。我的代码部分起作用,因为按下按钮会更新圆坐标并将圆向右移动。然而,旧的圆圈仍然被绘制,这不是我想要的。我希望只在图表上绘制新的、更新的圆圈。
这是当前在单击按钮之前发生的情况:
点击几个按钮后:
我尝试过使用plt.draw(),但不是很成功。
我首先定义我的轴:
"Create Figure and plot circle Subplot"
figure1 = plt.figure() # Main Figure to contain all subplots and button panel
CircSubplot = figure1.add_subplot(1,1,1, aspect= 'equal')
# -- Axes with centred spines --
CircSubplot.spines['left'].set_position('center')
CircSubplot.spines['right'].set_color('none')
CircSubplot.spines['bottom'].set_position('center')
CircSubplot.spines['top'].set_color('none')
CircSubplot.spines['left'] #.set_smart_bounds(True)
CircSubplot.spines['bottom'] #.set_smart_bounds(True)
CircSubplot.xaxis.set_ticks_position('bottom')
CircSubplot.yaxis.set_ticks_position('left')
# -- Sets scale for axes --
axesScaleFactor = 3 # Sets the scale of the axis wrt to circle radius
axCircSubplot = plt.gca() # get current axes object
axCircSubplot.set_xlim([-circRadius*axesScaleFactor,circRadius*axesScaleFactor]) #set x-axes range
axCircSubplot.set_ylim([-circRadius*axesScaleFactor,circRadius*axesScaleFactor]) #set y-axes range
然后我定义了一个在按下按钮时运行的回调函数:
class Index(object):
xinc = 0
def right(self, event):
self.xinc += 1
i = self.xinc
circCentre = [i,0] #Increments circle x co-ordinates by 1
UpdatedCircVec = CircleVector(circCentre[0],circCentre[1],circRadius,circPoints) #CircleVector function returns a 2D array containing X and Y co-ordinates for the circle
Upper = CircUpper(UpdatedCircVec) #Function splits the CircleVector into portions for upper circle segment
Lower = CircLower(UpdatedCircVec) #Function splits the CircleVector into portions for lower circle segment
CircSubplot.plot(Upper[0],Upper[1],'b') #Plot upper circle segment
CircSubplot.plot(Lower[0],Lower[1],'b') #Plot lower circle segment
plt.draw()
任何帮助将不胜感激。
【问题讨论】:
-
如果您不想在绘图中出现圆圈,则需要将其删除 (
remove())。或者,不用绘制新圆圈,而是用新数据更新旧圆圈 (.set_data())。另请注意,要绘制圆圈,您可以直接使用plt.Circle()。
标签: python button matplotlib interactive figure