forked from hyperspy/hyperspy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
executable file
·1895 lines (1613 loc) · 70.3 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2007-2023 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# HyperSpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with HyperSpy. If not, see <https://www.gnu.org/licenses/#GPL>.
import copy
from functools import partial
import itertools
import logging
from packaging.version import Version
import textwrap
import warnings
import dask.array as da
import traits.api as t
import numpy as np
import matplotlib as mpl
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.backend_bases import key_press_handler
from matplotlib.colors import LinearSegmentedColormap, BASE_COLORS, to_rgba
import matplotlib.pyplot as plt
from rsciio.utils import rgb_tools
import hyperspy.api as hs
from hyperspy.defaults_parser import preferences
from hyperspy.misc.utils import to_numpy
_logger = logging.getLogger(__name__)
def contrast_stretching(data, vmin=None, vmax=None):
"""Estimate bounds of the data to display.
Parameters
----------
data: numpy array
vmin, vmax: scalar, str, None
If str, formatted as 'xth', use this value to calculate the percentage
of pixels that are left out of the lower and upper bounds.
For example, for a vmin of '1th', 1% of the lowest will be ignored to
estimate the minimum value. Similarly, for a vmax value of '1th', 1%
of the highest value will be ignored in the estimation of the maximum
value. See :py:func:`numpy.percentile` for more explanation.
If None, use the percentiles value set in the preferences.
If float of integer, keep this value as bounds.
Returns
-------
vmin, vmax: scalar
The low and high bounds.
Raises
------
ValueError
if the value of `vmin` `vmax` is out of the valid range for percentile
calculation (in case of string values).
"""
if np.issubdtype(data.dtype, bool):
# in case of boolean, simply return 0, 1
return 0, 1
def _parse_value(value, value_name):
if value is None:
if value_name == "vmin":
value = "0th"
elif value_name == "vmax":
value = "100th"
if isinstance(value, str):
value = float(value.split("th")[0])
if not 0 <= value <= 100:
raise ValueError(f"{value_name} must be in the range[0, 100].")
return value
if np.ma.is_masked(data):
# If there is a mask, compressed the data to remove the masked data
data = np.ma.masked_less_equal(data, 0).compressed()
# If vmin, vmax are float or int, we keep the value, if not we calculate
# the precentile value
if not isinstance(vmin, (float, int)):
vmin = np.nanpercentile(data, _parse_value(vmin, 'vmin'))
if not isinstance(vmax, (float, int)):
vmax = np.nanpercentile(data, _parse_value(vmax, 'vmax'))
return vmin, vmax
MPL_DIVERGING_COLORMAPS = [
"BrBG",
"bwr",
"coolwarm",
"PiYG",
"PRGn",
"PuOr",
"RdBu",
"RdGy",
"RdYIBu",
"RdYIGn",
"seismic",
"Spectral", ]
# Add reversed colormaps
MPL_DIVERGING_COLORMAPS += [cmap + "_r" for cmap in MPL_DIVERGING_COLORMAPS]
def centre_colormap_values(vmin, vmax):
"""Calculate vmin and vmax to set the colormap midpoint to zero.
Parameters
----------
vmin, vmax : scalar
The range of data to display.
Returns
-------
cvmin, cvmax : scalar
The values to obtain a centre colormap.
"""
absmax = max(abs(vmin), abs(vmax))
return -absmax, absmax
def create_figure(window_title=None,
_on_figure_window_close=None,
disable_xyscale_keys=False,
**kwargs):
"""Create a matplotlib figure.
This function adds the possibility to execute another function
when the figure is closed and to easily set the window title. Any
keyword argument is passed to the plt.figure function.
Parameters
----------
window_title : None, string, optional
Default None.
_on_figure_window_close : None, function, optional
Default None.
disable_xyscale_keys : bool, optional
Disable the `k`, `l` and `L` shortcuts which toggle the x or y axis
between linear and log scale. Default False.
Returns
-------
fig : plt.figure
"""
fig = plt.figure(**kwargs)
if window_title is not None:
# remove non-alphanumeric characters to prevent file saving problems
# This is a workaround for:
# https://github.com/matplotlib/matplotlib/issues/9056
reserved_characters = r'<>"/\|?*'
for c in reserved_characters:
window_title = window_title.replace(c, '')
window_title = window_title.replace('\n', ' ')
window_title = window_title.replace(':', ' -')
fig.canvas.manager.set_window_title(window_title)
if disable_xyscale_keys and hasattr(fig.canvas, 'toolbar'):
# hack the `key_press_handler` to disable the `k`, `l`, `L` shortcuts
manager = fig.canvas.manager
fig.canvas.mpl_disconnect(manager.key_press_handler_id)
manager.key_press_handler_id = manager.canvas.mpl_connect(
'key_press_event',
lambda event: key_press_handler_custom(event, manager.canvas))
if _on_figure_window_close is not None:
on_figure_window_close(fig, _on_figure_window_close)
return fig
def key_press_handler_custom(event, canvas):
if event.key not in ['k', 'l', 'L']:
key_press_handler(event, canvas, canvas.manager.toolbar)
def on_figure_window_close(figure, function):
"""Connects a close figure signal to a given function.
Parameters
----------
figure : mpl figure instance
function : function
"""
def function_wrapper(evt):
function()
figure.canvas.mpl_connect('close_event', function_wrapper)
def plot_RGB_map(im_list, normalization='single', dont_plot=False):
"""Plot 2 or 3 maps in RGB.
Parameters
----------
im_list : list of Signal2D instances
normalization : 'single', 'global', optional
Default 'single'.
dont_plot : bool, optional
Default False.
Returns
-------
array: RGB matrix
"""
# from widgets import cursors
height, width = im_list[0].data.shape[:2]
rgb = np.zeros((height, width, 3))
rgb[:, :, 0] = im_list[0].data.squeeze()
rgb[:, :, 1] = im_list[1].data.squeeze()
if len(im_list) == 3:
rgb[:, :, 2] = im_list[2].data.squeeze()
if normalization == 'single':
for i in range(len(im_list)):
rgb[:, :, i] /= rgb[:, :, i].max()
elif normalization == 'global':
rgb /= rgb.max()
rgb = rgb.clip(0, rgb.max())
if not dont_plot:
figure = plt.figure()
ax = figure.add_subplot(111)
ax.frameon = False
ax.set_axis_off()
ax.imshow(rgb, interpolation='nearest')
# cursors.set_mpl_ax(ax)
figure.canvas.draw_idle()
else:
return rgb
def subplot_parameters(fig):
"""Returns a list of the subplot parameters of a mpl figure.
Parameters
----------
fig : mpl figure
Returns
-------
tuple : (left, bottom, right, top, wspace, hspace)
"""
wspace = fig.subplotpars.wspace
hspace = fig.subplotpars.hspace
left = fig.subplotpars.left
right = fig.subplotpars.right
top = fig.subplotpars.top
bottom = fig.subplotpars.bottom
return left, bottom, right, top, wspace, hspace
class ColorCycle:
_color_cycle = [mpl.colors.colorConverter.to_rgba(color) for color
in ('b', 'g', 'r', 'c', 'm', 'y', 'k')]
def __init__(self):
self.color_cycle = copy.copy(self._color_cycle)
def __call__(self):
if not self.color_cycle:
self.color_cycle = copy.copy(self._color_cycle)
return self.color_cycle.pop(0)
def plot_signals(signal_list, sync=True, navigator="auto",
navigator_list=None, **kwargs):
"""Plot several signals at the same time.
Parameters
----------
signal_list : list of BaseSignal instances
If sync is set to True, the signals must have the
same navigation shape, but not necessarily the same signal shape.
sync : True, False, optional
If True (default), the signals will share navigation. All the signals
must have the same navigation shape for this to work, but not
necessarily the same signal shape.
navigator : 'auto', None, 'spectrum', 'slider', BaseSignal, optional
Default 'auto'. See signal.plot docstring for full description.
navigator_list : None, list of navigator arguments, optional
Set different navigator options for the signals. Must use valid
navigator arguments: 'auto', None, 'spectrum', 'slider', or a
HyperSpy Signal. The list must have the same size as signal_list.
If None (default), the argument specified in navigator will be used.
**kwargs
Any extra keyword arguments are passed to each signal `plot` method.
Example
-------
>>> s_cl = hs.load("coreloss.dm3")
>>> s_ll = hs.load("lowloss.dm3")
>>> hs.plot.plot_signals([s_cl, s_ll])
Specifying the navigator:
>>> s_cl = hs.load("coreloss.dm3")
>>> s_ll = hs.load("lowloss.dm3")
>>> hs.plot.plot_signals([s_cl, s_ll], navigator="slider")
Specifying the navigator for each signal:
>>> s_cl = hs.load("coreloss.dm3")
>>> s_ll = hs.load("lowloss.dm3")
>>> s_edx = hs.load("edx.dm3")
>>> s_adf = hs.load("adf.dm3")
>>> hs.plot.plot_signals(
[s_cl, s_ll, s_edx], navigator_list=["slider",None,s_adf])
"""
from hyperspy.signal import BaseSignal
if navigator_list:
if not (len(signal_list) == len(navigator_list)):
raise ValueError(
"signal_list and navigator_list must"
" have the same size")
if sync:
axes_manager_list = []
for signal in signal_list:
axes_manager_list.append(signal.axes_manager)
if not navigator_list:
navigator_list = []
if navigator is None:
navigator_list.extend([None] * len(signal_list))
elif isinstance(navigator, BaseSignal):
navigator_list.append(navigator)
navigator_list.extend([None] * (len(signal_list) - 1))
elif navigator == "slider":
navigator_list.append("slider")
navigator_list.extend([None] * (len(signal_list) - 1))
elif navigator == "spectrum":
navigator_list.extend(["spectrum"] * len(signal_list))
elif navigator == "auto":
navigator_list.extend(["auto"] * len(signal_list))
else:
raise ValueError(
"navigator must be one of \"spectrum\",\"auto\","
" \"slider\", None, a Signal instance")
# Check to see if the spectra have the same navigational shapes
temp_shape_first = axes_manager_list[0].navigation_shape
for i, axes_manager in enumerate(axes_manager_list):
temp_shape = axes_manager.navigation_shape
if not (temp_shape_first == temp_shape):
raise ValueError(
"The spectra do not have the same navigation shape")
axes_manager_list[i] = axes_manager.deepcopy()
if i > 0:
for axis0, axisn in zip(axes_manager_list[0].navigation_axes,
axes_manager_list[i].navigation_axes):
axes_manager_list[i]._axes[axisn.index_in_array] = axis0
del axes_manager
for signal, navigator, axes_manager in zip(signal_list,
navigator_list,
axes_manager_list):
signal.plot(axes_manager=axes_manager,
navigator=navigator,
**kwargs)
# If sync is False
else:
if not navigator_list:
navigator_list = []
navigator_list.extend([navigator] * len(signal_list))
for signal, navigator in zip(signal_list, navigator_list):
signal.plot(navigator=navigator,
**kwargs)
def _make_heatmap_subplot(spectra, **plot_kwargs):
from hyperspy._signals.signal2d import Signal2D
im = Signal2D(spectra.data, axes=spectra.axes_manager._get_axes_dicts())
im.metadata.General.title = spectra.metadata.General.title
im.plot(**plot_kwargs)
return im._plot.signal_plot.ax
def set_xaxis_lims(mpl_ax, hs_axis):
"""
Set the matplotlib axis limits to match that of a HyperSpy axis.
Parameters
----------
mpl_ax : :class:`matplotlib.axis.Axis`
The ``matplotlib`` axis to change.
hs_axis : :class:`~hyperspy.axes.DataAxis`
The data axis that contains the values which control the scaling.
"""
x_axis_lower_lim = hs_axis.axis[0]
x_axis_upper_lim = hs_axis.axis[-1]
mpl_ax.set_xlim(x_axis_lower_lim, x_axis_upper_lim)
def _make_overlap_plot(spectra, ax, color, linestyle, **kwargs):
for spectrum_index, (spectrum, color, linestyle) in enumerate(
zip(spectra, color, linestyle)):
x_axis = spectrum.axes_manager.signal_axes[0]
spectrum = _transpose_if_required(spectrum, 1)
ax.plot(x_axis.axis, _parse_array(spectrum), color=color,ls=linestyle,
**kwargs)
set_xaxis_lims(ax, x_axis)
_set_spectrum_xlabel(spectra, ax)
ax.set_ylabel('Intensity')
ax.autoscale(tight=True)
def _make_cascade_subplot(spectra, ax, color, linestyle, padding=1, **kwargs):
max_value = 0
for spectrum in spectra:
spectrum_yrange = (np.nanmax(spectrum.data) -
np.nanmin(spectrum.data))
if spectrum_yrange > max_value:
max_value = spectrum_yrange
for i, (spectrum, color, linestyle) in enumerate(
zip(spectra, color, linestyle)):
x_axis = spectrum.axes_manager.signal_axes[0]
data = _parse_array(_transpose_if_required(spectrum, 1))
data_to_plot = (data - data.min()) / float(max_value) + i * padding
ax.plot(x_axis.axis, data_to_plot, color=color, ls=linestyle,
**kwargs)
set_xaxis_lims(ax, x_axis)
_set_spectrum_xlabel(spectra, ax)
ax.set_yticks([])
ax.autoscale(tight=True)
def _plot_spectrum(spectrum, ax, color="blue", linestyle='-', **kwargs):
x_axis = spectrum.axes_manager.signal_axes[0]
ax.plot(x_axis.axis, _parse_array(spectrum), color=color, ls=linestyle,
**kwargs)
set_xaxis_lims(ax, x_axis)
def _set_spectrum_xlabel(spectrum, ax):
s = spectrum[-1] if isinstance(spectrum, (list, tuple)) else spectrum
x_axis = s.axes_manager.signal_axes[0]
ax.set_xlabel("%s (%s)" % (x_axis.name, x_axis.units))
def _transpose_if_required(signal, expected_dimension):
# EDS profiles or maps have signal dimension = 0 and navigation dimension
# 1 or 2. For convenience, transpose the signal if possible
if (signal.axes_manager.signal_dimension == 0 and
signal.axes_manager.navigation_dimension == expected_dimension):
return signal.T
else:
return signal
def _parse_array(signal):
"""Convenience function to parse array from a signal."""
data = signal.data
if isinstance(data, da.Array):
data = data.compute()
return to_numpy(data)
def plot_images(images,
cmap=None,
no_nans=False,
per_row=3,
label='auto',
labelwrap=30,
suptitle=None,
suptitle_fontsize=18,
colorbar='default',
centre_colormap='auto',
scalebar=None,
scalebar_color='white',
axes_decor='all',
padding=None,
tight_layout=False,
aspect='auto',
min_asp=0.1,
namefrac_thresh=0.4,
fig=None,
vmin=None,
vmax=None,
overlay=False,
colors='auto',
alphas=1.0,
legend_picking=True,
legend_loc='upper right',
pixel_size_factor=None,
**kwargs):
"""Plot multiple images either as sub-images or overlayed in one figure.
Parameters
----------
images : list of Signal2D or BaseSignal
`images` should be a list of Signals to plot. For `BaseSignal` with
navigation dimensions 2 and signal dimension 0, the signal will be
transposed to form a `Signal2D`.
Multi-dimensional images will have each plane plotted as a separate
image.
If any of the signal shapes is not suitable, a ValueError will be
raised.
cmap : matplotlib colormap, list, 'mpl_colors', optional
The colormap used for the images, by default uses the setting
``color map signal`` from the plot preferences. A list of colormaps can
also be provided, and the images will cycle through them. Optionally,
the value ``'mpl_colors'`` will cause the cmap to loop through the
default ``matplotlib`` colors (to match with the default output of the
:py:func:`~.drawing.utils.plot_spectra` method).
Note: if using more than one colormap, using the ``'single'``
option for ``colorbar`` is disallowed.
no_nans : bool, optional
If True, set nans to zero for plotting.
per_row : int, optional
The number of plots in each row.
label : None, str, list of str, optional
Control the title labeling of the plotted images.
If None, no titles will be shown.
If 'auto' (default), function will try to determine suitable titles
using Signal2D titles, falling back to the 'titles' option if no good
short titles are detected.
Works best if all images to be plotted have the same beginning
to their titles.
If 'titles', the title from each image's `metadata.General.title`
will be used.
If any other single str, images will be labeled in sequence using
that str as a prefix.
If a list of str, the list elements will be used to determine the
labels (repeated, if necessary).
labelwrap : int, optional
Integer specifying the number of characters that will be used on
one line.
If the function returns an unexpected blank figure, lower this
value to reduce overlap of the labels between figures.
suptitle : str, optional
Title to use at the top of the figure. If called with label='auto',
this parameter will override the automatically determined title.
suptitle_fontsize : int, optional
Font size to use for super title at top of figure.
colorbar : 'default', 'multi', 'single', None, optional
Controls the type of colorbars that are plotted, incompatible with
``overlay=True``.
If 'default', same as 'multi' when ``overlay=False``, otherwise same
as ``None``.
If 'multi', individual colorbars are plotted for each (non-RGB) image.
If 'single', all (non-RGB) images are plotted on the same scale,
and one colorbar is shown for all.
If None, no colorbar is plotted.
centre_colormap : 'auto', True, False, optional
If True, the centre of the color scheme is set to zero. This is
particularly useful when using diverging color schemes. If 'auto'
(default), diverging color schemes are automatically centred.
scalebar : None, 'all', list of ints, optional
If None (or False), no scalebars will be added to the images.
If 'all', scalebars will be added to all images.
If list of ints, scalebars will be added to each image specified.
scalebar_color : str, optional
A valid MPL color string; will be used as the scalebar color.
axes_decor : 'all', 'ticks', 'off', None, optional
Controls how the axes are displayed on each image; default is 'all'.
If 'all', both ticks and axis labels will be shown.
If 'ticks', no axis labels will be shown, but ticks/labels will.
If 'off', all decorations and frame will be disabled.
If None, no axis decorations will be shown, but ticks/frame will.
padding : None, dict, optional
This parameter controls the spacing between images.
If None, default options will be used.
Otherwise, supply a dictionary with the spacing options as
keywords and desired values as values.
Values should be supplied as used in
:py:func:`matplotlib.pyplot.subplots_adjust`,
and can be 'left', 'bottom', 'right', 'top', 'wspace' (width) and
'hspace' (height).
tight_layout : bool, optional
If true, hyperspy will attempt to improve image placement in
figure using matplotlib's tight_layout.
If false, repositioning images inside the figure will be left as
an exercise for the user.
aspect : str, float, int, optional
If 'auto', aspect ratio is auto determined, subject to min_asp.
If 'square', image will be forced onto square display.
If 'equal', aspect ratio of 1 will be enforced.
If float (or int/long), given value will be used.
min_asp : float, optional
Minimum aspect ratio to be used when plotting images.
namefrac_thresh : float, optional
Threshold to use for auto-labeling. This parameter controls how
much of the titles must be the same for the auto-shortening of
labels to activate. Can vary from 0 to 1. Smaller values
encourage shortening of titles by auto-labeling, while larger
values will require more overlap in titles before activing the
auto-label code.
fig : mpl figure, optional
If set, the images will be plotted to an existing matplotlib figure.
vmin, vmax: scalar, str, None
If str, formatted as 'xth', use this value to calculate the percentage
of pixels that are left out of the lower and upper bounds.
For example, for a vmin of '1th', 1% of the lowest will be ignored to
estimate the minimum value. Similarly, for a vmax value of '1th', 1%
of the highest value will be ignored in the estimation of the maximum
value. It must be in the range [0, 100].
See :py:func:`numpy.percentile` for more explanation.
If None, use the percentiles value set in the preferences.
If float or integer, keep this value as bounds.
Note: vmin is ignored when overlaying images.
overlay : bool, optional
If True, overlays the images with different colors rather than plotting
each image as a subplot.
colors : 'auto', list of char, list of hex str, optional
If list, it must contains colors acceptable to matplotlib [1]_.
If ``'auto'``, colors will be taken from matplotlib.colors.BASE_COLORS.
alphas : float or list of floats, optional
Float value or a list of floats corresponding to the alpha value of
each color.
legend_picking: bool, optional
If True (default), an image can be toggled on and off by clicking on
the legended line. For ``overlay=True`` only.
legend_loc : str, int, optional
This parameter controls where the legend is placed on the figure
see the :py:func:`matplotlib.pyplot.legend` docstring for valid values
pixel_size_factor : None, int or float, optional
If ``None`` (default), the size of the figure is taken from the
matplotlib ``rcParams``. Otherwise sets the size of the figure when
plotting an overlay image. The higher the number the larger the figure
and therefore a greater number of pixels are used. This value will be
ignored if a Figure is provided.
**kwargs, optional
Additional keyword arguments passed to :py:func:`matplotlib.pyplot.imshow`.
Returns
-------
axes_list : list
A list of subplot axes that hold the images.
See Also
--------
plot_spectra : Plotting of multiple spectra
plot_signals : Plotting of multiple signals
plot_histograms : Compare signal histograms
References
----------
.. [1] Matplotlib colors API: https://matplotlib.org/stable/api/colors_api.html.
Notes
-----
`interpolation` is a useful parameter to provide as a keyword
argument to control how the space between pixels is interpolated. A
value of ``'nearest'`` will cause no interpolation between pixels.
`tight_layout` is known to be quite brittle, so an option is provided
to disable it. Turn this option off if output is not as expected,
or try adjusting `label`, `labelwrap`, or `per_row`.
"""
def __check_single_colorbar(cbar):
if cbar == 'single':
raise ValueError('Cannot use a single colorbar with multiple '
'colormaps. Please check for compatible '
'arguments.')
from hyperspy.drawing.widgets import ScaleBar
from hyperspy.signal import BaseSignal
# Check that we have a hyperspy signal
im = [images] if not isinstance(images, (list, tuple)) else images
for image in im:
if not isinstance(image, BaseSignal):
raise ValueError("`images` must be a list of image signals or a "
"multi-dimensional signal. "
f"{repr(type(images))} was given.")
# For list of EDS maps, transpose the BaseSignal
if isinstance(images, (list, tuple)):
images = [_transpose_if_required(image, 2) for image in images]
# If input is >= 1D signal (e.g. for multi-dimensional plotting),
# copy it and put it in a list so labeling works out as (x,y) when plotting
if isinstance(images,
BaseSignal) and images.axes_manager.navigation_dimension > 0:
images = [images._deepcopy_with_new_data(images.data)]
n = 0
for i, sig in enumerate(images):
if sig.axes_manager.signal_dimension != 2:
raise ValueError("This method only plots signals that are images. "
"The signal dimension must be equal to 2. "
"The signal at position " + repr(i) +
" was " + repr(sig) + ".")
# increment n by the navigation size, or by 1 if the navigation size is
# <= 0
n += (sig.axes_manager.navigation_size
if sig.axes_manager.navigation_size > 0
else 1)
# Check compatibility of colorbar and overlay arguments
if overlay and colorbar != 'default':
_logger.info(f"`colorbar='{colorbar}'` is incompatible with "
"`overlay=True`. Colorbar is disable.")
colorbar = None
# Setting the default value
elif colorbar == 'default':
colorbar = 'multi'
# If no cmap given, get default colormap from pyplot:
if cmap is None:
cmap = [preferences.Plot.cmap_signal]
elif cmap == 'mpl_colors':
cycle = mpl.rcParams['axes.prop_cycle']
for n_color, c in enumerate(cycle):
name = f'mpl{n_color}'
if name not in plt.colormaps():
make_cmap(colors=['#000000', c['color']], name=name)
cmap = [f'mpl{i}' for i in range(len(cycle))]
__check_single_colorbar(colorbar)
# cmap is list, tuple, or something else iterable (but not string):
elif hasattr(cmap, '__iter__') and not isinstance(cmap, str):
try:
cmap = [c.name for c in cmap] # convert colormap to string
except AttributeError:
cmap = [c for c in cmap] # c should be string if not colormap
__check_single_colorbar(colorbar)
elif isinstance(cmap, mpl.colors.Colormap):
cmap = [cmap.name] # convert single colormap to list with string
elif isinstance(cmap, str):
cmap = [cmap] # cmap is single string, so make it a list
else:
# Didn't understand cmap input, so raise error
raise ValueError('The provided cmap value was not understood. Please '
'check input values.')
# If any of the cmaps given are diverging, and auto-centering, set the
# appropriate flag:
if centre_colormap == "auto":
centre_colormaps = []
for c in cmap:
if c in MPL_DIVERGING_COLORMAPS:
centre_colormaps.append(True)
else:
centre_colormaps.append(False)
# if it was True, just convert to list
elif centre_colormap:
centre_colormaps = [True]
# likewise for false
elif not centre_colormap:
centre_colormaps = [False]
# finally, convert lists to cycle generators for adaptive length:
centre_colormaps = itertools.cycle(centre_colormaps)
cmap = itertools.cycle(cmap)
# Sort out the labeling:
div_num = 0
all_match = False
shared_titles = False
user_labels = False
if label is None:
pass
elif label == 'auto':
# Use some heuristics to try to get base string of similar titles
label_list = [x.metadata.General.title for x in images]
# Find the shortest common string between the image titles
# and pull that out as the base title for the sequence of images
# array in which to store arrays
res = np.zeros((len(label_list), len(label_list[0]) + 1))
res[:, 0] = 1
# j iterates the strings
for j in range(len(label_list)):
# i iterates length of substring test
for i in range(1, len(label_list[0]) + 1):
# stores whether or not characters in title match
res[j, i] = label_list[0][:i] in label_list[j]
# sum up the results (1 is True, 0 is False) and create
# a substring based on the minimum value (this will be
# the "smallest common string" between all the titles
if res.all():
basename = label_list[0]
div_num = len(label_list[0])
all_match = True
else:
div_num = int(min(np.sum(res, 1)))
basename = label_list[0][:div_num - 1]
all_match = False
# trim off any '(' or ' ' characters at end of basename
if div_num > 1:
basename = basename.strip()
if len(basename) > 1 and basename[len(basename) - 1] == '(':
basename = basename[:-1]
# namefrac is ratio of length of basename to the image name
# if it is high (e.g. over 0.5), we can assume that all images
# share the same base
if len(label_list[0]) > 0:
namefrac = float(len(basename)) / len(label_list[0])
else:
# If label_list[0] is empty, it means there was probably no
# title set originally, so nothing to share
namefrac = 0
if namefrac > namefrac_thresh:
# there was a significant overlap of label beginnings
shared_titles = True
# only use new suptitle if one isn't specified already
if suptitle is None:
suptitle = basename
else:
# there was not much overlap, so default back to 'titles' mode
shared_titles = False
label = 'titles'
div_num = 0
elif label == 'titles':
# Set label_list to each image's pre-defined title
label_list = [x.metadata.General.title for x in images]
elif isinstance(label, str):
# Set label_list to an indexed list, based off of label
label_list = [f"{label} {num}" for num in range(n)]
elif isinstance(label, list) and all(
isinstance(x, str) for x in label):
label_list = label
user_labels = True
# If list of labels is longer than the number of images, just use the
# first n elements
if len(label_list) > n:
del label_list[n:]
if len(label_list) < n:
label_list *= (n // len(label_list)) + 1
del label_list[n:]
else:
raise ValueError("Did not understand input of labels.")
# Check if we need to add a scalebar for some of the images
if isinstance(scalebar, (list, tuple)) and all(isinstance(x, int)
for x in scalebar):
scalelist = True
else:
scalelist = False
if scalebar not in [None, False, 'all'] and scalelist is False:
raise ValueError("Did not understand scalebar input. Must be None, "
"'all', or list of ints.")
# Determine appropriate number of images per row
if overlay:
# only a single image
per_row = rows = 1
else:
rows = int(np.ceil(n / float(per_row)))
if n < per_row:
per_row = n
# Set overall figure size and define figure (if not pre-existing)
if fig is None:
w, h = plt.rcParams['figure.figsize']
dpi = plt.rcParams['figure.dpi']
if overlay and axes_decor == 'off':
shape = images[0].axes_manager.signal_shape
if pixel_size_factor is None:
# Cap the maximum dimension of figure to
# plt.rcParams['figure.figsize']
aspect_ratio = shape[0] / shape[1]
if aspect_ratio >= w / h:
if label is not None and w / aspect_ratio < 1.0:
# Needs enough space for the labels
w = 1.0 * aspect_ratio
figsize = (w, w / aspect_ratio)
else:
if scalebar is not None and h * aspect_ratio < 2.0:
# Needs enough width for the scalebar
h = 2.0 / aspect_ratio
figsize = (h * aspect_ratio, h)
else:
figsize = [pixel_size_factor*v/dpi for v in shape]
else:
k = max(w, h) / max(per_row, rows)
figsize=[k * i for i in (per_row, rows)]
f = plt.figure(figsize=figsize, dpi=dpi)
else:
f = fig
# Initialize list to hold subplot axes
axes_list = []
# Initialize list of rgb tags
isrgb = [False] * len(images)
# Check to see if there are any rgb images in list
# and tag them using the isrgb list
for i, img in enumerate(images):
if rgb_tools.is_rgbx(img.data):
isrgb[i] = True
# Determine how many non-rgb images there are
non_rgb = list(itertools.compress(images, [not j for j in isrgb]))
if len(non_rgb) == 0 and colorbar is not None:
colorbar = None
warnings.warn("Sorry, colorbar is not implemented for RGB images.")
def check_list_length(arg, arg_name):
if isinstance(arg, (list, tuple)):
if len(arg) != n:
_logger.warning(f'The provided {arg_name} values are ignored '
'because the length of the list does not '
'match the number of images')
arg = [None] * n
return arg
# Find global min and max values of all the non-rgb images for use with
# 'single' scalebar, otherwise define this value later.
if colorbar == 'single':
# check that vmin and vmax are not list
if any([isinstance(v, (tuple, list)) for v in [vmin, vmax]]):
_logger.warning('The provided vmin or vmax value are ignored '
'because it needs to be a scalar or a str '
'to be compatible with a single colorbar. '
'The default values are used instead.')
vmin, vmax = None, None
vmin_max = np.array(
[contrast_stretching(_parse_array(i), vmin, vmax) for i in non_rgb])
_vmin, _vmax = vmin_max[:, 0].min(), vmin_max[:, 1].max()
if next(centre_colormaps):
_vmin, _vmax = centre_colormap_values(_vmin, _vmax)
else:
vmin = check_list_length(vmin, "vmin")
vmax = check_list_length(vmax, "vmax")
idx = 0
ax_im_list = [0] * len(isrgb)
# Replot: create a list to store references to the images
replot_ims = []
def transparent_single_color_cmap(color):
""" Return a single color matplotlib cmap with the transparency increasing
linearly from 0 to 1."""
return LinearSegmentedColormap.from_list("", [to_rgba(color, 0), to_rgba(color, 1)])
#Below is for overlayed images
if overlay:
#Check if images all have same scale and therefore can be overlayed.
for im in images:
if (im.axes_manager[0].scale !=
images[0].axes_manager[0].scale):
raise ValueError("Images are not the same scale and so should"
"not be overlayed.")
if vmin is not None:
_logger.warning('`vmin` is ignored when overlaying images.')
import matplotlib.patches as mpatches
factor = plt.rcParams['font.size'] / 100
if not suptitle and axes_decor == 'off':
ax = f.add_axes([0, 0, 1, 1])
else:
ax = f.add_subplot()
patches = []
#If no colors are selected use BASE_COLORS
if colors == 'auto':
colors = []
for i in range(len(images)):
colors.append(list(BASE_COLORS)[i])
#If no alphas are selected use 1.0
if isinstance(alphas, float):
alphas_list = []
for i in range(len(images)):
alphas_list.append(alphas)