Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plot overlay images #2599

Merged
merged 9 commits into from Dec 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
55 changes: 34 additions & 21 deletions hyperspy/drawing/utils.py
Expand Up @@ -492,9 +492,8 @@ def plot_images(images,
vmax=None,
overlay=False,
overlay_title=None,
colors=[],
alphas=[],
legend='auto',
colors='auto',
alphas=1.0,
legend_picking=True,
legend_loc='upper right',
**kwargs):
Expand Down Expand Up @@ -609,7 +608,7 @@ def plot_images(images,
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 of integer, keep this value as bounds.
If float or integer, keep this value as bounds.
overlay : boolean, optional
If True, overlays the images with different colors rather than plotting
each image as a subplot.
Expand All @@ -620,13 +619,10 @@ def plot_images(images,
`colors` should be a list compromising either characters or hex
strings, corresponding to colors acceptable to matplotlib. Details
can be found at https://matplotlib.org/2.0.2/api/colors_api.html.
alphas : list of floats, optional
`alphas` should be a list of floats corresponding to the alpha
value of each color.
legend: {None, list of str, 'auto'}, optional
If list of string, legend for "cascade" or title for "mosaic" is
displayed. If 'auto', the title of each spectra (metadata.General.title)
is used.
If 'auto', colors will be taken from matplotlib.colors.BASE_COLORS.
alphas : float or list of floats, optional
`alphas` should be a single float value or a list of floats
corresponding to the alpha value of each color.
legend_picking: bool, optional
If True (default), a spectrum can be toggled on and off by clicking on
the legended line.
Expand Down Expand Up @@ -848,7 +844,13 @@ def __check_single_colorbar(cbar):
# Set overall figure size and define figure (if not pre-existing)
if fig is None:
k = max(plt.rcParams['figure.figsize']) / max(per_row, rows)
f = plt.figure(figsize=(tuple(k * i for i in (per_row, rows))))
if overlay:
shape = images[0].data.shape
dpi = 100
sampling_factor = 10
ericpre marked this conversation as resolved.
Show resolved Hide resolved
f = plt.figure(figsize=[sampling_factor*v/dpi for v in shape], dpi=dpi)
else:
f = plt.figure(figsize=(tuple(k * i for i in (per_row, rows))))
else:
f = fig

Expand Down Expand Up @@ -925,32 +927,45 @@ def check_list_length(arg, arg_name):
original_cmap = plt.rcParams['image.cmap']
plt.rcParams['image.cmap'] = 'gray'
import matplotlib.patches as mpatches
ax = f.add_subplot(1, 1, 1)
ax = f.add_axes([0, 0, 1, 1])
patches = []

#If no colors are selected use BASE_COLORS
if 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 alphas == []:
if isinstance(alphas, float):
alphas_list = []
for i in range(len(images)):
alphas.append(1.0)
alphas_list.append(alphas)
alphas=alphas_list

ax.imshow(np.zeros_like(images[0].data))
ericpre marked this conversation as resolved.
Show resolved Hide resolved

#Loop through each image
for i, im in enumerate(images):

#Set vmin and vmax
centre = next(centre_colormaps) # get next value for centreing
data = im.data
_vmin = vmin[idx] if isinstance(vmin, (tuple, list)) else vmin
_vmax = vmax[idx] if isinstance(vmax, (tuple, list)) else vmax
_vmin, _vmax = contrast_stretching(data, _vmin, _vmax)
if centre:
_vmin, _vmax = centre_colormap_values(_vmin, _vmax)
ericpre marked this conversation as resolved.
Show resolved Hide resolved

cols = ['k', colors[i]]
cmap=LinearSegmentedColormap.from_list('cmap'+str(i), cols)
my_cmap = cmap(np.arange(cmap.N))
my_cmap[:,-1] = np.linspace(0.3, 1, cmap.N)
my_cmap = ListedColormap(my_cmap)
ax.imshow(im.data, vmin=im.data.min(), vmax=im.data.max(),
ax.imshow(im.data, vmin=_vmin, vmax=_vmax,
cmap=my_cmap, alpha=alphas[i], **kwargs)

if legend is not None:
if label is not None:
if shared_titles:
legend_label = label_list[i][div_num - 1:]
else:
Expand All @@ -959,13 +974,11 @@ def check_list_length(arg, arg_name):
patches.append(mpatches.Patch(color=colors[i],
label=legend_label))

if legend is not None:
if label is not None:
plt.legend(handles=patches, loc=legend_loc)
if legend_picking is True:
animate_legend(fig=f, ax=ax, plot_type='images')

if axes_decor == 'off':
ax.margins=(0,0)
set_axes_decor(ax, axes_decor)

if not overlay_title:
Expand Down
Binary file modified hyperspy/tests/drawing/plot_signal2d/test_plot_overlay.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions hyperspy/tests/drawing/test_plot_signal2d.py
Expand Up @@ -567,7 +567,7 @@ def test_plot_autoscale_data_changed(autoscale):
def test_plot_overlay():
s1 = hs.signals.Signal2D(np.arange(100).reshape(10, 10))
s2 = hs.signals.Signal2D(np.arange(99,-1,-1).reshape(10, 10))
ax = hs.plot.plot_images([s1,s2], overlay=True, colors=['r','b'],
alphas=[0.9,0.9], scalebar='all', label=['r','b'])
ax = hs.plot.plot_images([s1,s2], overlay=True, scalebar='all',
label=['b','g'])

return ax[0].figure