Home > Back-end >  How to display statsmodels model summary in tkinter?
How to display statsmodels model summary in tkinter?

Time:09-13

Is there any way to display statsmodels regression results in a tkinter GUI?

What I want is to get something like this output straight into the GUI:

enter image description here

I've been able to get matplotlib output into tkinter using FigureCanvasTkAgg and NavigationToolbar2Tk, but I can't find something similar to this in the statsmodels documentation or basically anywhere on the web.

Surely there's some way?

CodePudding user response:

Success! I managed to find an answer to this question.

Essentially you put the statsmodels model summary into a matplotlib figure, save the figure as an image, and then directly embed the image into tkinter.

Does exactly what I wanted.

Example code:

import statsmodels.api as sm
import matplotlib.pyplot as plt
from tkinter import *
from PIL import ImageTk, Image

# linear regression example using statsmodels 
spector_data = sm.datasets.spector.load()
spector_data.exog = sm.add_constant(spector_data.exog, prepend=False)
model = sm.OLS(spector_data.endog, spector_data.exog)
results = model.fit()

# pass the model results into a matplotlib figure and save as image
plt.rc('figure', figsize=(8, 5))
plt.text(0.01, 0.05, str(results.summary()), {'fontsize': 10}, fontproperties = 'monospace')
plt.axis('off')
plt.tight_layout()
plt.savefig('results.png')

# embed image into tkinter
root = Tk()
img = ImageTk.PhotoImage(Image.open("results.png"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
  • Related