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