|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# |
| 4 | +# http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html |
| 5 | +# |
| 6 | + |
| 7 | +# --- matplotlib --- |
| 8 | +import matplotlib |
| 9 | +matplotlib.use('TkAgg') # choose backend |
| 10 | + |
| 11 | +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg |
| 12 | +from matplotlib.pyplot import Figure |
| 13 | + |
| 14 | +# --- other --- |
| 15 | +import tkinter as tk |
| 16 | +import pandas as pd |
| 17 | + |
| 18 | +# --- for example data -- |
| 19 | +import random |
| 20 | +import math |
| 21 | + |
| 22 | +# --- random data --- |
| 23 | + |
| 24 | +df1 = pd.DataFrame([random.randint(-100, 100) for _ in range(60)]) |
| 25 | +df2 = pd.DataFrame([math.sin(math.radians(x*6)) for x in range(60)]) |
| 26 | + |
| 27 | +# --- GUI --- |
| 28 | + |
| 29 | +root = tk.Tk() |
| 30 | + |
| 31 | +# top frame for canvas and toolbar - which need `pack()` layout manager |
| 32 | +top = tk.Frame(root) |
| 33 | +top.pack() |
| 34 | + |
| 35 | +# bottom frame for other widgets - which may use other layout manager |
| 36 | +bottom = tk.Frame(root) |
| 37 | +bottom.pack() |
| 38 | + |
| 39 | +# --- canvas and toolbar in top --- |
| 40 | + |
| 41 | +# create figure |
| 42 | +fig = matplotlib.pyplot.Figure() |
| 43 | + |
| 44 | +# create matplotlib canvas using `fig` and assign to window `top` |
| 45 | +canvas = FigureCanvasTkAgg(fig, top) |
| 46 | +# get canvas as tkinter widget and put in window |
| 47 | +canvas.get_tk_widget().pack() |
| 48 | + |
| 49 | +# create toolbar |
| 50 | +toolbar = NavigationToolbar2TkAgg(canvas, top) |
| 51 | +toolbar.update() |
| 52 | +canvas._tkcanvas.pack() |
| 53 | + |
| 54 | +# --- first plot --- |
| 55 | + |
| 56 | +# create first place for plot |
| 57 | +ax1 = fig.add_subplot(211) |
| 58 | + |
| 59 | +# draw on this plot |
| 60 | +df1.plot(kind='bar', legend=False, ax=ax1) |
| 61 | + |
| 62 | +# --- second plot --- |
| 63 | + |
| 64 | +# create second place for plot |
| 65 | +ax2 = fig.add_subplot(212) |
| 66 | + |
| 67 | +# draw on this plot |
| 68 | +df2.plot(kind='bar', legend=False, ax=ax2) |
| 69 | + |
| 70 | +# --- other widgets in bottom --- |
| 71 | + |
| 72 | +b = tk.Button(bottom, text='Exit', command=root.destroy) |
| 73 | +b.pack() |
| 74 | + |
| 75 | +# --- start ---- |
| 76 | + |
| 77 | +root.mainloop() |
0 commit comments