我是matplotlib的新手,正在尝试从MySQL数据库中的数据制作条形图。条形图工作正常,但是当程序运行时将新记录添加到数据库中时,条形图不会更新。为了在条形图中显示新值,需要关闭并再次打开程序。这是我在tkinter gui中每次按下按钮时执行的功能的代码,我知道这可能不是解决此问题的最佳方法。我希望在按下按钮时更新条形图。有任何提示吗?
def graphs(self):
self.cursor.execute('SELECT * FROM Enrollment; ')
result = self.cursor.fetchall()
economics = 0
information_science = 0
data_science = 0
mathematics = 0
politics = 0
history = 0
information_sec = 0
music = 0
medicine = 0
business = 0
for row in result:
if row[2] == 1:
economics += 1
elif row[2] == 2:
information_science += 1
elif row[2] == 3:
data_science += 1
elif row[2] == 4:
mathematics += 1
elif row[2] == 5:
politics += 1
elif row[2] == 6:
history += 1
elif row[2] == 7:
information_sec += 1
elif row[2] == 8:
music += 1
elif row[2] == 9:
medicine += 1
elif row[2] == 10:
business += 1
values = [economics, information_science, data_science, mathematics, politics,
history, information_sec, music, medicine, business]
keys = ['Economics', 'Information Science', 'Data Science', 'Mathematics', 'Politics',
'History', 'Information Security', 'Music Studies', 'Medicine', 'Business Analytics']
plt.bar(keys, values, zorder=3)
plt.title('Students in each course')
plt.xlabel('Courses')
plt.ylabel('Students')
plt.xticks(keys, rotation='vertical')
plt.subplots_adjust(bottom=0.35)
plt.grid(zorder=0)
plt.show()
count = 0
plt.savefig('bar'+str(count)+'.png')
count += 1
这解决了我的问题。使用SQL计数值也极大地简化了我的代码。
def graphs(self):
self.cursor.execute('SELECT Course_ID, Count(*) FROM Enrollment GROUP BY Course_ID; ')
result = self.cursor.fetchall()
df = DataFrame(result)
keys = ['Economics', 'Information Science', 'Data Science', 'Mathematics', 'Politics',
'History', 'Information Security', 'Music Studies', 'Medicine', 'Business Analytics']
values = df[1]
plt.bar(keys, values, zorder=3)
plt.title('Students in each course')
plt.xlabel('Courses')
plt.ylabel('Students')
plt.xticks(keys, rotation='vertical')
plt.subplots_adjust(bottom=0.35)
plt.grid(zorder=0)
plt.show()