使用 tkinter 绘制 pandas 数据帧

Using tkinter to plot pandas dataframes

所以我正在尝试编写一个小型 GUI,它允许最终使用绘制 Excel 文件中任意 2 列的 X 与 Y。这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import tkinter as tk

my_base=pd.read_excel('my_base.xlsx', 'the_tab', index_col=None, na_values = ['NA'])
my_base_header = list(my_base.columns.values)

my_base['Generated Date'] = pd.to_datetime(my_base['Generated Date'])

main_win = tk.Tk()

def plot_graph():
    print(option1.get())
    print(option2.get())
    my_base.plot(x = option1.get(), y = option2.get(), style = 'x')
    plt.show()

option1 = tk.StringVar(main_win)
option1.set(my_base_header[0])
option2 = tk.StringVar(main_win)
option2.set(my_base_header[0])

opt1 = tk.OptionMenu(main_win, option1, *my_base_header)
opt1.pack()
opt2 = tk.OptionMenu(main_win, option2, *my_base_header)
opt2.pack()

runbtn = tk.Button(main_win, text = 'Plot', command = plot_graph)
runbtn.pack()

main_win.mainloop()

如果我像这样直接将数据帧 headers 放入,我可以让程序进行绘图:

my_base.plot(x = 'Generated Date', y = 'How many', style = 'x')

但是当我在那里使用 x = option1.get() 时,我得到了这个回溯

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    my_base.plot(x= x_ax, y = y_ax, style = 'x')
  File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 2485, in plot_frame
    **kwds)
  File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 2325, in _plot
    plot_obj.generate()
  File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 921, in generate
    self._compute_plot_data()
  File "C:\Python34\lib\site-packages\pandas\tools\plotting.py", line 997, in _compute_plot_data
    'plot'.format(numeric_data.__class__.__name__))
TypeError: Empty 'Series': no numeric data to plot

正如错误所说:您尝试绘制的数据是非数字的,因此它可能是一个字符串,或者从它的外观来看,可能是一个日期时间。如果您包括数据以及哪一列给您这个错误,我们可以指出问题。

如果是日期时间,您可能需要将其转换为pandas时间戳类型,例如:

pandas.DatetimeIndex([yourDatetime])

你的代码似乎对我有用。我使用了这个演示数据集: http://www.contextures.com/xlSampleData01.html

如果我尝试绘制一些非数字的东西,例如 'Region' 或 'Rep',它会给我同样的错误(没有要绘制的数字数据)。如果我绘制 'Unit Cost' 与 'Total' 或 2 个数字数据集的任何其他组合,它会起作用。

import pandas as pd
import matplotlib.pyplot as plt
import Tkinter as tk

my_base=pd.read_excel('SampleData.xls', 'SalesOrders', index_col=None, na_values = ['NA'])
my_base_header = list(my_base.columns.values)

#print my_base
my_base['OrderDate'] = pd.to_datetime(my_base['OrderDate'])

main_win = tk.Tk()

def plot_graph():
    print(option1.get())
    print(option2.get())
    my_base.plot(x = option1.get(), y = option2.get(), style = 'x')
    plt.show()

option1 = tk.StringVar(main_win)
option1.set(my_base_header[0])
option2 = tk.StringVar(main_win)
option2.set(my_base_header[0])

opt1 = tk.OptionMenu(main_win, option1, *my_base_header)
opt1.pack()
opt2 = tk.OptionMenu(main_win, option2, *my_base_header)
opt2.pack()

runbtn = tk.Button(main_win, text = 'Plot', command = plot_graph)
runbtn.pack()

main_win.mainloop()