Macro plotting examples
This chapter consists of a series of examples demonstrating how to plot graphics from inside a macro.
The complete set of pyplot
examples can be found
here
1import math
2from numpy import linspace
3from scipy.integrate import quad
4from scipy.special import j0
5
6from sardana.macroserver.macro import macro, Type
7
8
9def j0i(x):
10 """Integral form of J_0(x)"""
11 def integrand(phi):
12 return math.cos(x * math.sin(phi))
13 return (1 / math.pi) * quad(integrand, 0, math.pi)[0]
14
15
16@macro()
17def J0_plot(self):
18 """Sample J0 at linspace(0, 20, 200)"""
19 x = linspace(0, 20, 200)
20 y = j0(x)
21 x1 = x[::10]
22 y1 = list(map(j0i, x1))
23 self.pyplot.plot(x, y, label=r'$J_0(x)$')
24 self.pyplot.plot(x1, y1, 'ro', label=r'$J_0^{integ}(x)$')
25 self.pyplot.title(
26 r'Verify $J_0(x)=\frac{1}{\pi}\int_0^{\pi}\cos(x \sin\phi)\,d\phi$')
27 self.pyplot.xlabel('$x$')
28 self.pyplot.legend()
29 self.pyplot.draw()
30
31
32from numpy import random
33
34
35@macro()
36def random_image(self):
37 """Shows a random image 32x32"""
38 img = random.random((32, 32))
39 self.pyplot.matshow(img)
40 self.pyplot.draw()
41
42import numpy
43
44
45@macro([["interactions", Type.Integer, None, ""],
46 ["density", Type.Integer, None, ""]])
47def mandelbrot(self, interactions, density):
48
49 x_min, x_max = -2, 1
50 y_min, y_max = -1.5, 1.5
51
52 x, y = numpy.meshgrid(numpy.linspace(x_min, x_max, density),
53 numpy.linspace(y_min, y_max, density))
54
55 c = x + 1j * y
56 z = c.copy()
57
58 fractal = numpy.zeros(z.shape, dtype=numpy.uint8) + 255
59
60 for n in range(interactions):
61 z *= z
62 z += c
63 mask = (fractal == 255) & (abs(z) > 10)
64 fractal[mask] = 254 * n / interactions
65 self.pyplot.imshow(fractal)
66 self.pyplot.draw()