AlBud AlBud - 3 years ago 213
Python Question

Embed vector plot into Tkinter

I've been working on this for a while but I can't seem to get over it. The thing is that I want to insert a vector representation inside a tkinter window. I managed to plot lines and funcions into tkinter, but vectors are a whole different story.
Here's the code I have for embedding so far:

import matplotlib
matplotlib.use('TkAgg')

from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler


from matplotlib.figure import Figure

import tkinter as Tk


root = Tk.Tk()
root.wm_title("Embedding in TK")

f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)

a.plot([7,8], [2, 4])

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)


Tk.mainloop()


And the code for plotting vectors:

import matplotlib.pyplot as plt
import numpy as np
import tkinter as Tk


v1 = (3, -4)
v2 = (-6,4, 10)

soa = np.array([[0, 0, v1[0], v1[1]], [0, 0, v2[0], v2[1]]])
X, Y, U, V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 11])
plt.draw()

plt.show()

Tk.mainloop()


Maybe there is a way to merge these two?

Answer Source

I think you would benefit from reading a bit more on the matplotlib page and look at examples. Then you're making it harder for yourself than it needs to be. Start by calling similar things similarly. In the first case, you have an axes a, in the second case, you call it ax, appart the only difference is really that instead of .plot you need .quiver. plt.show is not needed because you have canvas.show().

import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import numpy as np
from matplotlib.figure import Figure

import tkinter as Tk


root = Tk.Tk()
root.wm_title("Embedding in TK")

f = Figure(figsize=(5, 4), dpi=100)
ax = f.add_subplot(111)

v1 = (3, -4)
v2 = (-6,4, 10)

soa = np.array([[0, 0, v1[0], v1[1]], [0, 0, v2[0], v2[1]]])
X, Y, U, V = zip(*soa)

ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 11])

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)


Tk.mainloop()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download