visualize
show
- py4DSTEM.visualize.show(ar, figsize=(5, 5), cmap='gray', scaling='none', intensity_range='ordered', clipvals=None, vmin=None, vmax=None, min=None, max=None, power=None, power_offset=True, combine_images=False, ticks=True, bordercolor=None, borderwidth=5, show_image=True, return_ar_scaled=False, return_intensity_range=False, returncax=False, returnfig=False, figax=None, hist=False, n_bins=256, mask=None, mask_color='k', mask_alpha=0.0, masked_intensity_range=False, rectangle=None, circle=None, annulus=None, ellipse=None, points=None, grid_overlay=None, cartesian_grid=None, polarelliptical_grid=None, rtheta_grid=None, scalebar=None, calibration=None, rx=None, ry=None, space='Q', pixelsize=None, pixelunits=None, x0=None, y0=None, a=None, e=None, theta=None, title=None, show_fft=False, show_cbar=False, **kwargs)
General visualization function for 2D arrays.
The simplest use of this function is:
>>> show(ar)
which will generate and display a matplotlib figure showing the 2D array
ar
. Additional functionality includes:scaling the image (log scaling, power law scaling)
displaying the image histogram
altering the histogram clip values
masking some subset of the image
setting the colormap
adding geometric overlays (e.g. points, circles, rectangles, annuli)
adding informational overlays (scalebars, coordinate grids, oriented axes or vectors)
further customization tools
These are each discussed in turn below.
- Scaling:
Setting the parameter
scaling
will scale the display image. Options are ‘none’, ‘auto’, ‘power’, or ‘log’. If ‘power’ is specified, the parameterpower
must also be passed. The underlying data is not altered. Values less than or equal to zero are set to zero. If the image histogram is displayed usinghist=True
, the scaled image histogram is shown.Examples:
>>> show(ar,scaling='log') >>> show(ar,power=0.5) >>> show(ar,scaling='power',power=0.5,hist=True)
- Histogram:
Setting the argument
hist=True
will display the image histogram, instead of the image. The displayed histogram will reflect any scaling requested. The number of bins can be set withn_bins
. The upper and lower clip values, indicating where the image display will be saturated, are shown with dashed lines.- Intensity range:
Controlling the lower and upper values at which the display image will be saturated is accomplished with the
intensity_range
parameter, or its (soon deprecated) aliasclipvals
, in combination withvmin
, andvmax
. The method by which the upper and lower clip values are determined is controlled byintensity_range
, and must be a string in (‘None’,’ordered’,’minmax’,’absolute’,’std’,’centered’). See the argument description forintensity_range
for a description of the behavior for each. The clip values can be returned with thereturn_intensity_range
parameter.- Masking:
If a numpy masked array is passed to show, the function will automatically mask the appropriate pixels. Alternatively, a boolean array of the same shape as the data array may be passed to the
mask
argument, and these pixels will be masked. Masked pixels are displayed as a single uniform color, black by default, and which can be specified with themask_color
argument. Masked pixels are excluded when displaying the histogram or computing clip values. The mask can also be blended with the hidden data by setting themask_alpha
argument.- Overlays (geometric):
The function natively supports overlaying points, circles, rectangles, annuli, and ellipses. Each is invoked by passing a dictionary to the appropriate input variable specifying the geometry and features of the requested overlay. For example:
>>> show(ar, rectangle={'lims':(10,20,10,20),'color':'r'})
will overlay a single red square, and
>>> show(ar, annulus={'center':[(28,68),(92,160)], 'radii':[(16,24),(12,36)], 'fill':True, 'alpha':[0.9,0.3], 'color':['r',(0,1,1,1)]})
will overlay two annuli with two different centers, radii, colors, and transparencies. For a description of the accepted dictionary parameters for each type of overlay, see the visualize functions add_*, where * = (‘rectangle’,’circle’,’annulus’,’ellipse’,’points’). (These docstrings are under construction!)
- Overlays (informational):
Informational overlays supported by this function include coordinate axes (cartesian, polar-elliptical, or r-theta) and scalebars. These are added by passing the appropriate input argument a dictionary of the desired parameters, as with geometric overlays. However, there are two key differences between these overlays and the geometric overlays. First, informational overlays (coordinate systems and scalebars) require information about the plot - e.g. the position of the origin, the pixel sizes, the pixel units, any elliptical distortions, etc. The easiest way to pass this information is by pass a Calibration object containing this info to
show
as the keywordcalibration
. Second, once the coordinate information has been passed, informational overlays can autoselect their own parameters, thus simply passing an empty dict to one of these parameters will add that overlay.For example:
>>> show(dp, scalebar={}, calibration=calibration)
will display the diffraction pattern
dp
with a scalebar overlaid in the bottom left corner given the pixel size and units described incalibration
, and>>> show(dp, calibration=calibration, scalebar={'length':0.5,'width':2, 'position':'ul','label':True'})
will display a more customized scalebar.
When overlaying coordinate grids, it is important to note that some relevant parameters, e.g. the position of the origin, may change by scan position. In these cases, the parameters
rx
,``ry`` must also be passed toshow
, to tell theCalibration
object where to look for the relevant parameters. For example:>>> show(dp, cartesian_grid={}, calibration=calibration, rx=2,ry=5)
will overlay a cartesian coordinate grid on the diffraction pattern at scan position (2,5). Adding
>>> show(dp, calibration=calibration, rx=2, ry=5, cartesian_grid={'label':True, 'alpha':0.7,'color':'r'})
will customize the appearance of the grid further. And
>>> show(im, calibration=calibration, cartesian_grid={}, space='R')
displays a cartesian grid over a real space image. For more details, see the documentation for the visualize functions add_*, where * = (‘scalebar’, ‘cartesian_grid’, ‘polarelliptical_grid’, ‘rtheta_grid’). (Under construction!)
- Further customization:
Most parameters accepted by a matplotlib axis will be accepted by
show
. Pass a valid matplotlib colormap or a known string indicating a colormap as the argumentcmap
to specify the colormap. Passfigsize
to specify the figure size. Etc.Further customization can be accomplished by either (1) returning the figure generated by show and then manipulating it using the normal matplotlib functions, or (2) generating a matplotlib Figure with Axes any way you like (e.g. with
plt.subplots
) and then using this function to plot inside a single one of the Axes of your choice.Option (1) is accomplished by simply passing this function
returnfig=True
. Thus:>>> fig,ax = show(ar, returnfig=True)
will now give you direct access to the figure and axes to continue to alter. Option (2) is accomplished by passing an existing figure and axis to
show
as a 2-tuple to thefigax
argument. Thus:>>> fig,(ax1,ax2) = plt.subplots(1,2) >>> show(ar, figax=(fig,ax1)) >>> show(ar, figax=(fig,ax2), hist=True)
will generate a 2-axis figure, and then plot the array
ar
as an image on the left, while plotting its histogram on the right.
- Parameters:
ar (2D array or a list of 2D arrays) – the data to plot. Normally this is a 2D array of the data. If a list of 2D arrays is passed, plots a corresponding grid of images.
figsize (2-tuple) – size of the plot
cmap (colormap) – any matplotlib cmap; default is gray
scaling (str) –
selects a scaling scheme for the intensity values. Default is none. Accepted values:
’none’: do not scale intensity values
’full’: fill entire color range with sorted intensity values
’power’: power law scaling
’log’: values where ar<=0 are set to 0
intensity_range (str) –
- method for setting clipvalues (min and max intensities).
The original name “clipvals” is now deprecated. Default is ‘ordered’. Accepted values:
’ordered’: vmin/vmax are set to fractions of the distribution of pixel values in the array, e.g. vmin=0.02 will set the minumum display value to saturate the lower 2% of pixels
’minmax’: The vmin/vmax values are np.min(ar)/np.max(r)
’absolute’: The vmin/vmax values are set to the values of the vmin,vmax arguments received by this function
- ’std’: The vmin/vmax values are
np.median(ar) -/+ N*np.std(ar)
, and N is this functions min,max vals.
- ’std’: The vmin/vmax values are
’centered’: The vmin/vmax values are set to
c -/+ m
, where by default ‘c’ is zero and m is the max(abs(ar-c), or the two params can be user specified using the kwargs vmin/vmax -> c/m.
vmin (number) – min intensity, behavior depends on clipvals
vmax (number) – max intensity, behavior depends on clipvals
min – alias’ for vmin,vmax, throws deprecation warning
max – alias’ for vmin,vmax, throws deprecation warning
power (number) – specifies the scaling power
power_offset (bool) – If true, image has min value subtracted before power scaling
ticks (bool) – Turn outer tick marks on or off
bordercolor (color or None) – if not None, add a border of this color. The color can be anything matplotlib recognizes as a color.
borderwidth (number) –
returnfig (bool) – if True, the function returns the tuple (figure,axis)
figax (None or 2-tuple) – controls which matplotlib Axes object draws the image. If None, generates a new figure with a single Axes instance. Otherwise, ax must be a 2-tuple containing the matplotlib class instances (Figure,Axes), with ar then plotted in the specified Axes instance.
hist (bool) – if True, instead of plotting a 2D image in ax, plots a histogram of the intensity values of ar, after any scaling this function has performed. Plots the clipvals as dashed vertical lines
n_bins (int) – number of hist bins
mask (None or boolean array) – if not None, must have the same shape as ‘ar’. Wherever mask==True, plot the pixel normally, and where
mask==False
, pixel values are set to mask_color. If hist==True, ignore these values in the histogram. Ifmask_alpha
is specified, the mask is blended with the array underneath, with 0 yielding an opaque mask and 1 yielding a fully transparent mask. Ifmask_color
is set to'empty'
instead of a matplotlib.color, nothing is done to pixels wheremask==False
, allowing overlaying multiple arrays in different regions of an image by invoking the ``figax` kwarg over multiple calls to showmask_color (color) – see ‘mask’
mask_alpha (float) – see ‘mask’
masked_intensity_range (bool) – controls if masked pixel values are included when determining the display value range; False indicates that all pixel values will be used to determine the intensity range, True indicates only unmasked pixels will be used
scalebar (None or dict or Bool) – if None, and a DiffractionSlice or RealSlice with calibrations is passed, adds a scalebar. If scalebar is not displaying the proper calibration, check .calibration pixel_size and pixel_units. If None and an array is passed, does not add a scalebar. If a dict is passed, it is propagated to the add_scalebar function which will attempt to use it to overlay a scalebar. If True, uses calibraiton or pixelsize/pixelunits for scalebar. If False, no scalebar is added.
show_fft (bool) – if True, plots 2D-fft of array
show_cbar (bool) – if True, adds cbar
**kwargs – any keywords accepted by matplotlib’s ax.matshow()
- Returns:
if returnfig==False (default), the figure is plotted and nothing is returned. if returnfig==True, return the figure and the axis.
- py4DSTEM.visualize.show_hist(arr, bins=200, vlines=None, vlinecolor='k', vlinestyle='--', returnhist=False, returnfig=False)
Visualization function to show histogram from any ndarray (arr).
- Accepts:
arr (ndarray) any array bins (int) number of bins that the intensity values will be sorted
into for histogram
- returnhist (bool) determines whether or not the histogram values are
returned (see Returns)
- returnfig (bool) determines whether or not figure and its axis are
returned (see Returns)
- Returns:
- If
returnhist==False and returnfig==False returns nothing returnhist==True and returnfig==True returns (counts,bin_edges) the histogram
values and bin edge locations
returnhist==False and returnfig==True returns (fig,ax), the Figure and Axis returnhist==True and returnfig==True returns (hist,bin_edges),(fig,ax)
- py4DSTEM.visualize.show_Q(ar, scalebar=True, grid=False, polargrid=False, Q_pixel_size=None, Q_pixel_units=None, calibration=None, rx=None, ry=None, qx0=None, qy0=None, e=None, theta=None, scalebarloc=0, scalebarsize=None, scalebarwidth=None, scalebartext=None, scalebartextloc='above', scalebartextsize=12, gridspacing=None, gridcolor='w', majorgridlines=True, majorgridlw=1, majorgridls=':', minorgridlines=True, minorgridlw=0.5, minorgridls=':', gridlabels=False, gridlabelsize=12, gridlabelcolor='k', alpha=0.35, **kwargs)
Shows a diffraction space image with options for several overlays to define the scale, including a scalebar, a cartesian grid, or a polar / polar-elliptical grid.
Regardless of which overlay is requested, the function must recieve either values for Q_pixel_size and Q_pixel_units, or a Calibration instance containing these values. If both are passed, the absolutely passed values take precedence. If a cartesian grid is requested, (qx0,qy0) are required, either passed absolutely or passed as a Calibration instance with the appropriate (rx,ry) value. If a polar grid is requested, (qx0,qy0,e,theta) are required, again either absolutely or via a Calibration instance.
Any arguments accepted by the show() function (e.g. image scaling, clipvalues, etc) may be passed to this function as kwargs.
- py4DSTEM.visualize.show_rectangles(ar, lims=(0, 1, 0, 1), color='r', fill=True, alpha=0.25, linewidth=2, returnfig=False, **kwargs)
Visualization function which plots a 2D array with one or more overlayed rectangles. lims is specified in the order (x0,xf,y0,yf). The rectangle bounds begin at the upper left corner of (x0,y0) and end at the upper left corner of (xf,yf) – i.e inclusive in the lower bound, exclusive in the upper bound – so that the boxed region encloses the area of array ar specified by ar[x0:xf,y0:yf].
To overlay one rectangle, lims must be a single 4-tuple. To overlay N rectangles, lims must be a list of N 4-tuples. color, fill, and alpha may each be single values, which are then applied to all the rectangles, or a length N list.
See the docstring for py4DSTEM.visualize.show() for descriptions of all input parameters not listed below.
- Accepts:
lims (4-tuple, or list of N 4-tuples) the rectangle bounds (x0,xf,y0,yf) color (valid matplotlib color, or list of N colors) fill (bool or list of N bools) filled in or empty rectangles alpha (number, 0 to 1) transparency linewidth (number)
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.show_circles(ar, center, R, color='r', fill=True, alpha=0.3, linewidth=2, returnfig=False, **kwargs)
Visualization function which plots a 2D array with one or more overlayed circles. To overlay one circle, center must be a single 2-tuple. To overlay N circles, center must be a list of N 2-tuples. color, fill, and alpha may each be single values, which are then applied to all the circles, or a length N list.
See the docstring for py4DSTEM.visualize.show() for descriptions of all input parameters not listed below.
- Accepts:
ar (2D array) the data center (2-tuple, or list of N 2-tuples) the center of the circle (x0,y0) R (number of list of N numbers) the circles radius color (valid matplotlib color, or list of N colors) fill (bool or list of N bools) filled in or empty rectangles alpha (number, 0 to 1) transparency linewidth (number)
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.show_ellipses(ar, center, a, b, theta, color='r', fill=True, alpha=0.3, linewidth=2, returnfig=False, **kwargs)
Visualization function which plots a 2D array with one or more overlayed ellipses. To overlay one ellipse, center must be a single 2-tuple. To overlay N circles, center must be a list of N 2-tuples. Similarly, the remaining ellipse parameters - a, e, and theta - must each be a single number or a len-N list. color, fill, and alpha may each be single values, which are then applied to all the circles, or length N lists.
See the docstring for py4DSTEM.visualize.show() for descriptions of all input parameters not listed below.
- Accepts:
center (2-tuple, or list of N 2-tuples) the center of the circle (x0,y0) a (number or list of N numbers) the semimajor axis length e (number or list of N numbers) ratio of semiminor/semimajor length theta (number or list of N numbers) the tilt angle in radians color (valid matplotlib color, or list of N colors) fill (bool or list of N bools) filled in or empty rectangles alpha (number, 0 to 1) transparency linewidth (number)
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.show_annuli(ar, center, radii, color='r', fill=True, alpha=0.3, linewidth=2, returnfig=False, **kwargs)
Visualization function which plots a 2D array with one or more overlayed annuli. To overlay one annulus, center must be a single 2-tuple. To overlay N annuli, center must be a list of N 2-tuples. color, fill, and alpha may each be single values, which are then applied to all the circles, or a length N list.
See the docstring for py4DSTEM.visualize.show() for descriptions of all input parameters not listed below.
- Accepts:
center (2-tuple, or list of N 2-tuples) the center of the annulus (x0,y0) radii (2-tuple, or list of N 2-tuples) the inner and outer radii color (string of list of N strings) fill (bool or list of N bools) filled in or empty rectangles alpha (number, 0 to 1) transparency linewidth (number)
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.show_points(ar, x, y, s=1, scale=50, alpha=1, pointcolor='r', open_circles=False, title=None, returnfig=False, **kwargs)
Plots a 2D array with one or more points. x and y are the point centers and must have the same length, N. s is the relative point sizes, and must have length 1 or N. scale is the size of the largest point. pointcolor have length 1 or N.
- Accepts:
ar (array) the image x,y (number or iterable of numbers) the point positions s (number or iterable of numbers) the relative point sizes scale (number) the maximum point size title (str) title for plot pointcolor alpha
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
overlay
- py4DSTEM.visualize.overlay.add_annuli(ax, d)
Adds one or more annuli to Axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.overlay.add_bragg_index_labels(ax, d)
Adds labels for indexed bragg directions to a plot, using the parameters in dict d.
- The dictionary d has required and optional parameters as follows:
- bragg_directions (req’d) (PointList) the Bragg directions. This PointList must have
the fields ‘qx’,’qy’,’h’, and ‘k’, and may optionally have ‘l’
voffset (number) vertical offset for the labels hoffset (number) horizontal offset for the labels color (color) size (number) points (bool) pointsize (number) pointcolor (color)
- py4DSTEM.visualize.overlay.add_cartesian_grid(ax, d)
Adds an overlaid cartesian coordinate grid over an image using the parameters in dictionary d.
- The dictionary d has required and optional parameters as follows:
x0,y0 (req’d) the origin Nx,Ny (req’d) the image extent space (str) ‘Q’ or ‘R’ spacing (number) spacing between gridlines pixelsize (number) pixelunits (str) lw (number) ls (str) color (color) label (bool) labelsize (number) labelcolor (color) alpha (number)
- py4DSTEM.visualize.overlay.add_circles(ax, d)
adds one or more circles to axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.overlay.add_ellipses(ax, d)
Adds one or more ellipses to axis ax using the parameters in dictionary d.
- Parameters:
center –
a –
b –
theta –
color –
fill –
alpha –
linewidth –
linestyle –
- py4DSTEM.visualize.overlay.add_grid_overlay(ax, d)
adds an overlaid grid over some subset of pixels in an image using the parameters in dictionary d.
- The dictionary d has required and optional parameters as follows:
x0,y0 (req’d) (ints) the corner of the grid xL,xL (req’d) (ints) the extent of the grid color (color) linewidth (number) alpha (number)
- py4DSTEM.visualize.overlay.add_pointlabels(ax, d)
adds number indices for a set of points to axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.overlay.add_points(ax, d)
adds one or more points to axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.overlay.add_polarelliptical_grid(ax, d)
adds an overlaid polar-ellitpical coordinate grid over an image using the parameters in dictionary d.
- The dictionary d has required and optional parameters as follows:
x0,y0 (req’d) the origin e,theta (req’d) the ellipticity (a/b) and major axis angle (radians) Nx,Ny (req’d) the image extent space (str) ‘Q’ or ‘R’ spacing (number) spacing between radial gridlines N_thetalines (int) the number of theta gridlines pixelsize (number) pixelunits (str) lw (number) ls (str) color (color) label (bool) labelsize (number) labelcolor (color) alpha (number)
- py4DSTEM.visualize.overlay.add_rectangles(ax, d)
Adds one or more rectangles to Axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.overlay.add_rtheta_grid(ar, d)
- py4DSTEM.visualize.overlay.add_scalebar(ax, d)
Adds an overlaid scalebar to an image, using the parameters in dict d.
- The dictionary d has required and optional parameters as follows:
Nx,Ny (req’d) the image extent space (str) ‘Q’ or ‘R’ length (number) the scalebar length width (number) the scalebar width pixelsize (number) pixelunits (str) color (color) label (bool) labelsize (number) labelcolor (color) alpha (number) position (str) ‘ul’,’ur’,’bl’, or ‘br’ for the
upperleft, upperright, bottomleft, bottomright
ticks (bool) if False, turns off image border ticks
- py4DSTEM.visualize.overlay.add_vector(ax, d)
Adds a vector to an image, using the parameters in dict d.
- The dictionary d has required and optional parameters as follows:
x0,y0 (req’d) the tail position vx,vy (req’d) the vector color (color) width (number) label (str) labelsize (number) labelcolor (color)
- py4DSTEM.visualize.overlay.get_nice_spacing(Nx, Ny, pixelsize)
Get a nice distance for gridlines, scalebars, etc
- Parameters:
Nx (int) – the image dimensions
Nx – the image dimensions
pixelsize (float) – the size of each pixel, in some units
- Returns:
A 3-tuple containing:
spacing_units: the spacing in real units
spacing_pixels:the spacing in pixels
spacing: the leading digits of the spacing
- Return type:
(3-tuple)
- py4DSTEM.visualize.overlay.is_color_like(c)
Return whether c can be interpreted as an RGB(A) color.
virtualimage
vis_RQ
- py4DSTEM.visualize.vis_RQ.ax_addaxes(ax, vx, vy, vlength, x0, y0, width=1, color='r', labelaxes=True, labelsize=12, labelcolor='r', righthandedcoords=True)
Adds a pair of x/y axes to the matplotlib subplot ax. The user supplies the x-axis direction with (vx,vy), and the y-axis is then chosen by rotating 90 degrees, in a direction set by righthandedcoords.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the x-axis,
Only the orientation is used; the axis is normalized and rescaled by
vlength (number) the axis length x0,y0 (numbers) the origin of the axes labelaxes (bool) if True, label ‘x’ and ‘y’ righthandedcoords (bool) if True, y-axis is counterclockwise
with respect to x-axis
- py4DSTEM.visualize.vis_RQ.ax_addaxes_QtoR(ax, vx, vy, vlength, x0, y0, QR_rotation, width=1, color='r', labelaxes=True, labelsize=12, labelcolor='r')
Adds a pair of x/y axes to the matplotlib subplot ax. The user supplies the x-axis direction with (vx,vy) in reciprocal space coordinates, and the function transforms and displays the corresponding vector in real space.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the x-axis,
in reciprocal space coordinates. Only the orientation is used; the axes are normalized and rescaled by
vlength (number) the axis length, in real space x0,y0 (numbers) the origin of the axes, in
real space
labelaxes (bool) if True, label ‘x’ and ‘y’ QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- py4DSTEM.visualize.vis_RQ.ax_addaxes_RtoQ(ax, vx, vy, vlength, x0, y0, QR_rotation, width=1, color='r', labelaxes=True, labelsize=12, labelcolor='r')
Adds a pair of x/y axes to the matplotlib subplot ax. The user supplies the x-axis direction with (vx,vy) in real space coordinates, and the function transforms and displays the corresponding vector in reciprocal space.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the x-axis,
in real space coordinates. Only the orientation is used; the axes are normalized and rescaled by
vlength (number) the axis length, in reciprocal space x0,y0 (numbers) the origin of the axes, in
reciprocal space
labelaxes (bool) if True, label ‘x’ and ‘y’ QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- py4DSTEM.visualize.vis_RQ.ax_addvector(ax, vx, vy, vlength, x0, y0, width=1, color='r')
Adds a vector to the subplot at ax.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the vector
Only the orientation is used, vector is normalized and rescaled by
vlength (number) the vector length x0,y0 (numbers) the origin / vector tail position
- py4DSTEM.visualize.vis_RQ.ax_addvector_QtoR(ax, vx, vy, vlength, x0, y0, QR_rotation, width=1, color='r')
Adds a vector to the subplot at ax, where the vector (vx,vy) passed to the function is in reciprocal space and the plotted vector is transformed into and plotted in real space.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the vector,
in reciprocal space. Only the orientation is used, vector is normalized and rescaled by
vlength (number) the vector length, in real space x0,y0 (numbers) the origin / vector tail position,
in real space
- QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- py4DSTEM.visualize.vis_RQ.ax_addvector_RtoQ(ax, vx, vy, vlength, x0, y0, QR_rotation, width=1, color='r')
Adds a vector to the subplot at ax, where the vector (vx,vy) passed to the function is in real space and the plotted vector is transformed into and plotted in reciprocal space.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the vector,
in real space. Only the orientation is used, vector is normalized and rescaled by
- vlength (number) the vector length, in reciprocal
space
- x0,y0 (numbers) the origin / vector tail position,
in reciprocal space
- QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- py4DSTEM.visualize.vis_RQ.show(ar, figsize=(5, 5), cmap='gray', scaling='none', intensity_range='ordered', clipvals=None, vmin=None, vmax=None, min=None, max=None, power=None, power_offset=True, combine_images=False, ticks=True, bordercolor=None, borderwidth=5, show_image=True, return_ar_scaled=False, return_intensity_range=False, returncax=False, returnfig=False, figax=None, hist=False, n_bins=256, mask=None, mask_color='k', mask_alpha=0.0, masked_intensity_range=False, rectangle=None, circle=None, annulus=None, ellipse=None, points=None, grid_overlay=None, cartesian_grid=None, polarelliptical_grid=None, rtheta_grid=None, scalebar=None, calibration=None, rx=None, ry=None, space='Q', pixelsize=None, pixelunits=None, x0=None, y0=None, a=None, e=None, theta=None, title=None, show_fft=False, show_cbar=False, **kwargs)
General visualization function for 2D arrays.
The simplest use of this function is:
>>> show(ar)
which will generate and display a matplotlib figure showing the 2D array
ar
. Additional functionality includes:scaling the image (log scaling, power law scaling)
displaying the image histogram
altering the histogram clip values
masking some subset of the image
setting the colormap
adding geometric overlays (e.g. points, circles, rectangles, annuli)
adding informational overlays (scalebars, coordinate grids, oriented axes or vectors)
further customization tools
These are each discussed in turn below.
- Scaling:
Setting the parameter
scaling
will scale the display image. Options are ‘none’, ‘auto’, ‘power’, or ‘log’. If ‘power’ is specified, the parameterpower
must also be passed. The underlying data is not altered. Values less than or equal to zero are set to zero. If the image histogram is displayed usinghist=True
, the scaled image histogram is shown.Examples:
>>> show(ar,scaling='log') >>> show(ar,power=0.5) >>> show(ar,scaling='power',power=0.5,hist=True)
- Histogram:
Setting the argument
hist=True
will display the image histogram, instead of the image. The displayed histogram will reflect any scaling requested. The number of bins can be set withn_bins
. The upper and lower clip values, indicating where the image display will be saturated, are shown with dashed lines.- Intensity range:
Controlling the lower and upper values at which the display image will be saturated is accomplished with the
intensity_range
parameter, or its (soon deprecated) aliasclipvals
, in combination withvmin
, andvmax
. The method by which the upper and lower clip values are determined is controlled byintensity_range
, and must be a string in (‘None’,’ordered’,’minmax’,’absolute’,’std’,’centered’). See the argument description forintensity_range
for a description of the behavior for each. The clip values can be returned with thereturn_intensity_range
parameter.- Masking:
If a numpy masked array is passed to show, the function will automatically mask the appropriate pixels. Alternatively, a boolean array of the same shape as the data array may be passed to the
mask
argument, and these pixels will be masked. Masked pixels are displayed as a single uniform color, black by default, and which can be specified with themask_color
argument. Masked pixels are excluded when displaying the histogram or computing clip values. The mask can also be blended with the hidden data by setting themask_alpha
argument.- Overlays (geometric):
The function natively supports overlaying points, circles, rectangles, annuli, and ellipses. Each is invoked by passing a dictionary to the appropriate input variable specifying the geometry and features of the requested overlay. For example:
>>> show(ar, rectangle={'lims':(10,20,10,20),'color':'r'})
will overlay a single red square, and
>>> show(ar, annulus={'center':[(28,68),(92,160)], 'radii':[(16,24),(12,36)], 'fill':True, 'alpha':[0.9,0.3], 'color':['r',(0,1,1,1)]})
will overlay two annuli with two different centers, radii, colors, and transparencies. For a description of the accepted dictionary parameters for each type of overlay, see the visualize functions add_*, where * = (‘rectangle’,’circle’,’annulus’,’ellipse’,’points’). (These docstrings are under construction!)
- Overlays (informational):
Informational overlays supported by this function include coordinate axes (cartesian, polar-elliptical, or r-theta) and scalebars. These are added by passing the appropriate input argument a dictionary of the desired parameters, as with geometric overlays. However, there are two key differences between these overlays and the geometric overlays. First, informational overlays (coordinate systems and scalebars) require information about the plot - e.g. the position of the origin, the pixel sizes, the pixel units, any elliptical distortions, etc. The easiest way to pass this information is by pass a Calibration object containing this info to
show
as the keywordcalibration
. Second, once the coordinate information has been passed, informational overlays can autoselect their own parameters, thus simply passing an empty dict to one of these parameters will add that overlay.For example:
>>> show(dp, scalebar={}, calibration=calibration)
will display the diffraction pattern
dp
with a scalebar overlaid in the bottom left corner given the pixel size and units described incalibration
, and>>> show(dp, calibration=calibration, scalebar={'length':0.5,'width':2, 'position':'ul','label':True'})
will display a more customized scalebar.
When overlaying coordinate grids, it is important to note that some relevant parameters, e.g. the position of the origin, may change by scan position. In these cases, the parameters
rx
,``ry`` must also be passed toshow
, to tell theCalibration
object where to look for the relevant parameters. For example:>>> show(dp, cartesian_grid={}, calibration=calibration, rx=2,ry=5)
will overlay a cartesian coordinate grid on the diffraction pattern at scan position (2,5). Adding
>>> show(dp, calibration=calibration, rx=2, ry=5, cartesian_grid={'label':True, 'alpha':0.7,'color':'r'})
will customize the appearance of the grid further. And
>>> show(im, calibration=calibration, cartesian_grid={}, space='R')
displays a cartesian grid over a real space image. For more details, see the documentation for the visualize functions add_*, where * = (‘scalebar’, ‘cartesian_grid’, ‘polarelliptical_grid’, ‘rtheta_grid’). (Under construction!)
- Further customization:
Most parameters accepted by a matplotlib axis will be accepted by
show
. Pass a valid matplotlib colormap or a known string indicating a colormap as the argumentcmap
to specify the colormap. Passfigsize
to specify the figure size. Etc.Further customization can be accomplished by either (1) returning the figure generated by show and then manipulating it using the normal matplotlib functions, or (2) generating a matplotlib Figure with Axes any way you like (e.g. with
plt.subplots
) and then using this function to plot inside a single one of the Axes of your choice.Option (1) is accomplished by simply passing this function
returnfig=True
. Thus:>>> fig,ax = show(ar, returnfig=True)
will now give you direct access to the figure and axes to continue to alter. Option (2) is accomplished by passing an existing figure and axis to
show
as a 2-tuple to thefigax
argument. Thus:>>> fig,(ax1,ax2) = plt.subplots(1,2) >>> show(ar, figax=(fig,ax1)) >>> show(ar, figax=(fig,ax2), hist=True)
will generate a 2-axis figure, and then plot the array
ar
as an image on the left, while plotting its histogram on the right.
- Parameters:
ar (2D array or a list of 2D arrays) – the data to plot. Normally this is a 2D array of the data. If a list of 2D arrays is passed, plots a corresponding grid of images.
figsize (2-tuple) – size of the plot
cmap (colormap) – any matplotlib cmap; default is gray
scaling (str) –
selects a scaling scheme for the intensity values. Default is none. Accepted values:
’none’: do not scale intensity values
’full’: fill entire color range with sorted intensity values
’power’: power law scaling
’log’: values where ar<=0 are set to 0
intensity_range (str) –
- method for setting clipvalues (min and max intensities).
The original name “clipvals” is now deprecated. Default is ‘ordered’. Accepted values:
’ordered’: vmin/vmax are set to fractions of the distribution of pixel values in the array, e.g. vmin=0.02 will set the minumum display value to saturate the lower 2% of pixels
’minmax’: The vmin/vmax values are np.min(ar)/np.max(r)
’absolute’: The vmin/vmax values are set to the values of the vmin,vmax arguments received by this function
- ’std’: The vmin/vmax values are
np.median(ar) -/+ N*np.std(ar)
, and N is this functions min,max vals.
- ’std’: The vmin/vmax values are
’centered’: The vmin/vmax values are set to
c -/+ m
, where by default ‘c’ is zero and m is the max(abs(ar-c), or the two params can be user specified using the kwargs vmin/vmax -> c/m.
vmin (number) – min intensity, behavior depends on clipvals
vmax (number) – max intensity, behavior depends on clipvals
min – alias’ for vmin,vmax, throws deprecation warning
max – alias’ for vmin,vmax, throws deprecation warning
power (number) – specifies the scaling power
power_offset (bool) – If true, image has min value subtracted before power scaling
ticks (bool) – Turn outer tick marks on or off
bordercolor (color or None) – if not None, add a border of this color. The color can be anything matplotlib recognizes as a color.
borderwidth (number) –
returnfig (bool) – if True, the function returns the tuple (figure,axis)
figax (None or 2-tuple) – controls which matplotlib Axes object draws the image. If None, generates a new figure with a single Axes instance. Otherwise, ax must be a 2-tuple containing the matplotlib class instances (Figure,Axes), with ar then plotted in the specified Axes instance.
hist (bool) – if True, instead of plotting a 2D image in ax, plots a histogram of the intensity values of ar, after any scaling this function has performed. Plots the clipvals as dashed vertical lines
n_bins (int) – number of hist bins
mask (None or boolean array) – if not None, must have the same shape as ‘ar’. Wherever mask==True, plot the pixel normally, and where
mask==False
, pixel values are set to mask_color. If hist==True, ignore these values in the histogram. Ifmask_alpha
is specified, the mask is blended with the array underneath, with 0 yielding an opaque mask and 1 yielding a fully transparent mask. Ifmask_color
is set to'empty'
instead of a matplotlib.color, nothing is done to pixels wheremask==False
, allowing overlaying multiple arrays in different regions of an image by invoking the ``figax` kwarg over multiple calls to showmask_color (color) – see ‘mask’
mask_alpha (float) – see ‘mask’
masked_intensity_range (bool) – controls if masked pixel values are included when determining the display value range; False indicates that all pixel values will be used to determine the intensity range, True indicates only unmasked pixels will be used
scalebar (None or dict or Bool) – if None, and a DiffractionSlice or RealSlice with calibrations is passed, adds a scalebar. If scalebar is not displaying the proper calibration, check .calibration pixel_size and pixel_units. If None and an array is passed, does not add a scalebar. If a dict is passed, it is propagated to the add_scalebar function which will attempt to use it to overlay a scalebar. If True, uses calibraiton or pixelsize/pixelunits for scalebar. If False, no scalebar is added.
show_fft (bool) – if True, plots 2D-fft of array
show_cbar (bool) – if True, adds cbar
**kwargs – any keywords accepted by matplotlib’s ax.matshow()
- Returns:
if returnfig==False (default), the figure is plotted and nothing is returned. if returnfig==True, return the figure and the axis.
- py4DSTEM.visualize.vis_RQ.show_RQ(realspace_image, diffractionspace_image, realspace_pdict={}, diffractionspace_pdict={'scaling': 'log'}, figsize=(12, 6), returnfig=False)
Shows side-by-side real/reciprocal space images.
- Accepts:
realspace_image (2D array) diffractionspace_image (2D array) realspace_pdict (dictionary) arguments and values to pass
to the show() fn for the real space image
diffractionspace_pdict (dictionary)
- py4DSTEM.visualize.vis_RQ.show_RQ_axes(realspace_image, diffractionspace_image, realspace_pdict, diffractionspace_pdict, vx, vy, vlength_R, vlength_Q, x0_R, y0_R, x0_Q, y0_Q, QR_rotation, vector_space='R', width_R=1, color_R='r', width_Q=1, color_Q='r', labelaxes=True, labelcolor_R='r', labelcolor_Q='r', labelsize_R=12, labelsize_Q=12, figsize=(12, 6), returnfig=False)
Shows side-by-side real/reciprocal space images with a set of corresponding coordinate axes overlaid in each. (vx,vy) specifies the x-axis, and the y-axis is rotated 90 degrees counterclockwise in reciprocal space (relevant in case of an R/Q transposition).
- Accepts:
realspace_image (2D array) diffractionspace_image (2D array) realspace_pdict (dictionary) arguments and values to pass
to the show() fn for the real space image
diffractionspace_pdict (dictionary) vx,vy (numbers) x,y components of the x-axis
in either real or diffraction space, depending on the value of vector_space. Note (vx,vy) is used for the orientation only - the vectors are normalized and rescaled by
- vlength_R,vlength_Q (number or 1D arrays) the vector length in each
space, in pixels
x0_R,y0_R,x0_Q,y0_Q (number) the origins / vector tail positions QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- vector_space (string) must be ‘R’ or ‘Q’. Specifies
whether the (vx,vy) values passed to this function describes a real or diffracation space vector.
- py4DSTEM.visualize.vis_RQ.show_RQ_vector(realspace_image, diffractionspace_image, realspace_pdict, diffractionspace_pdict, vx, vy, vlength_R, vlength_Q, x0_R, y0_R, x0_Q, y0_Q, QR_rotation, vector_space='R', width_R=1, color_R='r', width_Q=1, color_Q='r', figsize=(12, 6), returnfig=False)
Shows side-by-side real/reciprocal space images with a vector overlaid in each showing corresponding directions.
- Accepts:
realspace_image (2D array) diffractionspace_image (2D array) realspace_pdict (dictionary) arguments and values to pass
to the show() fn for the real space image
diffractionspace_pdict (dictionary) vx,vy (numbers) x,y components of the vector
in either real or diffraction space, depending on the value of vector_space. Note (vx,vy) is used for the orientation only - the two vectors are normalized and rescaled by
- vlength_R,vlength_Q (number) the vector length in each
space, in pixels
x0_R,y0_R,x0_Q,y0_Q (numbers) the origins / vector tail positions QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- vector_space (string) must be ‘R’ or ‘Q’. Specifies
whether the (vx,vy) values passed to this function describes a real or diffracation space vector.
- py4DSTEM.visualize.vis_RQ.show_RQ_vectors(realspace_image, diffractionspace_image, realspace_pdict, diffractionspace_pdict, vx, vy, vlength_R, vlength_Q, x0_R, y0_R, x0_Q, y0_Q, QR_rotation, vector_space='R', width_R=1, color_R='r', width_Q=1, color_Q='r', figsize=(12, 6), returnfig=False)
Shows side-by-side real/reciprocal space images with several vectors overlaid in each showing corresponding directions.
- Accepts:
realspace_image (2D array) diffractionspace_image (2D array) realspace_pdict (dictionary) arguments and values to pass
to the show() fn for the real space image
diffractionspace_pdict (dictionary) vx,vy (1D arrays) x,y components of the vectors
in either real or diffraction space, depending on the value of vector_space. Note (vx,vy) is used for the orientation only - the two vectors are normalized and rescaled by
- vlength_R,vlenght_Q (number) the vector length in each
space, in pixels
x0_R,y0_R,x0_Q,y0_Q (numbers) the origins / vector tail positions QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- vector_space (string) must be ‘R’ or ‘Q’. Specifies
whether the (vx,vy) values passed to this function describes a real or diffracation space vector.
- py4DSTEM.visualize.vis_RQ.show_points(ar, x, y, s=1, scale=50, alpha=1, pointcolor='r', open_circles=False, title=None, returnfig=False, **kwargs)
Plots a 2D array with one or more points. x and y are the point centers and must have the same length, N. s is the relative point sizes, and must have length 1 or N. scale is the size of the largest point. pointcolor have length 1 or N.
- Accepts:
ar (array) the image x,y (number or iterable of numbers) the point positions s (number or iterable of numbers) the relative point sizes scale (number) the maximum point size title (str) title for plot pointcolor alpha
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.vis_RQ.show_selected_dp(datacube, image, rx, ry, figsize=(12, 6), returnfig=False, pointsize=50, pointcolor='r', scaling='log', **kwargs)
vis_grid
- py4DSTEM.visualize.vis_grid._show_grid_overlay(image, x0, y0, xL, yL, color='k', linewidth=1, alpha=1, returnfig=False, **kwargs)
Shows the image with an overlaid boxgrid outline about the pixels beginning at (x0,y0) and with extent xL,yL in the two directions.
- Accepts:
image the image array x0,y0 the corner of the grid xL,xL the extent of the grid
- py4DSTEM.visualize.vis_grid.add_grid_overlay(ax, d)
adds an overlaid grid over some subset of pixels in an image using the parameters in dictionary d.
- The dictionary d has required and optional parameters as follows:
x0,y0 (req’d) (ints) the corner of the grid xL,xL (req’d) (ints) the extent of the grid color (color) linewidth (number) alpha (number)
- py4DSTEM.visualize.vis_grid.show(ar, figsize=(5, 5), cmap='gray', scaling='none', intensity_range='ordered', clipvals=None, vmin=None, vmax=None, min=None, max=None, power=None, power_offset=True, combine_images=False, ticks=True, bordercolor=None, borderwidth=5, show_image=True, return_ar_scaled=False, return_intensity_range=False, returncax=False, returnfig=False, figax=None, hist=False, n_bins=256, mask=None, mask_color='k', mask_alpha=0.0, masked_intensity_range=False, rectangle=None, circle=None, annulus=None, ellipse=None, points=None, grid_overlay=None, cartesian_grid=None, polarelliptical_grid=None, rtheta_grid=None, scalebar=None, calibration=None, rx=None, ry=None, space='Q', pixelsize=None, pixelunits=None, x0=None, y0=None, a=None, e=None, theta=None, title=None, show_fft=False, show_cbar=False, **kwargs)
General visualization function for 2D arrays.
The simplest use of this function is:
>>> show(ar)
which will generate and display a matplotlib figure showing the 2D array
ar
. Additional functionality includes:scaling the image (log scaling, power law scaling)
displaying the image histogram
altering the histogram clip values
masking some subset of the image
setting the colormap
adding geometric overlays (e.g. points, circles, rectangles, annuli)
adding informational overlays (scalebars, coordinate grids, oriented axes or vectors)
further customization tools
These are each discussed in turn below.
- Scaling:
Setting the parameter
scaling
will scale the display image. Options are ‘none’, ‘auto’, ‘power’, or ‘log’. If ‘power’ is specified, the parameterpower
must also be passed. The underlying data is not altered. Values less than or equal to zero are set to zero. If the image histogram is displayed usinghist=True
, the scaled image histogram is shown.Examples:
>>> show(ar,scaling='log') >>> show(ar,power=0.5) >>> show(ar,scaling='power',power=0.5,hist=True)
- Histogram:
Setting the argument
hist=True
will display the image histogram, instead of the image. The displayed histogram will reflect any scaling requested. The number of bins can be set withn_bins
. The upper and lower clip values, indicating where the image display will be saturated, are shown with dashed lines.- Intensity range:
Controlling the lower and upper values at which the display image will be saturated is accomplished with the
intensity_range
parameter, or its (soon deprecated) aliasclipvals
, in combination withvmin
, andvmax
. The method by which the upper and lower clip values are determined is controlled byintensity_range
, and must be a string in (‘None’,’ordered’,’minmax’,’absolute’,’std’,’centered’). See the argument description forintensity_range
for a description of the behavior for each. The clip values can be returned with thereturn_intensity_range
parameter.- Masking:
If a numpy masked array is passed to show, the function will automatically mask the appropriate pixels. Alternatively, a boolean array of the same shape as the data array may be passed to the
mask
argument, and these pixels will be masked. Masked pixels are displayed as a single uniform color, black by default, and which can be specified with themask_color
argument. Masked pixels are excluded when displaying the histogram or computing clip values. The mask can also be blended with the hidden data by setting themask_alpha
argument.- Overlays (geometric):
The function natively supports overlaying points, circles, rectangles, annuli, and ellipses. Each is invoked by passing a dictionary to the appropriate input variable specifying the geometry and features of the requested overlay. For example:
>>> show(ar, rectangle={'lims':(10,20,10,20),'color':'r'})
will overlay a single red square, and
>>> show(ar, annulus={'center':[(28,68),(92,160)], 'radii':[(16,24),(12,36)], 'fill':True, 'alpha':[0.9,0.3], 'color':['r',(0,1,1,1)]})
will overlay two annuli with two different centers, radii, colors, and transparencies. For a description of the accepted dictionary parameters for each type of overlay, see the visualize functions add_*, where * = (‘rectangle’,’circle’,’annulus’,’ellipse’,’points’). (These docstrings are under construction!)
- Overlays (informational):
Informational overlays supported by this function include coordinate axes (cartesian, polar-elliptical, or r-theta) and scalebars. These are added by passing the appropriate input argument a dictionary of the desired parameters, as with geometric overlays. However, there are two key differences between these overlays and the geometric overlays. First, informational overlays (coordinate systems and scalebars) require information about the plot - e.g. the position of the origin, the pixel sizes, the pixel units, any elliptical distortions, etc. The easiest way to pass this information is by pass a Calibration object containing this info to
show
as the keywordcalibration
. Second, once the coordinate information has been passed, informational overlays can autoselect their own parameters, thus simply passing an empty dict to one of these parameters will add that overlay.For example:
>>> show(dp, scalebar={}, calibration=calibration)
will display the diffraction pattern
dp
with a scalebar overlaid in the bottom left corner given the pixel size and units described incalibration
, and>>> show(dp, calibration=calibration, scalebar={'length':0.5,'width':2, 'position':'ul','label':True'})
will display a more customized scalebar.
When overlaying coordinate grids, it is important to note that some relevant parameters, e.g. the position of the origin, may change by scan position. In these cases, the parameters
rx
,``ry`` must also be passed toshow
, to tell theCalibration
object where to look for the relevant parameters. For example:>>> show(dp, cartesian_grid={}, calibration=calibration, rx=2,ry=5)
will overlay a cartesian coordinate grid on the diffraction pattern at scan position (2,5). Adding
>>> show(dp, calibration=calibration, rx=2, ry=5, cartesian_grid={'label':True, 'alpha':0.7,'color':'r'})
will customize the appearance of the grid further. And
>>> show(im, calibration=calibration, cartesian_grid={}, space='R')
displays a cartesian grid over a real space image. For more details, see the documentation for the visualize functions add_*, where * = (‘scalebar’, ‘cartesian_grid’, ‘polarelliptical_grid’, ‘rtheta_grid’). (Under construction!)
- Further customization:
Most parameters accepted by a matplotlib axis will be accepted by
show
. Pass a valid matplotlib colormap or a known string indicating a colormap as the argumentcmap
to specify the colormap. Passfigsize
to specify the figure size. Etc.Further customization can be accomplished by either (1) returning the figure generated by show and then manipulating it using the normal matplotlib functions, or (2) generating a matplotlib Figure with Axes any way you like (e.g. with
plt.subplots
) and then using this function to plot inside a single one of the Axes of your choice.Option (1) is accomplished by simply passing this function
returnfig=True
. Thus:>>> fig,ax = show(ar, returnfig=True)
will now give you direct access to the figure and axes to continue to alter. Option (2) is accomplished by passing an existing figure and axis to
show
as a 2-tuple to thefigax
argument. Thus:>>> fig,(ax1,ax2) = plt.subplots(1,2) >>> show(ar, figax=(fig,ax1)) >>> show(ar, figax=(fig,ax2), hist=True)
will generate a 2-axis figure, and then plot the array
ar
as an image on the left, while plotting its histogram on the right.
- Parameters:
ar (2D array or a list of 2D arrays) – the data to plot. Normally this is a 2D array of the data. If a list of 2D arrays is passed, plots a corresponding grid of images.
figsize (2-tuple) – size of the plot
cmap (colormap) – any matplotlib cmap; default is gray
scaling (str) –
selects a scaling scheme for the intensity values. Default is none. Accepted values:
’none’: do not scale intensity values
’full’: fill entire color range with sorted intensity values
’power’: power law scaling
’log’: values where ar<=0 are set to 0
intensity_range (str) –
- method for setting clipvalues (min and max intensities).
The original name “clipvals” is now deprecated. Default is ‘ordered’. Accepted values:
’ordered’: vmin/vmax are set to fractions of the distribution of pixel values in the array, e.g. vmin=0.02 will set the minumum display value to saturate the lower 2% of pixels
’minmax’: The vmin/vmax values are np.min(ar)/np.max(r)
’absolute’: The vmin/vmax values are set to the values of the vmin,vmax arguments received by this function
- ’std’: The vmin/vmax values are
np.median(ar) -/+ N*np.std(ar)
, and N is this functions min,max vals.
- ’std’: The vmin/vmax values are
’centered’: The vmin/vmax values are set to
c -/+ m
, where by default ‘c’ is zero and m is the max(abs(ar-c), or the two params can be user specified using the kwargs vmin/vmax -> c/m.
vmin (number) – min intensity, behavior depends on clipvals
vmax (number) – max intensity, behavior depends on clipvals
min – alias’ for vmin,vmax, throws deprecation warning
max – alias’ for vmin,vmax, throws deprecation warning
power (number) – specifies the scaling power
power_offset (bool) – If true, image has min value subtracted before power scaling
ticks (bool) – Turn outer tick marks on or off
bordercolor (color or None) – if not None, add a border of this color. The color can be anything matplotlib recognizes as a color.
borderwidth (number) –
returnfig (bool) – if True, the function returns the tuple (figure,axis)
figax (None or 2-tuple) – controls which matplotlib Axes object draws the image. If None, generates a new figure with a single Axes instance. Otherwise, ax must be a 2-tuple containing the matplotlib class instances (Figure,Axes), with ar then plotted in the specified Axes instance.
hist (bool) – if True, instead of plotting a 2D image in ax, plots a histogram of the intensity values of ar, after any scaling this function has performed. Plots the clipvals as dashed vertical lines
n_bins (int) – number of hist bins
mask (None or boolean array) – if not None, must have the same shape as ‘ar’. Wherever mask==True, plot the pixel normally, and where
mask==False
, pixel values are set to mask_color. If hist==True, ignore these values in the histogram. Ifmask_alpha
is specified, the mask is blended with the array underneath, with 0 yielding an opaque mask and 1 yielding a fully transparent mask. Ifmask_color
is set to'empty'
instead of a matplotlib.color, nothing is done to pixels wheremask==False
, allowing overlaying multiple arrays in different regions of an image by invoking the ``figax` kwarg over multiple calls to showmask_color (color) – see ‘mask’
mask_alpha (float) – see ‘mask’
masked_intensity_range (bool) – controls if masked pixel values are included when determining the display value range; False indicates that all pixel values will be used to determine the intensity range, True indicates only unmasked pixels will be used
scalebar (None or dict or Bool) – if None, and a DiffractionSlice or RealSlice with calibrations is passed, adds a scalebar. If scalebar is not displaying the proper calibration, check .calibration pixel_size and pixel_units. If None and an array is passed, does not add a scalebar. If a dict is passed, it is propagated to the add_scalebar function which will attempt to use it to overlay a scalebar. If True, uses calibraiton or pixelsize/pixelunits for scalebar. If False, no scalebar is added.
show_fft (bool) – if True, plots 2D-fft of array
show_cbar (bool) – if True, adds cbar
**kwargs – any keywords accepted by matplotlib’s ax.matshow()
- Returns:
if returnfig==False (default), the figure is plotted and nothing is returned. if returnfig==True, return the figure and the axis.
- py4DSTEM.visualize.vis_grid.show_DP_grid(datacube, x0, y0, xL, yL, axsize=(6, 6), returnfig=False, space=0, **kwargs)
Shows a grid of diffraction patterns from DataCube datacube, starting from scan position (x0,y0) and extending xL,yL.
- Accepts:
datacube (DataCube) the 4D-STEM data (x0,y0) the corner of the grid of DPs to display xL,yL the extent of the grid axsize the size of each diffraction pattern space (number) controls the space between subplots
- Returns:
if returnfig==false (default), the figure is plotted and nothing is returned. if returnfig==false, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.vis_grid.show_grid_overlay(image, x0, y0, xL, yL, color='k', linewidth=1, alpha=1, returnfig=False, **kwargs)
Shows the image with an overlaid boxgrid outline about the pixels beginning at (x0,y0) and with extent xL,yL in the two directions.
- Accepts:
image the image array x0,y0 the corner of the grid xL,xL the extent of the grid
- py4DSTEM.visualize.vis_grid.show_image_grid(get_ar, H, W, axsize=(6, 6), returnfig=False, figax=None, title=None, title_index=False, suptitle=None, get_bordercolor=None, get_x=None, get_y=None, get_pointcolors=None, get_s=None, open_circles=False, **kwargs)
Displays a set of images in a grid.
The images are specified by some function get_ar(i), which returns an image for values of some integer index i. The values of i passed to get_ar are 0 through HW-1.
To display the first 4 two-dimensional slices of some 3D array ar some 3D array ar, you can do
>>> show_image_grid(lambda i:ar[:,:,i], H=2, W=2)
Its also possible to add colored borders, or overlaid points, using similar functions to get_ar, i.e. functions which return the color or set of points of interest as a function of index i, which must be defined in the range [0,HW-1].
- Accepts:
- get_ar a function which returns a 2D array when passed
the integers 0 through HW-1
H,W integers, the dimensions of the grid axsize the size of each image figax controls which matplotlib Axes object draws the image.
If None, generates a new figure with a single Axes instance. Otherwise, ax must be a 2-tuple containing the matplotlib class instances (Figure,Axes), with ar then plotted in the specified Axes instance.
- title if title is sting, then prints title as suptitle. If a suptitle is also provided,
the suptitle is printed insead. if title is a list of strings (ex: [‘title 1’,’title 2’]), each array has corresponding title in list.
title_index if True, prints the index i passed to get_ar over each image suptitle string, suptitle on plot get_bordercolor
if not None, should be a function defined over the same i as get_ar, and which returns a valid matplotlib color for each i. Adds a colored bounding box about each image. E.g. if colors is an array of colors:
>>> show_image_grid(lambda i:ar[:,:,i],H=2,W=2, get_bordercolor=lambda i:colors[i])
- get_x,get_y functions which returns sets of x/y positions
as a function of index i
- get_s function which returns a set of point sizes
as a function of index i
- get_pointcolors a function which returns a color or list of colors
as a function of index i
- Returns:
if returnfig==false (default), the figure is plotted and nothing is returned. if returnfig==false, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.vis_grid.show_points(ar, x, y, s=1, scale=50, alpha=1, pointcolor='r', open_circles=False, title=None, returnfig=False, **kwargs)
Plots a 2D array with one or more points. x and y are the point centers and must have the same length, N. s is the relative point sizes, and must have length 1 or N. scale is the size of the largest point. pointcolor have length 1 or N.
- Accepts:
ar (array) the image x,y (number or iterable of numbers) the point positions s (number or iterable of numbers) the relative point sizes scale (number) the maximum point size title (str) title for plot pointcolor alpha
- Returns:
If returnfig==False (default), the figure is plotted and nothing is returned. If returnfig==False, the figure and its one axis are returned, and can be further edited.
vis_special
- py4DSTEM.visualize.vis_special.Complex2RGB(complex_data, vmin=None, vmax=None, power=None, chroma_boost=1)
complex_data (array): complex array to plot vmin (float) : minimum absolute value vmax (float) : maximum absolute value power (float) : power to raise amplitude to chroma_boost (float): boosts chroma for higher-contrast (~1-2.5)
- py4DSTEM.visualize.vis_special.add_bragg_index_labels(ax, d)
Adds labels for indexed bragg directions to a plot, using the parameters in dict d.
- The dictionary d has required and optional parameters as follows:
- bragg_directions (req’d) (PointList) the Bragg directions. This PointList must have
the fields ‘qx’,’qy’,’h’, and ‘k’, and may optionally have ‘l’
voffset (number) vertical offset for the labels hoffset (number) horizontal offset for the labels color (color) size (number) points (bool) pointsize (number) pointcolor (color)
- py4DSTEM.visualize.vis_special.add_ellipses(ax, d)
Adds one or more ellipses to axis ax using the parameters in dictionary d.
- Parameters:
center –
a –
b –
theta –
color –
fill –
alpha –
linewidth –
linestyle –
- py4DSTEM.visualize.vis_special.add_pointlabels(ax, d)
adds number indices for a set of points to axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.vis_special.add_points(ax, d)
adds one or more points to axis ax using the parameters in dictionary d.
- py4DSTEM.visualize.vis_special.add_scalebar(ax, d)
Adds an overlaid scalebar to an image, using the parameters in dict d.
- The dictionary d has required and optional parameters as follows:
Nx,Ny (req’d) the image extent space (str) ‘Q’ or ‘R’ length (number) the scalebar length width (number) the scalebar width pixelsize (number) pixelunits (str) color (color) label (bool) labelsize (number) labelcolor (color) alpha (number) position (str) ‘ul’,’ur’,’bl’, or ‘br’ for the
upperleft, upperright, bottomleft, bottomright
ticks (bool) if False, turns off image border ticks
- py4DSTEM.visualize.vis_special.add_vector(ax, d)
Adds a vector to an image, using the parameters in dict d.
- The dictionary d has required and optional parameters as follows:
x0,y0 (req’d) the tail position vx,vy (req’d) the vector color (color) width (number) label (str) labelsize (number) labelcolor (color)
- py4DSTEM.visualize.vis_special.ax_addaxes(ax, vx, vy, vlength, x0, y0, width=1, color='r', labelaxes=True, labelsize=12, labelcolor='r', righthandedcoords=True)
Adds a pair of x/y axes to the matplotlib subplot ax. The user supplies the x-axis direction with (vx,vy), and the y-axis is then chosen by rotating 90 degrees, in a direction set by righthandedcoords.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the x-axis,
Only the orientation is used; the axis is normalized and rescaled by
vlength (number) the axis length x0,y0 (numbers) the origin of the axes labelaxes (bool) if True, label ‘x’ and ‘y’ righthandedcoords (bool) if True, y-axis is counterclockwise
with respect to x-axis
- py4DSTEM.visualize.vis_special.ax_addaxes_QtoR(ax, vx, vy, vlength, x0, y0, QR_rotation, width=1, color='r', labelaxes=True, labelsize=12, labelcolor='r')
Adds a pair of x/y axes to the matplotlib subplot ax. The user supplies the x-axis direction with (vx,vy) in reciprocal space coordinates, and the function transforms and displays the corresponding vector in real space.
- Accepts:
ax (matplotlib subplot) vx,vy (numbers) x,y components of the x-axis,
in reciprocal space coordinates. Only the orientation is used; the axes are normalized and rescaled by
vlength (number) the axis length, in real space x0,y0 (numbers) the origin of the axes, in
real space
labelaxes (bool) if True, label ‘x’ and ‘y’ QR_rotation (number) the offset angle between real and
diffraction space. Specifically, this is the counterclockwise rotation of real space with respect to diffraction space. In degrees.
- py4DSTEM.visualize.vis_special.make_axes_locatable(axes)
- py4DSTEM.visualize.vis_special.select_point(ar, x, y, i, color='lightblue', color_selected='r', size=20, returnfig=False, **kwargs)
Show enumerated index labels for a set of points, with one selected point highlighted
- py4DSTEM.visualize.vis_special.show(ar, figsize=(5, 5), cmap='gray', scaling='none', intensity_range='ordered', clipvals=None, vmin=None, vmax=None, min=None, max=None, power=None, power_offset=True, combine_images=False, ticks=True, bordercolor=None, borderwidth=5, show_image=True, return_ar_scaled=False, return_intensity_range=False, returncax=False, returnfig=False, figax=None, hist=False, n_bins=256, mask=None, mask_color='k', mask_alpha=0.0, masked_intensity_range=False, rectangle=None, circle=None, annulus=None, ellipse=None, points=None, grid_overlay=None, cartesian_grid=None, polarelliptical_grid=None, rtheta_grid=None, scalebar=None, calibration=None, rx=None, ry=None, space='Q', pixelsize=None, pixelunits=None, x0=None, y0=None, a=None, e=None, theta=None, title=None, show_fft=False, show_cbar=False, **kwargs)
General visualization function for 2D arrays.
The simplest use of this function is:
>>> show(ar)
which will generate and display a matplotlib figure showing the 2D array
ar
. Additional functionality includes:scaling the image (log scaling, power law scaling)
displaying the image histogram
altering the histogram clip values
masking some subset of the image
setting the colormap
adding geometric overlays (e.g. points, circles, rectangles, annuli)
adding informational overlays (scalebars, coordinate grids, oriented axes or vectors)
further customization tools
These are each discussed in turn below.
- Scaling:
Setting the parameter
scaling
will scale the display image. Options are ‘none’, ‘auto’, ‘power’, or ‘log’. If ‘power’ is specified, the parameterpower
must also be passed. The underlying data is not altered. Values less than or equal to zero are set to zero. If the image histogram is displayed usinghist=True
, the scaled image histogram is shown.Examples:
>>> show(ar,scaling='log') >>> show(ar,power=0.5) >>> show(ar,scaling='power',power=0.5,hist=True)
- Histogram:
Setting the argument
hist=True
will display the image histogram, instead of the image. The displayed histogram will reflect any scaling requested. The number of bins can be set withn_bins
. The upper and lower clip values, indicating where the image display will be saturated, are shown with dashed lines.- Intensity range:
Controlling the lower and upper values at which the display image will be saturated is accomplished with the
intensity_range
parameter, or its (soon deprecated) aliasclipvals
, in combination withvmin
, andvmax
. The method by which the upper and lower clip values are determined is controlled byintensity_range
, and must be a string in (‘None’,’ordered’,’minmax’,’absolute’,’std’,’centered’). See the argument description forintensity_range
for a description of the behavior for each. The clip values can be returned with thereturn_intensity_range
parameter.- Masking:
If a numpy masked array is passed to show, the function will automatically mask the appropriate pixels. Alternatively, a boolean array of the same shape as the data array may be passed to the
mask
argument, and these pixels will be masked. Masked pixels are displayed as a single uniform color, black by default, and which can be specified with themask_color
argument. Masked pixels are excluded when displaying the histogram or computing clip values. The mask can also be blended with the hidden data by setting themask_alpha
argument.- Overlays (geometric):
The function natively supports overlaying points, circles, rectangles, annuli, and ellipses. Each is invoked by passing a dictionary to the appropriate input variable specifying the geometry and features of the requested overlay. For example:
>>> show(ar, rectangle={'lims':(10,20,10,20),'color':'r'})
will overlay a single red square, and
>>> show(ar, annulus={'center':[(28,68),(92,160)], 'radii':[(16,24),(12,36)], 'fill':True, 'alpha':[0.9,0.3], 'color':['r',(0,1,1,1)]})
will overlay two annuli with two different centers, radii, colors, and transparencies. For a description of the accepted dictionary parameters for each type of overlay, see the visualize functions add_*, where * = (‘rectangle’,’circle’,’annulus’,’ellipse’,’points’). (These docstrings are under construction!)
- Overlays (informational):
Informational overlays supported by this function include coordinate axes (cartesian, polar-elliptical, or r-theta) and scalebars. These are added by passing the appropriate input argument a dictionary of the desired parameters, as with geometric overlays. However, there are two key differences between these overlays and the geometric overlays. First, informational overlays (coordinate systems and scalebars) require information about the plot - e.g. the position of the origin, the pixel sizes, the pixel units, any elliptical distortions, etc. The easiest way to pass this information is by pass a Calibration object containing this info to
show
as the keywordcalibration
. Second, once the coordinate information has been passed, informational overlays can autoselect their own parameters, thus simply passing an empty dict to one of these parameters will add that overlay.For example:
>>> show(dp, scalebar={}, calibration=calibration)
will display the diffraction pattern
dp
with a scalebar overlaid in the bottom left corner given the pixel size and units described incalibration
, and>>> show(dp, calibration=calibration, scalebar={'length':0.5,'width':2, 'position':'ul','label':True'})
will display a more customized scalebar.
When overlaying coordinate grids, it is important to note that some relevant parameters, e.g. the position of the origin, may change by scan position. In these cases, the parameters
rx
,``ry`` must also be passed toshow
, to tell theCalibration
object where to look for the relevant parameters. For example:>>> show(dp, cartesian_grid={}, calibration=calibration, rx=2,ry=5)
will overlay a cartesian coordinate grid on the diffraction pattern at scan position (2,5). Adding
>>> show(dp, calibration=calibration, rx=2, ry=5, cartesian_grid={'label':True, 'alpha':0.7,'color':'r'})
will customize the appearance of the grid further. And
>>> show(im, calibration=calibration, cartesian_grid={}, space='R')
displays a cartesian grid over a real space image. For more details, see the documentation for the visualize functions add_*, where * = (‘scalebar’, ‘cartesian_grid’, ‘polarelliptical_grid’, ‘rtheta_grid’). (Under construction!)
- Further customization:
Most parameters accepted by a matplotlib axis will be accepted by
show
. Pass a valid matplotlib colormap or a known string indicating a colormap as the argumentcmap
to specify the colormap. Passfigsize
to specify the figure size. Etc.Further customization can be accomplished by either (1) returning the figure generated by show and then manipulating it using the normal matplotlib functions, or (2) generating a matplotlib Figure with Axes any way you like (e.g. with
plt.subplots
) and then using this function to plot inside a single one of the Axes of your choice.Option (1) is accomplished by simply passing this function
returnfig=True
. Thus:>>> fig,ax = show(ar, returnfig=True)
will now give you direct access to the figure and axes to continue to alter. Option (2) is accomplished by passing an existing figure and axis to
show
as a 2-tuple to thefigax
argument. Thus:>>> fig,(ax1,ax2) = plt.subplots(1,2) >>> show(ar, figax=(fig,ax1)) >>> show(ar, figax=(fig,ax2), hist=True)
will generate a 2-axis figure, and then plot the array
ar
as an image on the left, while plotting its histogram on the right.
- Parameters:
ar (2D array or a list of 2D arrays) – the data to plot. Normally this is a 2D array of the data. If a list of 2D arrays is passed, plots a corresponding grid of images.
figsize (2-tuple) – size of the plot
cmap (colormap) – any matplotlib cmap; default is gray
scaling (str) –
selects a scaling scheme for the intensity values. Default is none. Accepted values:
’none’: do not scale intensity values
’full’: fill entire color range with sorted intensity values
’power’: power law scaling
’log’: values where ar<=0 are set to 0
intensity_range (str) –
- method for setting clipvalues (min and max intensities).
The original name “clipvals” is now deprecated. Default is ‘ordered’. Accepted values:
’ordered’: vmin/vmax are set to fractions of the distribution of pixel values in the array, e.g. vmin=0.02 will set the minumum display value to saturate the lower 2% of pixels
’minmax’: The vmin/vmax values are np.min(ar)/np.max(r)
’absolute’: The vmin/vmax values are set to the values of the vmin,vmax arguments received by this function
- ’std’: The vmin/vmax values are
np.median(ar) -/+ N*np.std(ar)
, and N is this functions min,max vals.
- ’std’: The vmin/vmax values are
’centered’: The vmin/vmax values are set to
c -/+ m
, where by default ‘c’ is zero and m is the max(abs(ar-c), or the two params can be user specified using the kwargs vmin/vmax -> c/m.
vmin (number) – min intensity, behavior depends on clipvals
vmax (number) – max intensity, behavior depends on clipvals
min – alias’ for vmin,vmax, throws deprecation warning
max – alias’ for vmin,vmax, throws deprecation warning
power (number) – specifies the scaling power
power_offset (bool) – If true, image has min value subtracted before power scaling
ticks (bool) – Turn outer tick marks on or off
bordercolor (color or None) – if not None, add a border of this color. The color can be anything matplotlib recognizes as a color.
borderwidth (number) –
returnfig (bool) – if True, the function returns the tuple (figure,axis)
figax (None or 2-tuple) – controls which matplotlib Axes object draws the image. If None, generates a new figure with a single Axes instance. Otherwise, ax must be a 2-tuple containing the matplotlib class instances (Figure,Axes), with ar then plotted in the specified Axes instance.
hist (bool) – if True, instead of plotting a 2D image in ax, plots a histogram of the intensity values of ar, after any scaling this function has performed. Plots the clipvals as dashed vertical lines
n_bins (int) – number of hist bins
mask (None or boolean array) – if not None, must have the same shape as ‘ar’. Wherever mask==True, plot the pixel normally, and where
mask==False
, pixel values are set to mask_color. If hist==True, ignore these values in the histogram. Ifmask_alpha
is specified, the mask is blended with the array underneath, with 0 yielding an opaque mask and 1 yielding a fully transparent mask. Ifmask_color
is set to'empty'
instead of a matplotlib.color, nothing is done to pixels wheremask==False
, allowing overlaying multiple arrays in different regions of an image by invoking the ``figax` kwarg over multiple calls to showmask_color (color) – see ‘mask’
mask_alpha (float) – see ‘mask’
masked_intensity_range (bool) – controls if masked pixel values are included when determining the display value range; False indicates that all pixel values will be used to determine the intensity range, True indicates only unmasked pixels will be used
scalebar (None or dict or Bool) – if None, and a DiffractionSlice or RealSlice with calibrations is passed, adds a scalebar. If scalebar is not displaying the proper calibration, check .calibration pixel_size and pixel_units. If None and an array is passed, does not add a scalebar. If a dict is passed, it is propagated to the add_scalebar function which will attempt to use it to overlay a scalebar. If True, uses calibraiton or pixelsize/pixelunits for scalebar. If False, no scalebar is added.
show_fft (bool) – if True, plots 2D-fft of array
show_cbar (bool) – if True, adds cbar
**kwargs – any keywords accepted by matplotlib’s ax.matshow()
- Returns:
if returnfig==False (default), the figure is plotted and nothing is returned. if returnfig==True, return the figure and the axis.
- py4DSTEM.visualize.vis_special.show_amorphous_ring_fit(dp, fitradii, p_dsg, N=12, cmap=('gray', 'gray'), fitborder=True, fitbordercolor='k', fitborderlw=0.5, scaling='log', ellipse=False, ellipse_color='r', ellipse_alpha=0.7, ellipse_lw=2, returnfig=False, **kwargs)
Display a diffraction pattern with a fit to its amorphous ring, interleaving the data and the fit in a pinwheel pattern.
- Parameters:
dp (array) – the diffraction pattern
fitradii (2-tuple of numbers) – the min/max distances of the fitting annulus
p_dsg (11-tuple) – the fit parameters to the double-sided gaussian function returned by fit_ellipse_amorphous_ring
N (int) – the number of pinwheel sections
cmap (colormap or 2-tuple of colormaps) – if passed a single cmap, uses this colormap for both the data and the fit; if passed a 2-tuple of cmaps, uses the first for the data and the second for the fit
fitborder (bool) – if True, plots a border line around the fit data
fitbordercolor (color) – color of the fitborder
fitborderlw (number) – linewidth of the fitborder
scaling (str) – the normal scaling param – see docstring for visualize.show
ellipse (bool) – if True, overlay an ellipse
returnfig (bool) – if True, returns the figure
- py4DSTEM.visualize.vis_special.show_class_BPs(ar, x, y, s, s2, color='r', color2='y', **kwargs)
words
- py4DSTEM.visualize.vis_special.show_class_BPs_grid(ar, H, W, x, y, get_s, s2, color='r', color2='y', returnfig=False, axsize=(6, 6), titlesize=0, get_bordercolor=None, **kwargs)
words
- py4DSTEM.visualize.vis_special.show_complex(ar_complex, vmin=None, vmax=None, power=None, chroma_boost=1, cbar=True, scalebar=False, pixelunits='pixels', pixelsize=1, returnfig=False, **kwargs)
Function to plot complex arrays
- Parameters:
ar_complex (2D array) – complex array to be plotted. If ar_complex is list of complex arrarys such as [array1, array2], then arrays are horizonally plotted in one figure
vmin (float, optional) – minimum absolute value
vmax (float, optional) – maximum absolute value if None, vmin/vmax are set to fractions of the distribution of pixel values in the array, e.g. vmin=0.02 will set the minumum display value to saturate the lower 2% of pixels
power (float,optional) – power to raise amplitude to
chroma_boost (float) – boosts chroma for higher-contrast (~1-2.25)
cbar (bool, optional) – if True, include color bar
scalebar (bool, optional) – if True, adds scale bar
pixelunits (str, optional) – units for scalebar
pixelsize (float, optional) – size of one pixel in pixelunits for scalebar
returnfig (bool, optional) – if True, the function returns the tuple (figure,axis)
- Returns:
if returnfig==False (default), the figure is plotted and nothing is returned. if returnfig==True, return the figure and the axis.
- py4DSTEM.visualize.vis_special.show_elliptical_fit(ar, fitradii, p_ellipse, fill=True, color_ann='y', color_ell='r', alpha_ann=0.2, alpha_ell=0.7, linewidth_ann=2, linewidth_ell=2, returnfig=False, **kwargs)
Plots an elliptical curve over its annular fit region.
- Parameters:
center (2-tuple) – the center
fitradii (2-tuple of numbers) – the annulus inner and outer fit radii
p_ellipse (5-tuple) – the parameters of the fit ellipse, (qx0,qy0,a,b,theta). See the module docstring for utils.elliptical_coords for more details.
fill (bool) – if True, fills in the annular fitting region, else shows only inner/outer edges
color_ann (color) – annulus color
color_ell (color) – ellipse color
alpha_ann – transparency for the annulus
alpha_ell – transparency forn the fit ellipse
linewidth_ann –
linewidth_ell –
- py4DSTEM.visualize.vis_special.show_image_grid(get_ar, H, W, axsize=(6, 6), returnfig=False, figax=None, title=None, title_index=False, suptitle=None, get_bordercolor=None, get_x=None, get_y=None, get_pointcolors=None, get_s=None, open_circles=False, **kwargs)
Displays a set of images in a grid.
The images are specified by some function get_ar(i), which returns an image for values of some integer index i. The values of i passed to get_ar are 0 through HW-1.
To display the first 4 two-dimensional slices of some 3D array ar some 3D array ar, you can do
>>> show_image_grid(lambda i:ar[:,:,i], H=2, W=2)
Its also possible to add colored borders, or overlaid points, using similar functions to get_ar, i.e. functions which return the color or set of points of interest as a function of index i, which must be defined in the range [0,HW-1].
- Accepts:
- get_ar a function which returns a 2D array when passed
the integers 0 through HW-1
H,W integers, the dimensions of the grid axsize the size of each image figax controls which matplotlib Axes object draws the image.
If None, generates a new figure with a single Axes instance. Otherwise, ax must be a 2-tuple containing the matplotlib class instances (Figure,Axes), with ar then plotted in the specified Axes instance.
- title if title is sting, then prints title as suptitle. If a suptitle is also provided,
the suptitle is printed insead. if title is a list of strings (ex: [‘title 1’,’title 2’]), each array has corresponding title in list.
title_index if True, prints the index i passed to get_ar over each image suptitle string, suptitle on plot get_bordercolor
if not None, should be a function defined over the same i as get_ar, and which returns a valid matplotlib color for each i. Adds a colored bounding box about each image. E.g. if colors is an array of colors:
>>> show_image_grid(lambda i:ar[:,:,i],H=2,W=2, get_bordercolor=lambda i:colors[i])
- get_x,get_y functions which returns sets of x/y positions
as a function of index i
- get_s function which returns a set of point sizes
as a function of index i
- get_pointcolors a function which returns a color or list of colors
as a function of index i
- Returns:
if returnfig==false (default), the figure is plotted and nothing is returned. if returnfig==false, the figure and its one axis are returned, and can be further edited.
- py4DSTEM.visualize.vis_special.show_kernel(kernel, R, L, W, figsize=(12, 6), returnfig=False, **kwargs)
Plots, side by side, the probe kernel and its line profile. R is the kernel plot’s window size. L and W are the length and width of the lineprofile.
- py4DSTEM.visualize.vis_special.show_max_peak_spacing(ar, spacing, braggdirections, color='g', lw=2, returnfig=False, **kwargs)
Show a circle of radius spacing about each Bragg direction
- py4DSTEM.visualize.vis_special.show_origin_fit(data)
Show the measured, fit, and residuals of the origin positions.
- Parameters:
data (DataCube or Calibration or (3,2) – ((qx0_meas,qy0_meas),(qx0_fit,qy0_fit),(qx0_residuals,qy0_residuals))
- py4DSTEM.visualize.vis_special.show_origin_meas(data)
Show the measured positions of the origin.
- Parameters:
data (DataCube or Calibration or 2-tuple of arrays (qx0,qy0)) –
- py4DSTEM.visualize.vis_special.show_pointlabels(ar, x, y, color='lightblue', size=20, alpha=1, returnfig=False, **kwargs)
Show enumerated index labels for a set of points
- py4DSTEM.visualize.vis_special.show_qprofile(q, intensity, ymax=None, figsize=(12, 4), returnfig=False, color='k', xlabel='q (pixels)', ylabel='Intensity (A.U.)', labelsize=16, ticklabelsize=14, grid=True, label=None, **kwargs)
Plots a diffraction space radial profile. Params:
q (1D array) the diffraction coordinate / x-axis intensity (1D array) the y-axis values ymax (number) max value for the yaxis color (matplotlib color) profile color xlabel (str) ylabel labelsize size of x and y labels ticklabelsize grid True or False label a legend label for the plotted curve
- py4DSTEM.visualize.vis_special.show_selected_dps(datacube, positions, im, bragg_pos=None, colors=None, HW=None, figsize_im=(6, 6), figsize_dp=(4, 4), **kwargs)
Shows two plots: first, a real space image overlaid with colored dots at the specified positions; second, a grid of diffraction patterns corresponding to these scan positions.
- Parameters:
datacube (DataCube) –
positions (len N list or tuple of 2-tuples) – the scan positions
im (2d array) – a real space image
bragg_pos (len N list of pointlistarrays) – bragg disk positions for each position. if passed, overlays the disk positions, and supresses plot of the real space image
colors (len N list of colors or None) –
HW (2-tuple of ints) – diffraction pattern grid shape
figsize_im (2-tuple) – size of the image figure
figsize_dp (2-tuple) – size of each diffraction pattern panel
**kwargs (dict) – arguments passed to visualize.show for the diffraction patterns. Default is scaling=’log’
- py4DSTEM.visualize.vis_special.show_voronoi(ar, x, y, color_points='r', color_lines='w', max_dist=None, returnfig=False, **kwargs)
words