我的matplotlib条形图在每次运行函数时都会重复,我该如何刷新条形图?

时间:2017-08-21 02:18:44

标签: python matplotlib charts tkinter sqlite

我通过浏览互联网创建的条形图和条形图似乎在运行的函数的前一个图表上堆叠相同的结果,而不是在从数据库获取数据时更改值。

下面的代码使用类,包括我在tkinter中创建的页面,以及使用SQLite3和函数:

class ViewTrackData(tkinter.Frame):
def __init__(self, parent, controller):
    tkinter.Frame.__init__(self, parent)
    # label1 = tkinter.Label(self, text="This is the page where track data will be shown.")
    # label1.grid(row=50, column=70, sticky="nsew")

    self.athleteData = ""
    self.athlete = ""
    self.position = 1
    self.times = {}
    self.roundFigUp = ""
    self.roundFigDown = ""
    self.x = []
    self.y = []
    self.text = ""


    self.trackName = tkinter.Spinbox(self, values=trackTables, width=50, justify="center", font=entry_font,
                                     foreground="#000000", background="#FFFFFF")
    self.trackName.place(relx=0.15, rely=0.1)

    self.eventYear = tkinter.Entry(self, width=50, justify="center", font=entry_font, foreground="#000000",
                                   background="#FFFFFF")
    self.eventYear.insert(0, "The year which the event took place.")
    self.eventYear.place(relx=0.15, rely=0.41)

    self.yearGroup = tkinter.Spinbox(self, from_=7, to=11, width=50, justify="center", font=entry_font,
                                     foreground="#000000", background="#FFFFFF")
    self.yearGroup.place(relx=0.15, rely=0.70)

    self.filterButton = tkinter.Button(self, text="filter", bg="#383A39", fg="#AB97BD", width=15, height=3,
                                       command=self.show_graph)
    self.filterButton.place(relx=0.24, rely=0.82)

    self.infoLabel = tkinter.Label(self, height=25, width=40, wraplength=300, anchor="center", relief="groove", font=font_use)
    self.infoLabel.place(relx=0.52, rely=0.1)

def show_graph(self):
    self.infoLabel.configure(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 in this year for this year group.")
    else:
        for self.item in self.athleteData:
            self.athlete = self.item
            self.times.update({self.athlete[1] : self.position}) # adds data about the name of the athlete as the key and the position which a athlete placed as a value.
            self.position += 1 # increments the position value
            self.x.append(self.times[self.athlete[1]]) # adds the position in which an athlete placed as an argument to the x axis
            self.truncatedTime = str(self.athlete[3]).replace((self.athlete[3])[5:],"") # turns the value for the seconds an athlete has run under into a string and slices off " seconds"
            print(self.truncatedTime)
            if int((self.truncatedTime)[3]) >= 5: # if statement which rounds up or down depending on the first value after the decimal point.
                self.roundFigUp = math.ceil(float(self.truncatedTime))
                self.y.append(int(self.roundFigUp))
            else:
                self.roundFigDown = math.floor(float(self.truncatedTime))
                self.y.append(int(self.roundFigDown))
            self.text += ("representing number " + str(self.times[self.athlete[1]]) + " is " + str(self.athlete[1])
                          + ", ")
            self.infoLabel.configure(text=self.text)
            print(self.athlete)

    plt.bar(self.x, self.y, label="Athlete time bars", color="green")

    plt.xlabel("Athlete Positions")
    plt.ylabel("Athlete Time")
    plt.title("Bar chart, representing times of athletes.")
    plt.legend()
    plt.show()

我试图寻找答案,但我似乎无法实现我在程序中看到的所有内容。

如果这个问题对你来说似乎没有问题我事先道歉。

我还想要求最后一件事。

你能解释一下我应该如何使用plt.xticks吗?为了将标签从数字更改为运动员的实际名称。这表示自self.athlete [1]。

1 个答案:

答案 0 :(得分:0)

每次调用show_graph时,都会有更多数据附加到self.xself.y

self.x.append(self.times[self.athlete[1]]) 
...
if int((self.truncatedTime)[3]) >= 5: 
    self.roundFigUp = math.ceil(float(self.truncatedTime))
    self.y.append(int(self.roundFigUp))
else:
    self.roundFigDown = math.floor(float(self.truncatedTime))
    self.y.append(int(self.roundFigDown))

修复方法是在self.x开头重新初始化self.yshow_graph

def show_graph(self):
    self.x = []
    self.y = []
    ...

self.x方法中发生的self.y__init__的初始化只发生一次, 当ViewTrackData帧被实例化时。

PS。您可能也有兴趣看到this example 这显示了如何在Tk应用程序中嵌入matplotlib图。一个优点 这样做就是显示图表不会冻结其余部分 应用程序的图形用户界面(例如菜单和按钮)。