簡體   English   中英

Python:在 Tkinter GUI 中嵌入熊貓圖

[英]Python: Embed pandas plot in Tkinter GUI

我正在使用 Python 2.7 中的 Pandas DataFrames 編寫一個應用程序。 我需要將 DataFrame 的列繪制到 Tkinter 窗口。 我知道我可以使用 DataFrame 或 Series(這只是 matplotlib plot 函數的包裝器)上的內置 plot 方法繪制 pandas DataFrames 列,如下所示:

import pandas as pd
df = pd.DataFrame({'one':[2,4,6,8], 'two':[3,5,7,9]})
df.plot('one')

另外,我想出了如何使用 matplotlib 繪制到 Tkinter GUI 窗口:

import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import pandas as pd
import Tkinter as tk
import ttk

root = tk.Tk()
#-------------------------------------------------------------------------------
lf = ttk.Labelframe(root, text='Plot Area')
lf.grid(row=0, column=0, sticky='nwes', padx=3, pady=3)

f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)
a.plot(t,s)

dataPlot = FigureCanvasTkAgg(f, master=lf)
dataPlot.show()
dataPlot.get_tk_widget().grid(row=0, column=0)
#-------------------------------------------------------------------------------
root.mainloop()

這一切都按預期工作。 我想要做的是在 Tkinter 窗口上有 pandas.DataFrame.plot() 輸出,例如在上面的 Labelframe 中。 我不能讓它工作。 如果可能,我不想使用 matplotlibs 繪圖工具,因為 Pandas 繪圖工具更適合我的需要。 有沒有辦法將 Pandas plot() 與 Tkinter 結合起來? 基本上而不是這一行:

dataPlot = FigureCanvasTkAgg(f, master=lf)
dataPlot.show()

我需要這個:

dataPlot = FigureCanvasTkAgg(df.plot('one'), master=lf)
dataPlot.show()

pandas使用matplotlib進行繪圖。 pandas繪圖功能需要一個ax kwarg指定將要使用的軸對象。 有一些pandas函數不能以這種方式使用,並且將始終使用pyplot創建自己的圖形/軸。 (例如scatter_matrix

但是,對於基於您的示例的簡單案例:

import matplotlib
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import pandas as pd
import Tkinter as tk
import ttk

root = tk.Tk()

lf = ttk.Labelframe(root, text='Plot Area')
lf.grid(row=0, column=0, sticky='nwes', padx=3, pady=3)

t = np.arange(0.0,3.0,0.01)
df = pd.DataFrame({'t':t, 's':np.sin(2*np.pi*t)})

fig = Figure(figsize=(5,4), dpi=100)
ax = fig.add_subplot(111)

df.plot(x='t', y='s', ax=ax)

canvas = FigureCanvasTkAgg(fig, master=lf)
canvas.show()
canvas.get_tk_widget().grid(row=0, column=0)

root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM