The following code has to be copied to the file $HOME/sardanaMacros/mpl_plot.py. The macro is available after a restart of the MacroServer.
$ spock Spock 1.0.0 -- An interactive laboratory application. help -> Spock's help system. object? -> Details about 'object'. ?object also works, ?? prints more. p09/door/haso107d1 [2]: mpl_plot
The macro mpl_plot creates the display 9.4.
After mpl_plot has been called, control stays at the graphics window until it is closed by clicking Quit.
The DISPLAY variable, see the code below, is set to :1, if the MacroServer
runs on the host providing the X display. Otherwise
the Unix command $ echo $DISPLAY$ tells you what
to specify, e.g.: localhost:10.0
This is the contents of mpl_plot.py.
#!/bin/env python
__all__ = ["mpl_plot"]
from sardana.macroserver.macro import *
import os, sys, time
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
class mpl_plot( Macro):
"""
this macro plots some data using matplotlib within Tk
"""
def _quit( self):
self.root.quit()
self.root.destroy()
param_def = []
result_def = []
def setup( self):
os.environ[ 'DISPLAY'] = ':1' # used to be: ':0.0'
matplotlib.use('TkAgg')
self.root = Tk.Tk()
self.root.wm_title("Simple Plot")
if not plt.get_fignums():
self.fig = plt.figure( 1, figsize = (6.4, 4.8))
else:
self.fig = plt.figure(1)
self.fig.clear()
canvas = FigureCanvasTkAgg( self.fig, master=self.root)
#canvas.show()
#canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg( canvas, self.root )
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
button = Tk.Button(master=self.root, text='Quit', command = self._quit)
button.pack(side=Tk.BOTTOM)
def run( self):
self.setup()
sin = self.fig.add_subplot(211)
x = np.arange( 0.0, 1.5, 0.01)
s = np.sin( 2*np.pi*x)
sin.plot( x, s)
cos = self.fig.add_subplot(212)
t = np.cos( 2*np.pi*x)
cos.plot( x, t)
Tk.mainloop()