如何将我的 seaborn 图打印到 tkinter window,将显示在 IDE 但不坚持 canvas

How do I print my seaborn plot to a tkinter window, will show in IDE but doesnt stick to canvas

我有:

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()

除了 canvas 之外还启动了 2(?) 空 tkinter windows,但是 IDE 显示了我正在尝试打印的实际图表,所以我知道该函数正在执行它的工作。

如何使返回的图表贴在 window 上?

  • 你得到 2 个空的 windows 因为你使用了 plt.show(),它不打算在 tkinter 应用程序中使用。另一个是空的 tkinter window(通过 tk.Tk() 生成),没有任何内容。
  • 您还错过了向我们提供示例数据 (my_final_data.json)。
  • 稍作研究就会为您带来很多将 seaborn 集成到 tkinter 中的示例
  • sns.distplot 已弃用 here, i would recommend using sns.displot or sns.histplot instead (some nice histplot examples)

这个例子应该让你开始:

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()