I have:
def create_plot():
df = pd.read_json("my_final_data.json")
small_df = df[df.small_airport.isin(['Y'])]
medium_df = df[df.medium_airport.isin(['Y'])]
large_df = df[df.large_airport.isin(['Y'])]
plt.figure(figsize=(35,10))
ax = sns.distplot(small_df['frequency_mhz'], color='red', label='Small Airports')
sns.distplot(medium_df['frequency_mhz'], color='green', ax=ax, label='Medium Airports')
sns.distplot(large_df['frequency_mhz'], ax=ax, label='Large Airports')
plt.legend(loc="upper right")
graph = plt.show()
return graph
#Generating tkinter window
window1 = tk.Tk()
figure = create_plot()
canvas = FigureCanvasTkAgg(figure, master=window1)
canvas.draw()
canvas.get_tk_widget().pack()
tk.mainloop()
Which launches 2(?) empty tkinter windows besides the canvas in one, but the IDE shows the actual graph im trying to print so I know the function is doing its job.
How do I make that returned graph stick to the window?
CodePudding user response:
- Youre getting 2 empty windows because you used
plt.show()
which is not intended to be used from within a tkinter application. The other one is an empty tkinter window (generated viatk.Tk()
), without any content. - You also missed to give us sample data (
my_final_data.json
). - A little bit of research would have brought you a lot of examples for seaborn integration into tkinter
sns.distplot
is deprecated as mentioned here, i would recommend usingsns.displot
orsns.histplot
instead (some nice histplot examples)
This example should get you started:
import tkinter as tk
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
def create_plot(root):
# create random seaborn displot; replace this part with your own data
figure, ax = plt.subplots(figsize=(6, 6))
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm", ax=ax, hue="species")
# create tkinter canvas from figure
canvas = FigureCanvasTkAgg(figure, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# optional: create toolbar
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# create your application
window1 = tk.Tk()
# call function to create plot
create_plot(window1)
# mainloop
tk.mainloop()