我正试图在Tkinter中使用Seaborn进行绘图。到目前为止,我的方法是对此的不同变化,我无法使其正常工作。
我尝试了matplotlib.use(“ Agg”),它在页面上的正常Matplotlib图上工作正常,但似乎不适用于Seaborn图
matplotlib.use("TkAgg") # 'Agg' doesnt work either
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import seaborn as sns
import tkinter as tk
def graphspage():
pf = tk.Tk()
pf.geometry("1000x800")
### Works
f = Figure(figsize=(5, 5), dpi=100)
a = f.add_subplot(111)
a.plot(df['date'],daily_drawdown, 'b-',df['date'], daily_drawdownbm, 'k-', linewidth=1)
f.tight_layout()
canvas = FigureCanvasTkAgg(f,pf)
canvas.get_tk_widget().grid(row=1,column=1)
### Doesnt Work
pct = diststats()[4]
pctbm = diststats()[5]
f = Figure(figsize=(5, 5), dpi=100)
a = f.add_subplot(111)
a.sns.distplot(pct,label = 'Portfolio')
a.sns.distplot(pctbm,axlabel='Distribution of returns',label='Benchmark')
canvas = FigureCanvasTkAgg(f,pf)
canvas.get_tk_widget().grid(row=2,column=1)
graphspage()
答案 0 :(得分:2)
如果我没有记错的话,OP的原始代码仅缺少canvas.draw()
。 furas 也表明了这一点。我最近发现很难找到如何在Tkinter GUI上使用Seaborn进行绘制的完整示例,尤其是如何在画布上进行重新绘制。
所以,让我为您提供一个可以正常工作的最小片段,该程序最初在每次按键时都会绘制和重新绘制。
import tkinter
from typing import Callable
import numpy as np
import seaborn as sns
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
def init_gui(root, update_function: Callable) -> FigureCanvasTkAgg:
def event_key_press(event):
print("you pressed {}".format(event.key))
update_function()
key_press_handler(event, canvas)
# create empty figure and draw
init_figure = create_figure()
canvas = FigureCanvasTkAgg(init_figure, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
# call key press event
canvas.mpl_connect("key_press_event", event_key_press)
return canvas
def create_figure() -> Figure:
# generate some data
matrix = np.random.randint(20, size=(10, 10))
# plot the data
figure = Figure(figsize=(6, 6))
ax = figure.subplots()
sns.heatmap(matrix, square=True, cbar=False, ax=ax)
return figure
def redraw_figure():
figure = create_figure()
canvas.figure = figure
canvas.draw()
sns.set()
root = tkinter.Tk()
canvas = init_gui(root, update_function=redraw_figure)
tkinter.mainloop()
我使用了matplotlib提供的一些example code。
这是上面的代码在执行和按某些键时的外观:
答案 1 :(得分:0)
我拿了example from Seaborn page-我可以运行它-然后放入tkinter
create_plot
中的代码将matplotlib
与seaborn
一起使用来创建绘图,并返回figure
。
稍后这段代码将figure
添加到tkinter的窗口中
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
示例不需要matplotlib.use('TkAgg')
或matplotlib.use('Agg')
有tkinter.Label
,Seaborn的情节和tkinter.Button
,但我也有NavigationToolbar2Tk
完整代码:
# seaborn in matplotlib - tkinter doesn't need it
#import matplotlib
#matplotlib.use('TkAgg')
# embed matplotlib in tkinter
import tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# seaborn example
from string import ascii_letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def create_plot():
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
columns=list(ascii_letters[26:]))
# Compute the correlation matrix
corr = d.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
return f
# --- main ---
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
label = tkinter.Label(root, text="Matplotlib with Seaborn in Tkinter")
label.pack()
fig = create_plot()
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack()
button = tkinter.Button(root, text="Quit", command=root.destroy)
button.pack()
tkinter.mainloop()