Skip to content

scan_plot_manager

Plot Manager for the Scan object

ScanPlotManager

ScanPlotManager scan.plot = ScanPlotManager(scan) scan.plot() # plot default axes scan.plot.plot(xaxis, yaxis) # creates figure scan.plot.plotline(xaxis, yaxis) # plots line on current figure scan.plot.image() # create figure and display detector image

Parameters:

Name Type Description Default
scan NexusScan

NexusScan object

required
Source code in mmg_toolbox/plotting/scan_plot_manager.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
class ScanPlotManager:
    """
    ScanPlotManager
        scan.plot = ScanPlotManager(scan)
        scan.plot() # plot default axes
        scan.plot.plot(xaxis, yaxis)  # creates figure
        scan.plot.plotline(xaxis, yaxis)  # plots line on current figure
        scan.plot.image()  # create figure and display detector image

    :param scan: NexusScan object
    """
    set_plot_defaults = set_plot_defaults

    def __init__(self, scan: NexusScan):
        self.scan = scan
        self.show = plt.show
        self._x_axis: str | None = None
        self._y_axis: str | None = None
        self._z_axis: str | None = None

    def __call__(self, *args, **kwargs) -> plt.Axes:
        if self.scan.map.scannables_length() == 1 and self.scan.map.image_data:
            return self.image(*args, **kwargs)
        if len(self.scan.map.scannables_shape()) == 2:
            return self.map2d(*args, **kwargs)
        return self.plot(*args, **kwargs)

    def _set_axes(self, x_axis: str | None = None, y_axis: str | None = None, z_axis: str | None = None):
        self._x_axis = x_axis
        self._y_axis = y_axis
        self._z_axis = z_axis

    def plotline(self, xaxis: str = 'axes', yaxis: str = 'signal',
                 *args, axes: plt.Axes | None, **kwargs) -> list[plt.Line2D]:
        """
        Plot scanned datasets on matplotlib axes subplot

        :param xaxis: str name or address of array to plot on x axis
        :param yaxis: str name or address of array to plot on y axis
        :param args: given directly to plt.plot(..., *args, **kwars)
        :param axes: matplotlib.axes subplot, or None to use plt.gca()
        :param kwargs: given directly to plt.plot(..., *args, **kwars)
        :return: list lines object, output of plot
        """
        data = self.scan.get_plot_data(xaxis, yaxis)

        if 'label' not in kwargs:
            kwargs['label'] = self.scan.label()
        axes = new_plot() if axes is None else axes
        lines = plot_line(axes, data['x'], data['y'], None, *args, **kwargs)
        self._set_axes(data['xlabel'], data['ylabel'])
        return lines

    def plot(self, xaxis: str = 'axes', yaxis: str | list[str] = 'signal', *args,
             axes: plt.Axes | None = None, **kwargs) -> plt.Axes:
        """
        Create matplotlib figure with 1D lineplot of the scan

        :param xaxis: str name or address of array to plot on x axis
        :param yaxis: str name or address of array to plot on y axis, also accepts list of names for multiple lines
        :param args: given directly to plt.plot(..., *args, **kwars)
        :param axes: matplotlib.axes subplot, or None to create a figure
        :param kwargs: given directly to plt.plot(..., *args, **kwars)
        :return: axes object
        """
        axes = new_plot() if axes is None else axes

        yaxis = [yaxis] if isinstance(yaxis, str) else yaxis
        data = self.scan.get_plot_data(xaxis, *yaxis)
        plot_line(axes, data['xdata'], data['ydata'], None, *args, **kwargs)

        # Add labels
        self._set_axes(data['xlabel'], data['ylabel'])
        axes.set_xlabel(data['xlabel'])
        axes.set_title(data['title'])
        if len(yaxis) == 1:
            axes.set_ylabel(data['ylabel'])
        else:
            axes.legend(data['legend'])
        return axes

    def map2d(self, xaxis: str = 'axes0', yaxis: str = 'axes1', zaxis: str = 'signal',
              axes: plt.Axes | None = None, clim: tuple[float, float] | None = None,
              cmap: str = DEFAULT_CMAP, colorbar: bool = True, **kwargs) -> plt.Axes:
        """
        Create matplotlib figure with 2D colormap of the scan, for 2D grid scans

        :param xaxis: str name or address of array to plot on x-axis
        :param yaxis: str name or address of array to plot on y-axis
        :param zaxis: str name or address of array to plot on colour axis
        :param axes: matplotlib axes to plot on (None to create figure)
        :param clim: [min, max] colormap cut-offs (None for auto)
        :param cmap: str colormap name (None for auto)
        :param colorbar: False/ True add colorbar to plot
        :param axes: matplotlib.axes subplot, or None to create a figure
        :param kwargs: given directly to plt.pcolormesh(..., *args, **kwars)
        :return: axes object
        """
        if len(self.scan.map.scannables_shape()) != 2:
            raise ValueError(f"Scan {repr(self.scan)} has shape {self.scan.map.scannables_shape()} inconsistent with map2d")
        data = self.scan.get_plot_data(xaxis, yaxis, z_axis=zaxis)

        axes = new_plot() if axes is None else axes
        mesh = plot_2d_surface(
            axes=axes,
            xdata=data['grid_xdata'],
            ydata=data['grid_ydata'],
            image=data['grid_data'],
            clim=clim,
            cmap=cmap,
            **kwargs
        )
        axes.set_xlabel(data['grid_xlabel'])
        axes.set_ylabel(data['grid_ylabel'])
        axes.set_title(data['title'])
        self._set_axes(data['grid_xlabel'], data['grid_ylabel'])
        if colorbar:
            plt.colorbar(mesh, ax=axes, label=data['grid_label'])
        return axes

    def plot3d(self, xaxis: str = 'axes0', yaxis: str = 'axes1', zaxis: str = 'signal',
               axes: plt.Axes | None = None, **kwargs) -> Axes3D:
        """
        Create matplotlib figure with 3D plot, for 2D grid scans

        :param xaxis: str name or address of array to plot on x-axis
        :param yaxis: str name or address of array to plot on y-axis
        :param zaxis: str name or address of array to plot on z-axis
        :param axes: matplotlib axes to plot on (None to create figure)
        :param axes: matplotlib.axes subplot, or None to create a figure
        :param kwargs: given directly to plt.pcolormesh(..., *args, **kwars)
        :return: axes object
        """
        if len(self.scan.map.scannables_shape()) != 2:
            raise ValueError(f"Scan {repr(self.scan)} has shape {self.scan.map.scannables_shape()} inconsistent with map2d")
        data = self.scan.get_plot_data(xaxis, yaxis, z_axis=zaxis)

        axes = new_plot('3d') if axes is None else axes
        lines = plot_3d_lines(
            axes=axes,
            xdata=data['grid_xdata'],
            ydata=data['grid_ydata'],
            zdata=data['grid_data'],
            **kwargs
        )
        axes.set_xlabel(data['grid_xlabel'])
        axes.set_ylabel(data['grid_ylabel'])
        axes.set_zlabel(data['grid_label'])
        axes.set_title(data['title'])
        self._set_axes(data['grid_xlabel'], data['grid_ylabel'], data['grid_label'])
        return axes

    def image(self, index: int | str | None = None, xaxis: str = 'axes',
              axes: plt.Axes | None = None, clim: tuple[float, float] | None = None,
              cmap: str = DEFAULT_CMAP, colorbar: bool = False,
              log: bool = False, rois: bool = False, **kwargs) -> plt.Axes:
        """
        Plot image in matplotlib figure (if available)
        :param index: int, detector image index, 0-length of scan, 'sum' gives sum of stack. If None, use centre index
        :param xaxis: name or address of xaxis dataset
        :param axes: matplotlib axes to plot on (None to create figure)
        :param clim: [min, max] colormap cut-offs (None for auto)
        :param cmap: str colormap name (None for auto)
        :param colorbar: False/ True add colorbar to plot
        :param log: False/ True plot log10 of the image
        :param rois: False/ True plot ROIs on the image
        :param kwargs: additional arguments for plot_detector_image
        :return: axes object
        """
        # x axis data
        xdata, xname = self.scan.get_plot_axis(xaxis, reduce_shape=True, flatten=True)

        # image data
        im = self.scan.image(index)
        im = np.log10(im + 1) if log else im
        if im is None:
            im = np.zeros((101, 101))
        if index is None or index == 'sum':
            xvalue = xdata[np.size(xdata) // 2]
        else:
            xvalue = xdata[index]

        # plot
        axes = new_plot() if axes is None else axes
        plot_image(axes, im, clim=clim, cmap=cmap, **kwargs)
        if not self.scan.map.image_data:
            axes.text(0.5, 0.5, 'No Detector Image', c='w',
                      horizontalalignment='center',
                      verticalalignment='center',
                      transform=axes.transAxes)
        if colorbar:
            im = next(c for c in axes.get_children() if isinstance(c, QuadMesh))
            plt.colorbar(im, ax=axes, label='log10(counts)' if log else 'counts')
        ttl = '%s\n%s [%s] = %s' % (self.scan.title(), xname, index, xvalue)
        axes.set_title(ttl)
        self._set_axes('Pixel x', 'Pixel y')
        if rois:
            rois = self.scan.rois('')
            for roi in rois:
                box = self.scan.eval(f"{roi}_box")
                axes.plot(box[:, 1], box[:, 0], '-', lw=1, label=roi)
            axes.legend()
        return axes

    def image_sum(self, index: int | tuple | slice | str | None = None, sum_axis: int = 0, xaxis: str = 'axes',
                  axes: plt.Axes | None = None, x_label: str | None = None, x_scale: float = 1.0, x_offset: float = 0.0,
                  **kwargs) -> plt.Axes:
        """
        Plot image summed along one axis in matplotlib figure (if available)
        :param index: int, detector image index, 0-length of scan, if None, use centre index, if 'sum', sum stack
        :param sum_axis: axis to sum (0 or 1)
        :param xaxis: name or address of axes dataset (for title)
        :param axes: matplotlib axes to plot on (None to create figure)
        :param x_label: str name of plot label on x-axis
        :param x_scale: scale of x-axis (default to 1)
        :param x_offset: offset of x-axis (default to 0)
        :param kwargs: additional arguments for plot_detector_image
        :return: axes object
        """
        # x axis data
        xdata, xname = self.scan.get_plot_axis(xaxis, reduce_shape=True, flatten=True)

        # image data
        im = self.scan.image(index)
        if im is None:
            im = np.zeros((101, 101))
        if index is None or index == 'sum':
            xvalue = xdata[np.size(xdata) // 2]
        else:
            xvalue = xdata[index]

        # sum image
        line = im.sum(axis=sum_axis)
        xdata = x_scale * np.arange(line.size) + x_offset

        # plot
        axes = new_plot() if axes is None else axes
        plot_line(axes, xdata, line, **kwargs)
        if not self.scan.map.image_data:
            axes.text(0.5, 0.5, 'No Detector Image', c='w',
                      horizontalalignment='center',
                      verticalalignment='center',
                      transform=axes.transAxes)
        ttl = '%s\n%s [%s] = %s' % (self.scan.title(), xname, index, xvalue)
        axes.set_title(ttl)
        axes.set_xlabel(x_label)
        self._set_axes(x_label, 'Intensity')
        return axes

    def roi(self, roi_name: str, **kwargs) -> plt.Figure:
        """
        Create matplotlib figure with plot of a detector ROI and integrated area
        :param roi_name: name of ROI to plot
        :param kwargs: additional arguments for matplotlib.subplots
        :return: matplotlib figure
        """
        if roi_name not in self.scan.rois(''):
            raise Exception(f'ROI "{roi_name}" not found in scan')

        axes_values, axes_name = self.scan.get_plot_axis('axes')
        roi_total = self.scan.eval(f"{roi_name}_total")
        roi_box = self.scan.eval(f"{roi_name}_box")
        if f"{roi_name}_pos" in self.scan.map.alternate_names:
            pi, pj, pk = self.scan.eval(f"{roi_name}_pos")
        else:
            pi = np.argmax(roi_total)
            pj, pk = np.mean(roi_box, axis=1)
        det_image = self.scan.image(pi)
        roi_image = self.scan.eval(f"{roi_name}[{pi}]")

        fig, (ax1, ax2, ax3) = plt.subplots(1, 3, **kwargs)
        plot_image(ax1, det_image)
        ax1.plot(roi_box[:, 1], roi_box[:, 0], label=roi_name)
        detector = self.scan.replace_default_names('IMAGE')
        ax1.set_title(detector)

        plot_image(ax2, roi_image)
        ax2.plot([pk], [pj], '+', markersize=10, color='black')
        ax2.set_title(roi_name)

        ax3.plot(axes_values, roi_total, label=f"{roi_name}_total")
        ax3.set_xlabel(axes_name)
        ax3.set_ylabel(roi_name)
        fig.suptitle(self.scan.title())
        return fig

    def detail(self, xaxis: str = 'axes', yaxis: str | list[str] = 'signal',
               index: int | tuple | slice | None = None, clim: tuple[float, float] | None = None,
               cmap: str = DEFAULT_CMAP, **kwargs) -> plt.Figure:
        """
        Create matplotlib figure with plot of the scan and detector image
        :param xaxis: str name or address of array to plot on x axis
        :param yaxis: str name or address of array to plot on y axis, also accepts list of names for multiple plots
        :param index: int, detector image index, 0-length of scan, if None, use centre index
        :param clim: [min, max] colormap cut-offs (None for auto)
        :param cmap: str colormap name (None for auto)
        :param kwargs: given directly to plt.plot(..., *args, **kwars)
        :return: figure object
        """

        # Create figure
        fig, ((lt, rt), (lb, rb)) = plt.subplots(2, 2, figsize=[FIG_SIZE[0] * 1.2, FIG_SIZE[1] * 1.2], dpi=FIG_DPI)
        fig.subplots_adjust(hspace=0.35, left=0.1, right=0.95)

        # Top left - line plot
        self.plot(xaxis, yaxis, axes=lt, **kwargs)

        # Top right - image plot
        try:
            self.image(index, xaxis, cmap=cmap, clim=clim, axes=rt)
        except (FileNotFoundError, KeyError, TypeError):
            rt.text(0.5, 0.5, 'No Image')
            rt.set_axis_off()

        # Bottom-Left - details
        details = str(self.scan)
        lb.text(-0.2, 1, details, ha='left', va='top', multialignment="left", fontsize=12, wrap=True)
        lb.set_axis_off()

        # Bottom-Right - fit results
        rb.set_axis_off()
        if 'fit' in yaxis:
            fit_report = str(self.scan.fit)
            rb.text(-0.2, 1, fit_report, ha='left', va='top',  multialignment="left", fontsize=12, wrap=True)
        return fig

    def scananddetector(self, xaxis: str = 'axes', yaxis: str | list[str] = 'signal',
                        index: int | tuple | slice | None = None, clim: tuple[float, float] | None = None,
                        cmap: str = DEFAULT_CMAP, **kwargs) -> plt.Figure:
        """
        Create matplotlib figure with plot of the scan and detector image
        :param xaxis: str name or address of array to plot on x axis
        :param yaxis: str name or address of array to plot on y axis, also accepts list of names for multiple plots
        :param index: int, detector image index, 0-length of scan, if None, use centre index
        :param clim: [min, max] colormap cut-offs (None for auto)
        :param cmap: str colormap name (None for auto)
        :param kwargs: given directly to plt.plot(..., *args, **kwars)
        :return: Figure object
        """

        # Create figure
        fig, (lt, rt) = plt.subplots(1, 2, figsize=[FIG_SIZE[0] * 1.5, FIG_SIZE[1]], dpi=FIG_DPI)
        fig.subplots_adjust(hspace=0.35, left=0.1, right=0.95)

        # left - line plot
        self.plot(xaxis, yaxis, axes=lt, **kwargs)

        # right - image plot
        self.image(index, xaxis, cmap=cmap, clim=clim, axes=rt)
        return fig

    def image_histogram(self, index: int | tuple | slice | None = (),
                        axes: plt.Axes | None = None, **kwargs) -> plt.Axes:
        """
        Plot histogram of detector images in matplotlib figure
        :param index: int, detector image index, 0-length of scan, if None, use centre index
        :param axes: matplotlib axes to plot on (None to create figure)
        :param kwargs: additional arguments for plt.hist
        :return: axes object
        """
        if index is None:
            index = ()
        vol = self.scan.get_image(index=index)
        axes = new_plot() if axes is None else axes
        axes.hist(np.log10(vol[vol > 0].flatten()), 100, **kwargs)

        axes.set_xlabel('Log$_{10}$ Pixel Intensity')
        axes.set_ylabel('N')
        axes.set_title(self.scan.title())
        self._set_axes('Log$_{10}$ Pixel Intensity', 'N')
        return axes

    def axes_labels(self, axes: plt.Axes | None = None, x_label: bool | str | None = True,
                    y_label: bool | str | None = True, z_label: bool | str | None = True,
                    title: bool | str | None = True, legend: bool | None = True):
        """
        Set the axes labels using default or specified labels

        Each axis can be one of three values:

            - True: Use the last plotted axes or the default one
            - 'expression': convert expression into the axis name (defaults are replaced with actual names)
            - None: axis is not updated

        :param axes: matplotlib Axes object
        :param x_label: x-axis label
        :param y_label: y-axis label
        :param z_label: z-axis label (if available)
        :param title: axis title
        :param legend: True/False - add legend
        """
        if axes is None:
            axes = plt.gca()

        def update(fn, value, default):
            if value:  # True or str
                if not isinstance(value, str): # True
                    value = default
                fn(self.scan.replace_default_names(value))

        if title:
            if not isinstance(title, str):
                title = self.scan.title()
            axes.set_title(title)

        if z_label and isinstance(axes, Axes3D):
            # assume 3D plot with set_zlabel
            update(axes.set_xlabel, x_label, self._x_axis or 'axes0')
            update(axes.set_ylabel, y_label, self._y_axis or 'axes1')
            update(axes.set_zlabel, z_label, self._z_axis or 'signal')
        else:
            update(axes.set_xlabel, x_label, self._x_axis or 'axes')
            update(axes.set_ylabel, y_label, self._y_axis or 'signal')

        if legend:
            handles, labels = axes.get_legend_handles_labels()
            if handles:
                axes.legend()

axes_labels(axes=None, x_label=True, y_label=True, z_label=True, title=True, legend=True)

Set the axes labels using default or specified labels

Each axis can be one of three values:

- True: Use the last plotted axes or the default one
- 'expression': convert expression into the axis name (defaults are replaced with actual names)
- None: axis is not updated

Parameters:

Name Type Description Default
axes Axes | None

matplotlib Axes object

None
x_label bool | str | None

x-axis label

True
y_label bool | str | None

y-axis label

True
z_label bool | str | None

z-axis label (if available)

True
title bool | str | None

axis title

True
legend bool | None

True/False - add legend

True
Source code in mmg_toolbox/plotting/scan_plot_manager.py
def axes_labels(self, axes: plt.Axes | None = None, x_label: bool | str | None = True,
                y_label: bool | str | None = True, z_label: bool | str | None = True,
                title: bool | str | None = True, legend: bool | None = True):
    """
    Set the axes labels using default or specified labels

    Each axis can be one of three values:

        - True: Use the last plotted axes or the default one
        - 'expression': convert expression into the axis name (defaults are replaced with actual names)
        - None: axis is not updated

    :param axes: matplotlib Axes object
    :param x_label: x-axis label
    :param y_label: y-axis label
    :param z_label: z-axis label (if available)
    :param title: axis title
    :param legend: True/False - add legend
    """
    if axes is None:
        axes = plt.gca()

    def update(fn, value, default):
        if value:  # True or str
            if not isinstance(value, str): # True
                value = default
            fn(self.scan.replace_default_names(value))

    if title:
        if not isinstance(title, str):
            title = self.scan.title()
        axes.set_title(title)

    if z_label and isinstance(axes, Axes3D):
        # assume 3D plot with set_zlabel
        update(axes.set_xlabel, x_label, self._x_axis or 'axes0')
        update(axes.set_ylabel, y_label, self._y_axis or 'axes1')
        update(axes.set_zlabel, z_label, self._z_axis or 'signal')
    else:
        update(axes.set_xlabel, x_label, self._x_axis or 'axes')
        update(axes.set_ylabel, y_label, self._y_axis or 'signal')

    if legend:
        handles, labels = axes.get_legend_handles_labels()
        if handles:
            axes.legend()

detail(xaxis='axes', yaxis='signal', index=None, clim=None, cmap=DEFAULT_CMAP, **kwargs)

Create matplotlib figure with plot of the scan and detector image

Parameters:

Name Type Description Default
xaxis str

str name or address of array to plot on x axis

'axes'
yaxis str | list[str]

str name or address of array to plot on y axis, also accepts list of names for multiple plots

'signal'
index int | tuple | slice | None

int, detector image index, 0-length of scan, if None, use centre index

None
clim tuple[float, float] | None

[min, max] colormap cut-offs (None for auto)

None
cmap str

str colormap name (None for auto)

DEFAULT_CMAP
kwargs

given directly to plt.plot(..., args, *kwars)

{}

Returns:

Type Description
Figure

figure object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def detail(self, xaxis: str = 'axes', yaxis: str | list[str] = 'signal',
           index: int | tuple | slice | None = None, clim: tuple[float, float] | None = None,
           cmap: str = DEFAULT_CMAP, **kwargs) -> plt.Figure:
    """
    Create matplotlib figure with plot of the scan and detector image
    :param xaxis: str name or address of array to plot on x axis
    :param yaxis: str name or address of array to plot on y axis, also accepts list of names for multiple plots
    :param index: int, detector image index, 0-length of scan, if None, use centre index
    :param clim: [min, max] colormap cut-offs (None for auto)
    :param cmap: str colormap name (None for auto)
    :param kwargs: given directly to plt.plot(..., *args, **kwars)
    :return: figure object
    """

    # Create figure
    fig, ((lt, rt), (lb, rb)) = plt.subplots(2, 2, figsize=[FIG_SIZE[0] * 1.2, FIG_SIZE[1] * 1.2], dpi=FIG_DPI)
    fig.subplots_adjust(hspace=0.35, left=0.1, right=0.95)

    # Top left - line plot
    self.plot(xaxis, yaxis, axes=lt, **kwargs)

    # Top right - image plot
    try:
        self.image(index, xaxis, cmap=cmap, clim=clim, axes=rt)
    except (FileNotFoundError, KeyError, TypeError):
        rt.text(0.5, 0.5, 'No Image')
        rt.set_axis_off()

    # Bottom-Left - details
    details = str(self.scan)
    lb.text(-0.2, 1, details, ha='left', va='top', multialignment="left", fontsize=12, wrap=True)
    lb.set_axis_off()

    # Bottom-Right - fit results
    rb.set_axis_off()
    if 'fit' in yaxis:
        fit_report = str(self.scan.fit)
        rb.text(-0.2, 1, fit_report, ha='left', va='top',  multialignment="left", fontsize=12, wrap=True)
    return fig

image(index=None, xaxis='axes', axes=None, clim=None, cmap=DEFAULT_CMAP, colorbar=False, log=False, rois=False, **kwargs)

Plot image in matplotlib figure (if available)

Parameters:

Name Type Description Default
index int | str | None

int, detector image index, 0-length of scan, 'sum' gives sum of stack. If None, use centre index

None
xaxis str

name or address of xaxis dataset

'axes'
axes Axes | None

matplotlib axes to plot on (None to create figure)

None
clim tuple[float, float] | None

[min, max] colormap cut-offs (None for auto)

None
cmap str

str colormap name (None for auto)

DEFAULT_CMAP
colorbar bool

False/ True add colorbar to plot

False
log bool

False/ True plot log10 of the image

False
rois bool

False/ True plot ROIs on the image

False
kwargs

additional arguments for plot_detector_image

{}

Returns:

Type Description
Axes

axes object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def image(self, index: int | str | None = None, xaxis: str = 'axes',
          axes: plt.Axes | None = None, clim: tuple[float, float] | None = None,
          cmap: str = DEFAULT_CMAP, colorbar: bool = False,
          log: bool = False, rois: bool = False, **kwargs) -> plt.Axes:
    """
    Plot image in matplotlib figure (if available)
    :param index: int, detector image index, 0-length of scan, 'sum' gives sum of stack. If None, use centre index
    :param xaxis: name or address of xaxis dataset
    :param axes: matplotlib axes to plot on (None to create figure)
    :param clim: [min, max] colormap cut-offs (None for auto)
    :param cmap: str colormap name (None for auto)
    :param colorbar: False/ True add colorbar to plot
    :param log: False/ True plot log10 of the image
    :param rois: False/ True plot ROIs on the image
    :param kwargs: additional arguments for plot_detector_image
    :return: axes object
    """
    # x axis data
    xdata, xname = self.scan.get_plot_axis(xaxis, reduce_shape=True, flatten=True)

    # image data
    im = self.scan.image(index)
    im = np.log10(im + 1) if log else im
    if im is None:
        im = np.zeros((101, 101))
    if index is None or index == 'sum':
        xvalue = xdata[np.size(xdata) // 2]
    else:
        xvalue = xdata[index]

    # plot
    axes = new_plot() if axes is None else axes
    plot_image(axes, im, clim=clim, cmap=cmap, **kwargs)
    if not self.scan.map.image_data:
        axes.text(0.5, 0.5, 'No Detector Image', c='w',
                  horizontalalignment='center',
                  verticalalignment='center',
                  transform=axes.transAxes)
    if colorbar:
        im = next(c for c in axes.get_children() if isinstance(c, QuadMesh))
        plt.colorbar(im, ax=axes, label='log10(counts)' if log else 'counts')
    ttl = '%s\n%s [%s] = %s' % (self.scan.title(), xname, index, xvalue)
    axes.set_title(ttl)
    self._set_axes('Pixel x', 'Pixel y')
    if rois:
        rois = self.scan.rois('')
        for roi in rois:
            box = self.scan.eval(f"{roi}_box")
            axes.plot(box[:, 1], box[:, 0], '-', lw=1, label=roi)
        axes.legend()
    return axes

image_histogram(index=(), axes=None, **kwargs)

Plot histogram of detector images in matplotlib figure

Parameters:

Name Type Description Default
index int | tuple | slice | None

int, detector image index, 0-length of scan, if None, use centre index

()
axes Axes | None

matplotlib axes to plot on (None to create figure)

None
kwargs

additional arguments for plt.hist

{}

Returns:

Type Description
Axes

axes object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def image_histogram(self, index: int | tuple | slice | None = (),
                    axes: plt.Axes | None = None, **kwargs) -> plt.Axes:
    """
    Plot histogram of detector images in matplotlib figure
    :param index: int, detector image index, 0-length of scan, if None, use centre index
    :param axes: matplotlib axes to plot on (None to create figure)
    :param kwargs: additional arguments for plt.hist
    :return: axes object
    """
    if index is None:
        index = ()
    vol = self.scan.get_image(index=index)
    axes = new_plot() if axes is None else axes
    axes.hist(np.log10(vol[vol > 0].flatten()), 100, **kwargs)

    axes.set_xlabel('Log$_{10}$ Pixel Intensity')
    axes.set_ylabel('N')
    axes.set_title(self.scan.title())
    self._set_axes('Log$_{10}$ Pixel Intensity', 'N')
    return axes

image_sum(index=None, sum_axis=0, xaxis='axes', axes=None, x_label=None, x_scale=1.0, x_offset=0.0, **kwargs)

Plot image summed along one axis in matplotlib figure (if available)

Parameters:

Name Type Description Default
index int | tuple | slice | str | None

int, detector image index, 0-length of scan, if None, use centre index, if 'sum', sum stack

None
sum_axis int

axis to sum (0 or 1)

0
xaxis str

name or address of axes dataset (for title)

'axes'
axes Axes | None

matplotlib axes to plot on (None to create figure)

None
x_label str | None

str name of plot label on x-axis

None
x_scale float

scale of x-axis (default to 1)

1.0
x_offset float

offset of x-axis (default to 0)

0.0
kwargs

additional arguments for plot_detector_image

{}

Returns:

Type Description
Axes

axes object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def image_sum(self, index: int | tuple | slice | str | None = None, sum_axis: int = 0, xaxis: str = 'axes',
              axes: plt.Axes | None = None, x_label: str | None = None, x_scale: float = 1.0, x_offset: float = 0.0,
              **kwargs) -> plt.Axes:
    """
    Plot image summed along one axis in matplotlib figure (if available)
    :param index: int, detector image index, 0-length of scan, if None, use centre index, if 'sum', sum stack
    :param sum_axis: axis to sum (0 or 1)
    :param xaxis: name or address of axes dataset (for title)
    :param axes: matplotlib axes to plot on (None to create figure)
    :param x_label: str name of plot label on x-axis
    :param x_scale: scale of x-axis (default to 1)
    :param x_offset: offset of x-axis (default to 0)
    :param kwargs: additional arguments for plot_detector_image
    :return: axes object
    """
    # x axis data
    xdata, xname = self.scan.get_plot_axis(xaxis, reduce_shape=True, flatten=True)

    # image data
    im = self.scan.image(index)
    if im is None:
        im = np.zeros((101, 101))
    if index is None or index == 'sum':
        xvalue = xdata[np.size(xdata) // 2]
    else:
        xvalue = xdata[index]

    # sum image
    line = im.sum(axis=sum_axis)
    xdata = x_scale * np.arange(line.size) + x_offset

    # plot
    axes = new_plot() if axes is None else axes
    plot_line(axes, xdata, line, **kwargs)
    if not self.scan.map.image_data:
        axes.text(0.5, 0.5, 'No Detector Image', c='w',
                  horizontalalignment='center',
                  verticalalignment='center',
                  transform=axes.transAxes)
    ttl = '%s\n%s [%s] = %s' % (self.scan.title(), xname, index, xvalue)
    axes.set_title(ttl)
    axes.set_xlabel(x_label)
    self._set_axes(x_label, 'Intensity')
    return axes

map2d(xaxis='axes0', yaxis='axes1', zaxis='signal', axes=None, clim=None, cmap=DEFAULT_CMAP, colorbar=True, **kwargs)

Create matplotlib figure with 2D colormap of the scan, for 2D grid scans

Parameters:

Name Type Description Default
xaxis str

str name or address of array to plot on x-axis

'axes0'
yaxis str

str name or address of array to plot on y-axis

'axes1'
zaxis str

str name or address of array to plot on colour axis

'signal'
axes Axes | None

matplotlib axes to plot on (None to create figure)

None
clim tuple[float, float] | None

[min, max] colormap cut-offs (None for auto)

None
cmap str

str colormap name (None for auto)

DEFAULT_CMAP
colorbar bool

False/ True add colorbar to plot

True
kwargs

given directly to plt.pcolormesh(..., args, *kwars)

{}

Returns:

Type Description
Axes

axes object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def map2d(self, xaxis: str = 'axes0', yaxis: str = 'axes1', zaxis: str = 'signal',
          axes: plt.Axes | None = None, clim: tuple[float, float] | None = None,
          cmap: str = DEFAULT_CMAP, colorbar: bool = True, **kwargs) -> plt.Axes:
    """
    Create matplotlib figure with 2D colormap of the scan, for 2D grid scans

    :param xaxis: str name or address of array to plot on x-axis
    :param yaxis: str name or address of array to plot on y-axis
    :param zaxis: str name or address of array to plot on colour axis
    :param axes: matplotlib axes to plot on (None to create figure)
    :param clim: [min, max] colormap cut-offs (None for auto)
    :param cmap: str colormap name (None for auto)
    :param colorbar: False/ True add colorbar to plot
    :param axes: matplotlib.axes subplot, or None to create a figure
    :param kwargs: given directly to plt.pcolormesh(..., *args, **kwars)
    :return: axes object
    """
    if len(self.scan.map.scannables_shape()) != 2:
        raise ValueError(f"Scan {repr(self.scan)} has shape {self.scan.map.scannables_shape()} inconsistent with map2d")
    data = self.scan.get_plot_data(xaxis, yaxis, z_axis=zaxis)

    axes = new_plot() if axes is None else axes
    mesh = plot_2d_surface(
        axes=axes,
        xdata=data['grid_xdata'],
        ydata=data['grid_ydata'],
        image=data['grid_data'],
        clim=clim,
        cmap=cmap,
        **kwargs
    )
    axes.set_xlabel(data['grid_xlabel'])
    axes.set_ylabel(data['grid_ylabel'])
    axes.set_title(data['title'])
    self._set_axes(data['grid_xlabel'], data['grid_ylabel'])
    if colorbar:
        plt.colorbar(mesh, ax=axes, label=data['grid_label'])
    return axes

plot(xaxis='axes', yaxis='signal', *args, axes=None, **kwargs)

Create matplotlib figure with 1D lineplot of the scan

Parameters:

Name Type Description Default
xaxis str

str name or address of array to plot on x axis

'axes'
yaxis str | list[str]

str name or address of array to plot on y axis, also accepts list of names for multiple lines

'signal'
args

given directly to plt.plot(..., args, *kwars)

()
axes Axes | None

matplotlib.axes subplot, or None to create a figure

None
kwargs

given directly to plt.plot(..., args, *kwars)

{}

Returns:

Type Description
Axes

axes object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def plot(self, xaxis: str = 'axes', yaxis: str | list[str] = 'signal', *args,
         axes: plt.Axes | None = None, **kwargs) -> plt.Axes:
    """
    Create matplotlib figure with 1D lineplot of the scan

    :param xaxis: str name or address of array to plot on x axis
    :param yaxis: str name or address of array to plot on y axis, also accepts list of names for multiple lines
    :param args: given directly to plt.plot(..., *args, **kwars)
    :param axes: matplotlib.axes subplot, or None to create a figure
    :param kwargs: given directly to plt.plot(..., *args, **kwars)
    :return: axes object
    """
    axes = new_plot() if axes is None else axes

    yaxis = [yaxis] if isinstance(yaxis, str) else yaxis
    data = self.scan.get_plot_data(xaxis, *yaxis)
    plot_line(axes, data['xdata'], data['ydata'], None, *args, **kwargs)

    # Add labels
    self._set_axes(data['xlabel'], data['ylabel'])
    axes.set_xlabel(data['xlabel'])
    axes.set_title(data['title'])
    if len(yaxis) == 1:
        axes.set_ylabel(data['ylabel'])
    else:
        axes.legend(data['legend'])
    return axes

plot3d(xaxis='axes0', yaxis='axes1', zaxis='signal', axes=None, **kwargs)

Create matplotlib figure with 3D plot, for 2D grid scans

Parameters:

Name Type Description Default
xaxis str

str name or address of array to plot on x-axis

'axes0'
yaxis str

str name or address of array to plot on y-axis

'axes1'
zaxis str

str name or address of array to plot on z-axis

'signal'
axes Axes | None

matplotlib axes to plot on (None to create figure)

None
kwargs

given directly to plt.pcolormesh(..., args, *kwars)

{}

Returns:

Type Description
Axes3D

axes object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def plot3d(self, xaxis: str = 'axes0', yaxis: str = 'axes1', zaxis: str = 'signal',
           axes: plt.Axes | None = None, **kwargs) -> Axes3D:
    """
    Create matplotlib figure with 3D plot, for 2D grid scans

    :param xaxis: str name or address of array to plot on x-axis
    :param yaxis: str name or address of array to plot on y-axis
    :param zaxis: str name or address of array to plot on z-axis
    :param axes: matplotlib axes to plot on (None to create figure)
    :param axes: matplotlib.axes subplot, or None to create a figure
    :param kwargs: given directly to plt.pcolormesh(..., *args, **kwars)
    :return: axes object
    """
    if len(self.scan.map.scannables_shape()) != 2:
        raise ValueError(f"Scan {repr(self.scan)} has shape {self.scan.map.scannables_shape()} inconsistent with map2d")
    data = self.scan.get_plot_data(xaxis, yaxis, z_axis=zaxis)

    axes = new_plot('3d') if axes is None else axes
    lines = plot_3d_lines(
        axes=axes,
        xdata=data['grid_xdata'],
        ydata=data['grid_ydata'],
        zdata=data['grid_data'],
        **kwargs
    )
    axes.set_xlabel(data['grid_xlabel'])
    axes.set_ylabel(data['grid_ylabel'])
    axes.set_zlabel(data['grid_label'])
    axes.set_title(data['title'])
    self._set_axes(data['grid_xlabel'], data['grid_ylabel'], data['grid_label'])
    return axes

plotline(xaxis='axes', yaxis='signal', *args, axes, **kwargs)

Plot scanned datasets on matplotlib axes subplot

Parameters:

Name Type Description Default
xaxis str

str name or address of array to plot on x axis

'axes'
yaxis str

str name or address of array to plot on y axis

'signal'
args

given directly to plt.plot(..., args, *kwars)

()
axes Axes | None

matplotlib.axes subplot, or None to use plt.gca()

required
kwargs

given directly to plt.plot(..., args, *kwars)

{}

Returns:

Type Description
list[Line2D]

list lines object, output of plot

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def plotline(self, xaxis: str = 'axes', yaxis: str = 'signal',
             *args, axes: plt.Axes | None, **kwargs) -> list[plt.Line2D]:
    """
    Plot scanned datasets on matplotlib axes subplot

    :param xaxis: str name or address of array to plot on x axis
    :param yaxis: str name or address of array to plot on y axis
    :param args: given directly to plt.plot(..., *args, **kwars)
    :param axes: matplotlib.axes subplot, or None to use plt.gca()
    :param kwargs: given directly to plt.plot(..., *args, **kwars)
    :return: list lines object, output of plot
    """
    data = self.scan.get_plot_data(xaxis, yaxis)

    if 'label' not in kwargs:
        kwargs['label'] = self.scan.label()
    axes = new_plot() if axes is None else axes
    lines = plot_line(axes, data['x'], data['y'], None, *args, **kwargs)
    self._set_axes(data['xlabel'], data['ylabel'])
    return lines

roi(roi_name, **kwargs)

Create matplotlib figure with plot of a detector ROI and integrated area

Parameters:

Name Type Description Default
roi_name str

name of ROI to plot

required
kwargs

additional arguments for matplotlib.subplots

{}

Returns:

Type Description
Figure

matplotlib figure

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def roi(self, roi_name: str, **kwargs) -> plt.Figure:
    """
    Create matplotlib figure with plot of a detector ROI and integrated area
    :param roi_name: name of ROI to plot
    :param kwargs: additional arguments for matplotlib.subplots
    :return: matplotlib figure
    """
    if roi_name not in self.scan.rois(''):
        raise Exception(f'ROI "{roi_name}" not found in scan')

    axes_values, axes_name = self.scan.get_plot_axis('axes')
    roi_total = self.scan.eval(f"{roi_name}_total")
    roi_box = self.scan.eval(f"{roi_name}_box")
    if f"{roi_name}_pos" in self.scan.map.alternate_names:
        pi, pj, pk = self.scan.eval(f"{roi_name}_pos")
    else:
        pi = np.argmax(roi_total)
        pj, pk = np.mean(roi_box, axis=1)
    det_image = self.scan.image(pi)
    roi_image = self.scan.eval(f"{roi_name}[{pi}]")

    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, **kwargs)
    plot_image(ax1, det_image)
    ax1.plot(roi_box[:, 1], roi_box[:, 0], label=roi_name)
    detector = self.scan.replace_default_names('IMAGE')
    ax1.set_title(detector)

    plot_image(ax2, roi_image)
    ax2.plot([pk], [pj], '+', markersize=10, color='black')
    ax2.set_title(roi_name)

    ax3.plot(axes_values, roi_total, label=f"{roi_name}_total")
    ax3.set_xlabel(axes_name)
    ax3.set_ylabel(roi_name)
    fig.suptitle(self.scan.title())
    return fig

scananddetector(xaxis='axes', yaxis='signal', index=None, clim=None, cmap=DEFAULT_CMAP, **kwargs)

Create matplotlib figure with plot of the scan and detector image

Parameters:

Name Type Description Default
xaxis str

str name or address of array to plot on x axis

'axes'
yaxis str | list[str]

str name or address of array to plot on y axis, also accepts list of names for multiple plots

'signal'
index int | tuple | slice | None

int, detector image index, 0-length of scan, if None, use centre index

None
clim tuple[float, float] | None

[min, max] colormap cut-offs (None for auto)

None
cmap str

str colormap name (None for auto)

DEFAULT_CMAP
kwargs

given directly to plt.plot(..., args, *kwars)

{}

Returns:

Type Description
Figure

Figure object

Source code in mmg_toolbox/plotting/scan_plot_manager.py
def scananddetector(self, xaxis: str = 'axes', yaxis: str | list[str] = 'signal',
                    index: int | tuple | slice | None = None, clim: tuple[float, float] | None = None,
                    cmap: str = DEFAULT_CMAP, **kwargs) -> plt.Figure:
    """
    Create matplotlib figure with plot of the scan and detector image
    :param xaxis: str name or address of array to plot on x axis
    :param yaxis: str name or address of array to plot on y axis, also accepts list of names for multiple plots
    :param index: int, detector image index, 0-length of scan, if None, use centre index
    :param clim: [min, max] colormap cut-offs (None for auto)
    :param cmap: str colormap name (None for auto)
    :param kwargs: given directly to plt.plot(..., *args, **kwars)
    :return: Figure object
    """

    # Create figure
    fig, (lt, rt) = plt.subplots(1, 2, figsize=[FIG_SIZE[0] * 1.5, FIG_SIZE[1]], dpi=FIG_DPI)
    fig.subplots_adjust(hspace=0.35, left=0.1, right=0.95)

    # left - line plot
    self.plot(xaxis, yaxis, axes=lt, **kwargs)

    # right - image plot
    self.image(index, xaxis, cmap=cmap, clim=clim, axes=rt)
    return fig