如何在tkinter windows python中显示从excel文件提取的matplotlib图形

2024-10-03 23:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用excel中的数据绘制一个图表,并将其显示在Tkinter窗口上。 但是我不能,也不知道如何才能做到,我搜索了很多地方,只得到了一些示例来显示代码中的数据。这是我的密码:

here the file of Excel download here

import tkinter as tk
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

df= pd.read_excel (r'C:\Users\evil4ever\Desktop\acheraf\project\projetCorona.xlsx') 
tab1=df[0:31]

#Dates=['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']
Dates = []
for i in range(1,32):
    Dates.append(str(i))


Values=tab1['Cas confirmés']#rmorocco
Values2=tab1['RABAT.SALE.KENITRA']#rabat

f=plt.Figure(figsize=(9,5), dpi=100)

plt.xlabel('days of March')
plt.ylabel('Confirmed cases')
plt.title('Confirmed Cases in March RABAT.SALE.KENITRA ')
plt.bar(Dates,Values,label='all morocco',color='r')
plt.bar(Dates,Values2,label='RABAT.SALE.KENITRA',color='c')
a=f.add_subplot(111)
root= tk.Tk()
canvas=FigureCanvasTkAgg(f, root)

canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
root.mainloop()

explain the problem: when i run the program is showing this windows look this image

图中显示的是image 在代码显示我想在windows上显示的图形之后,不在那里

after this line:a=f.add_subplot(111) i add a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5]) is showing something in windows

我搜索了3天,没有任何解决方案


Tags: theinimportaddwindowsaspltroot
1条回答
网友
1楼 · 发布于 2024-10-03 23:26:42

matplotlibtkinter组合时,使用Figure代替pyplot。官方样本见this

import tkinter as tk
import pandas as pd
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

df = pd.DataFrame({"Name":list("ABCD"),"Value":[1,2,3,4,]})
#df = pd.read_excel (r'C:\Users\evil4ever\Desktop\acheraf\project\projetCorona.xlsx') 

f = Figure(figsize=(9,5), dpi=100)

ax = f.add_subplot(111)

ax.set_xlabel('days of March')
ax.set_ylabel('Confirmed cases')
ax.set_title('Confirmed Cases in March RABAT.SALE.KENITRA')

df.plot(kind="bar",ax=ax)

root= tk.Tk()
canvas=FigureCanvasTkAgg(f, root)

canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
root.mainloop()

相关问题 更多 >