我不明白我应该使用哪种方法来清除我在tkinter程序中嵌入的matplotlib条形图。
我应该专注于摆脱画布还是应该专注于使用plt.cla或plt.clf()。我已经尝试了两个,因为我正在使用Pycharm,IDE没有显示任何其他方法供我使用。
我将在下面显示我的代码:
def show_graph(self):
self.infoLabel.config(text="")
c.execute("SELECT * FROM " + self.trackName.get() + " WHERE Year_Of_Event = ? AND Athlete_Year_Group = ? "
"ORDER BY ATHLETE_TIME ASC", (self.eventYear.get(),
self.yearGroup.get()))
self.athleteData = c.fetchall()
if self.athleteData is None:
self.infoLabel.configure(text="There are no records for the event in this year for this year group.")
else:
for self.item in self.athleteData:
self.athlete = self.item
self.x.append(self.athlete[1])
self.truncatedTime = str(self.athlete[3]).replace((self.athlete[3])[5:], "")
self.y.append(float(self.truncatedTime))
self.text += (self.athlete[1]+" ran the "+self.trackName.get()+" in "+self.athlete[3]+" and is from the"
" house, "+self.athlete[4]+"\n")
self.infoLabel.configure(text=self.text)
self.numOfValues = len(self.x)
self.ind = numpy.arange(self.numOfValues)
self.colorChoice = random.choice(["r", "y", "b", "g", "w", "k", "m", "c"])
self.rect = self.ax.bar(self.ind, self.y, width=self.width, color=self.colorChoice)
# add some text for labels, title and axes ticks
self.ax.set_ylabel('Time')
self.ax.set_title('Times under which athletes ran a race.')
self.ax.set_xticks(self.ind)
self.ax.set_xticklabels(self.x)
def label(bars):
"""
Attach a text label in each bar displaying its height
"""
for self.rect in bars:
height = self.rect.get_height()
self.ax.text(self.rect.get_x() + self.rect.get_width() / 2., 0.5 * height, int(height),
ha='center', va='bottom')
label(self.rect)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=tkinter.BOTTOM, fill="x")
self.canvas._tkcanvas.pack(side=tkinter.BOTTOM, fill="x")
def clear_all(self):
self.infoLabel.configure(text="")
我想这样做,以便clear_all函数携带清除条形图的代码,这样我就可以在图表上绘制不同的数据。
我不确定应该如何解决这个问题。很感谢任何形式的帮助。谢谢。
答案 0 :(得分:0)
要清除图形,您必须从self.xList1和self.yList1
中删除数据self.xList1 = []
self.yList1 = []
因为在清除了地块(a.clear()/plt.clf()/plt.cla()
)之后,您仍然在列表中有数据,然后再次绘制它们。