Roosevelt H
Roosevelt H

Reputation: 340

plotting pandas data in tkinter window

I am trying to plot a pandas dataframe into a tkinter window. Basically what I am trying to accomplish: when a user clicks on the graph button, a graph with the years and values would appear in the tkinter window. But for some weird reason I get an attribute error AttributeError: 'AxesSubplot' object has no attribute 'set_canvas' ' Any idea why this is happening?

plotting.py file:

import matplotlib
import pandas as pd
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

fig, ax = plt.subplots()


def plotGraph(self):
   data2 = {'Year': [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010],
         'Value': [9.8, 12, 8, 7.2, 6.9, 7, 6.5, 6.2, 5.5, 6.3]
         }
   df2 = pd.DataFrame(data2, columns=['Year', 'Value'])
   df2 = df2[['Year', 'Value']].groupby('Year').sum()

   yLabelText = "Value"
   ax.set_xlabel('Years')
   ax.set_ylabel(yLabelText)

   fig = plt.figure(figsize=(12, 10), dpi=80)
   ax1 = fig.add_subplot(111)
   datas = df2.plot(ax=ax1,color ='orange')
   ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
   fig.tight_layout()
   canvas = FigureCanvasTkAgg(datas, self)
   canvas.show()
canvas.get_tk_widget().pack(side=self.BOTTOM, fill=self.BOTH, expand=True)

and the main interface file:

try:
    import Tkinter as tk
except:
    import tkinter as tk

import plotting as pyt


class GetInterfaceValues():
    def __init__(self):
        self.root = tk.Tk()
        self.totalValue = tk.StringVar()

        self.root.geometry('500x200')

        self.plotGraphButton = tk.Button(self.root, text='plot the kegs values', command=self.plot)

        self.plotGraphButton.pack()

        self.root.mainloop()



    def plot(self):
        pyt.plotGraph(self.root)




app = GetInterfaceValues()

Upvotes: 0

Views: 343

Answers (1)

Henry Yik
Henry Yik

Reputation: 22493

You passed the wrong object to FigureCanvasTkAgg.

The setup is FigureCanvasTkAgg(figure, master=None, resize_callback=None), so you need to pass fig instead of data, like so:

def plotGraph(self):
    ...
    canvas = FigureCanvasTkAgg(fig, self)
    canvas.draw()
    canvas.get_tk_widget().pack(side="bottom", fill="both", expand=True)

Also you should be using Figure instead of pyplot when combining tkinter with matplotlib. See this for a sample.

Upvotes: 1

Related Questions