sidpy/viz/plot_utils/image.py
def plot_map(axis, img, show_xy_ticks=True, show_cbar=True, x_vec=None, y_vec=None,
             num_ticks=4, stdevs=None, cbar_label=None, tick_font_size=None, infer_aspect=False, **kwargs):
    """
    Plots an image within the given axis with a color bar + label and appropriate X, Y tick labels.
    This is particularly useful to get readily interpretable plots for papers

    Parameters
    ----------
    axis : matplotlib.axes.Axes object
        Axis to plot this image onto
    img : 2D numpy array with real values
        Data for the image plot
    show_xy_ticks : bool, Optional, default = None, shown unedited
        Whether or not to show X, Y ticks
    show_cbar : bool, optional, default = True
        Whether or not to show the colorbar
    x_vec : 1-D array-like or Number, optional
        if an array-like is provided, these will be used for the tick values on the X axis
        if a Number is provided, this will serve as an extent for tick values in the X axis.
        For example x_vec=1.5 would cause the x tick labels to range from 0 to 1.5
    y_vec : 1-D array-like or Number, optional
        if an array-like is provided - these will be used for the tick values on the Y axis
        if a Number is provided, this will serve as an extent for tick values in the Y axis.
        For example y_vec=225 would cause the y tick labels to range from 0 to 225
    num_ticks : unsigned int, optional, default = 4
        Number of tick marks on the X and Y axes
    stdevs : unsigned int (Optional. Default = None)
        Number of standard deviations to consider for plotting.  If None, full range is plotted.
    cbar_label : str, optional, default = None
        Labels for the colorbar. Use this for something like quantity (units)
    tick_font_size : unsigned int, optional, default = None
        Font size to apply to x, y, colorbar ticks and colorbar label
    infer_aspect : bool, Optional. Default = False
        Whether or not to adjust the aspect ratio of the image based on the provided x_vec and y_vec
        The values of x_vec and y_vec will be assumed to have the same units.
    kwargs : dictionary
        Anything else that will be passed on to matplotlib.pyplot.imshow

    Returns
    -------
    im_handle : handle to image plot
        handle to image plot
    cbar : handle to color bar
        handle to color bar

    Note
    ----
    The origin of the image will be set to the lower left corner. Use the kwarg 'origin' to change this

    """
    if not isinstance(axis, mpl.axes.Axes):
        raise TypeError('axis must be a matplotlib.axes.Axes object')
    if not isinstance(img, (np.ndarray, da.core.Array)):
        raise TypeError('img should be a numpy array')
    if not img.ndim == 2:
        raise ValueError('img should be a 2D array')
    if not isinstance(show_xy_ticks, bool):
        raise TypeError('show_xy_ticks should be a boolean value')
    if not isinstance(show_cbar, bool):
        raise TypeError('show_cbar should be a boolean value')
    # checks for x_vec and y_vec are done below
    if num_ticks is not None:
        if not isinstance(num_ticks, int):
            raise TypeError('num_ticks should be a whole number')
        if num_ticks < 2:
            raise ValueError('num_ticks should be at least 2')
    if tick_font_size is not None:
        if not isinstance(tick_font_size, Number):
            raise TypeError('tick_font_size must be a whole number')
        if tick_font_size < 0:
            raise ValueError('tick_font_size must be a whole number')
    if stdevs is not None:
        if not isinstance(stdevs, Number):
            raise TypeError('stdevs should be a Number')
        data_mean = np.mean(img)
        data_std = np.std(img)
        kwargs.update({'clim': [data_mean - stdevs * data_std, data_mean + stdevs * data_std]})

    kwargs.update({'origin': kwargs.pop('origin', 'lower')})

    if show_cbar:
        
        if np.isnan(img).any():
            _img = img[np.where(~np.isnan(img))]
            y_exp = get_exponent(np.squeeze(_img))
        else:
            y_exp = get_exponent(np.squeeze(img))
        z_suffix = ''
        if y_exp < -2 or y_exp > 3:
            img = np.squeeze(img) / 10 ** y_exp
            z_suffix = ' x $10^{' + str(y_exp) + '}$'

    assert isinstance(show_xy_ticks, bool)

    ########################################################################################################

    def set_ticks_for_axis(tick_vals, is_x):
        if is_x:
            tick_vals_var_name = 'x_vec'
            tick_set_func = axis.set_xticks
            tick_labs_set_func = axis.set_xticklabels
        else:
            tick_vals_var_name = 'y_vec'
            tick_set_func = axis.set_yticks
            tick_labs_set_func = axis.set_yticklabels

        img_axis = int(is_x)
        img_size = img.shape[img_axis]
        chosen_ticks = np.linspace(0, img_size - 1, num_ticks, dtype=int)

        if tick_vals is not None:
            if isinstance(tick_vals, (int, float)):
                if tick_vals > 0.01:
                    tick_labs = [str(np.round(ind * tick_vals / img_size, 2)) for ind in chosen_ticks]
                else:
                    tick_labs = ['{0:.1E}'.format(ind * tick_vals / img_size) for ind in chosen_ticks]
                    print(tick_labs)
                tick_vals = np.linspace(0, tick_vals, img_size)
            else:
                if not isinstance(tick_vals, (np.ndarray, list, tuple, range, da.core.Array)) or \
                        len(tick_vals) != img_size:
                    raise ValueError(
                        '{} should be array-like with shape equal to axis {} of img'.format(tick_vals_var_name,
                                                                                            img_axis))
                if np.max(tick_vals) > 0.01:
                    tick_labs = [str(np.round(tick_vals[ind], 2)) for ind in chosen_ticks]
                else:
                    tick_labs = ['{0:.1E}'.format(tick_vals[ind]) for ind in chosen_ticks]
        else:
            tick_labs = [str(ind) for ind in chosen_ticks]

        tick_set_func(chosen_ticks)
        tick_labs_set_func(tick_labs)

        if tick_font_size is not None:
            set_tick_font_size(axis, tick_font_size)

        return tick_vals

    ########################################################################################################

    if show_xy_ticks is True or x_vec is not None:
        x_vec = set_ticks_for_axis(x_vec, True)
    else:
        axis.set_xticks([])

    if show_xy_ticks is True or y_vec is not None:
        y_vec = set_ticks_for_axis(y_vec, False)
    else:
        axis.set_yticks([])

    if infer_aspect:
        # Aspect ratio determined by this function will take precedence.
        _ = kwargs.pop('infer_aspect', None)

        """
        At this stage, if x_vec and y_vec are not None, they should be arrays.
        
        This will be very useful when one dimension is coarsely sampled while another is finely sampled
        and we want to visualize the image with the physically correct aspect ratio.
        This CANNOT be performed automatically due to potentially incompatible units which are unknown to this func.
        """

        if x_vec is not None or y_vec is not None:
            x_range = x_vec.max() - x_vec.min()
            y_range = y_vec.max() - y_vec.min()
            kwargs.update({'aspect': (y_range / x_range) * (img.shape[1] / img.shape[0])})

    im_handle = axis.imshow(img, **kwargs)

    cbar = None
    if not isinstance(show_cbar, bool):
        show_cbar = False

    if show_cbar:
        cbar = plt.colorbar(im_handle, ax=axis, orientation='vertical',
                            fraction=0.046, pad=0.04, use_gridspec=True)
        # cbar = axis.cbar_axes[count].colorbar(im_handle)

        if cbar_label is not None:
            if not isinstance(cbar_label, (str, unicode)):
                raise TypeError('cbar_label should be a string')

            if tick_font_size is not None:
                cbar.set_label(cbar_label + z_suffix)
            else:
                cbar.set_label(cbar_label + z_suffix, fontsize=tick_font_size)
        else:
            if z_suffix != '':
                cbar.set_label(z_suffix)

        if tick_font_size is not None:
            cbar.ax.tick_params(labelsize=tick_font_size)
    return im_handle, cbar

    Plots an image within the given axis with a color bar + label and appropriate X, Y tick labels.
    This is particularly useful to get readily interpretable plots for papers

    Parameters
    ----------
    axis : matplotlib.axes.Axes object
        Axis to plot this image onto
    img : 2D numpy array with real values
        Data for the image plot
    show_xy_ticks : bool, Optional, default = None, shown unedited
        Whether or not to show X, Y ticks
    show_cbar : bool, optional, default = True
        Whether or not to show the colorbar
    x_vec : 1-D array-like or Number, optional
        if an array-like is provided, these will be used for the tick values on the X axis
        if a Number is provided, this will serve as an extent for tick values in the X axis.
        For example x_vec=1.5 would cause the x tick labels to range from 0 to 1.5
    y_vec : 1-D array-like or Number, optional
        if an array-like is provided - these will be used for the tick values on the Y axis
        if a Number is provided, this will serve as an extent for tick values in the Y axis.
        For example y_vec=225 would cause the y tick labels to range from 0 to 225
    num_ticks : unsigned int, optional, default = 4
        Number of tick marks on the X and Y axes
    stdevs : unsigned int (Optional. Default = None)
        Number of standard deviations to consider for plotting.  If None, full range is plotted.
    cbar_label : str, optional, default = None
        Labels for the colorbar. Use this for something like quantity (units)
    tick_font_size : unsigned int, optional, default = None
        Font size to apply to x, y, colorbar ticks and colorbar label
    infer_aspect : bool, Optional. Default = False
        Whether or not to adjust the aspect ratio of the image based on the provided x_vec and y_vec
        The values of x_vec and y_vec will be assumed to have the same units.
    kwargs : dictionary
        Anything else that will be passed on to matplotlib.pyplot.imshow

    Returns
    -------
    im_handle : handle to image plot
        handle to image plot
    cbar : handle to color bar
        handle to color bar

    Note
    ----
    The origin of the image will be set to the lower left corner. Use the kwarg 'origin' to change this

    
Plots an image within the given axis with a color bar + label and appropriate X, Y tick labels.
This is particularly useful to get readily interpretable plots for papers

Parameters



Returns

im_handle : handle to image plot
handle to image plot
cbar : handle to color bar
handle to color bar

Note

The origin of the image will be set to the lower left corner. Use the kwarg 'origin' to change this
Plots an image within the given axis with a color bar + label and appropriate X Y tick labels . This is particularly useful to get readily interpretable plots for papers Parameters Returns im_handle : handle to image plot handle to image plot cbar : handle to color bar handle to color bar Note The origin of the image will be set to the lower left corner . Use the kwarg ' origin ' to change this
def plot_map(axis, img, show_xy_ticks=True, show_cbar=True, x_vec=None, y_vec=None,
             num_ticks=4, stdevs=None, cbar_label=None, tick_font_size=None, infer_aspect=False, **kwargs):
    if not isinstance(axis, mpl.axes.Axes):
        raise TypeError('axis must be a matplotlib.axes.Axes object')
    if not isinstance(img, (np.ndarray, da.core.Array)):
        raise TypeError('img should be a numpy array')
    if not img.ndim == 2:
        raise ValueError('img should be a 2D array')
    if not isinstance(show_xy_ticks, bool):
        raise TypeError('show_xy_ticks should be a boolean value')
    if not isinstance(show_cbar, bool):
        raise TypeError('show_cbar should be a boolean value')
    if num_ticks is not None:
        if not isinstance(num_ticks, int):
            raise TypeError('num_ticks should be a whole number')
        if num_ticks < 2:
            raise ValueError('num_ticks should be at least 2')
    if tick_font_size is not None:
        if not isinstance(tick_font_size, Number):
            raise TypeError('tick_font_size must be a whole number')
        if tick_font_size < 0:
            raise ValueError('tick_font_size must be a whole number')
    if stdevs is not None:
        if not isinstance(stdevs, Number):
            raise TypeError('stdevs should be a Number')
        data_mean = np.mean(img)
        data_std = np.std(img)
        kwargs.update({'clim': [data_mean - stdevs * data_std, data_mean + stdevs * data_std]})
    kwargs.update({'origin': kwargs.pop('origin', 'lower')})
    if show_cbar:
        if np.isnan(img).any():
            _img = img[np.where(~np.isnan(img))]
            y_exp = get_exponent(np.squeeze(_img))
        else:
            y_exp = get_exponent(np.squeeze(img))
        z_suffix = ''
        if y_exp < -2 or y_exp > 3:
            img = np.squeeze(img) / 10 ** y_exp
            z_suffix = ' x $10^{' + str(y_exp) + '}$'
    assert isinstance(show_xy_ticks, bool)
    def set_ticks_for_axis(tick_vals, is_x):
        if is_x:
            tick_vals_var_name = 'x_vec'
            tick_set_func = axis.set_xticks
            tick_labs_set_func = axis.set_xticklabels
        else:
            tick_vals_var_name = 'y_vec'
            tick_set_func = axis.set_yticks
            tick_labs_set_func = axis.set_yticklabels
        img_axis = int(is_x)
        img_size = img.shape[img_axis]
        chosen_ticks = np.linspace(0, img_size - 1, num_ticks, dtype=int)
        if tick_vals is not None:
            if isinstance(tick_vals, (int, float)):
                if tick_vals > 0.01:
                    tick_labs = [str(np.round(ind * tick_vals / img_size, 2)) for ind in chosen_ticks]
                else:
                    tick_labs = ['{0:.1E}'.format(ind * tick_vals / img_size) for ind in chosen_ticks]
                    print(tick_labs)
                tick_vals = np.linspace(0, tick_vals, img_size)
            else:
                if not isinstance(tick_vals, (np.ndarray, list, tuple, range, da.core.Array)) or \
                        len(tick_vals) != img_size:
                    raise ValueError(
                        '{} should be array-like with shape equal to axis {} of img'.format(tick_vals_var_name,
                                                                                            img_axis))
                if np.max(tick_vals) > 0.01:
                    tick_labs = [str(np.round(tick_vals[ind], 2)) for ind in chosen_ticks]
                else:
                    tick_labs = ['{0:.1E}'.format(tick_vals[ind]) for ind in chosen_ticks]
        else:
            tick_labs = [str(ind) for ind in chosen_ticks]
        tick_set_func(chosen_ticks)
        tick_labs_set_func(tick_labs)
        if tick_font_size is not None:
            set_tick_font_size(axis, tick_font_size)
        return tick_vals
    if show_xy_ticks is True or x_vec is not None:
        x_vec = set_ticks_for_axis(x_vec, True)
    else:
        axis.set_xticks([])
    if show_xy_ticks is True or y_vec is not None:
        y_vec = set_ticks_for_axis(y_vec, False)
    else:
        axis.set_yticks([])
    if infer_aspect:
        _ = kwargs.pop('infer_aspect', None)
        if x_vec is not None or y_vec is not None:
            x_range = x_vec.max() - x_vec.min()
            y_range = y_vec.max() - y_vec.min()
            kwargs.update({'aspect': (y_range / x_range) * (img.shape[1] / img.shape[0])})
    im_handle = axis.imshow(img, **kwargs)
    cbar = None
    if not isinstance(show_cbar, bool):
        show_cbar = False
    if show_cbar:
        cbar = plt.colorbar(im_handle, ax=axis, orientation='vertical',
                            fraction=0.046, pad=0.04, use_gridspec=True)
        if cbar_label is not None:
            if not isinstance(cbar_label, (str, unicode)):
                raise TypeError('cbar_label should be a string')
            if tick_font_size is not None:
                cbar.set_label(cbar_label + z_suffix)
            else:
                cbar.set_label(cbar_label + z_suffix, fontsize=tick_font_size)
        else:
            if z_suffix != '':
                cbar.set_label(z_suffix)
        if tick_font_size is not None:
            cbar.ax.tick_params(labelsize=tick_font_size)
    return im_handle, cbar
def plot_map ( axis , img , show_xy_ticks = True , show_cbar = True , x_vec = None , y_vec = None , num_ticks = 4 , stdevs = None , cbar_label = None , tick_font_size = None , infer_aspect = False , ** kwargs ) : if not isinstance ( axis , mpl . axes . Axes ) : raise TypeError ( 'axis must be a matplotlib.axes.Axes object' ) if not isinstance ( img , ( np . ndarray , da . core . Array ) ) : raise TypeError ( 'img should be a numpy array' ) if not img . ndim == 2 : raise ValueError ( 'img should be a 2D array' ) if not isinstance ( show_xy_ticks , bool ) : raise TypeError ( 'show_xy_ticks should be a boolean value' ) if not isinstance ( show_cbar , bool ) : raise TypeError ( 'show_cbar should be a boolean value' ) if num_ticks is not None : if not isinstance ( num_ticks , int ) : raise TypeError ( 'num_ticks should be a whole number' ) if num_ticks < 2 : raise ValueError ( 'num_ticks should be at least 2' ) if tick_font_size is not None : if not isinstance ( tick_font_size , Number ) : raise TypeError ( 'tick_font_size must be a whole number' ) if tick_font_size < 0 : raise ValueError ( 'tick_font_size must be a whole number' ) if stdevs is not None : if not isinstance ( stdevs , Number ) : raise TypeError ( 'stdevs should be a Number' ) data_mean = np . mean ( img ) data_std = np . std ( img ) kwargs . update ( { 'clim' : [ data_mean - stdevs * data_std , data_mean + stdevs * data_std ] } ) kwargs . update ( { 'origin' : kwargs . pop ( 'origin' , 'lower' ) } ) if show_cbar : if np . isnan ( img ) . any ( ) : _img = img [ np . where ( ~ np . isnan ( img ) ) ] y_exp = get_exponent ( np . squeeze ( _img ) ) else : y_exp = get_exponent ( np . squeeze ( img ) ) z_suffix = '' if y_exp < - 2 or y_exp > 3 : img = np . squeeze ( img ) / 10 ** y_exp z_suffix = ' x $10^{' + str ( y_exp ) + '}$' assert isinstance ( show_xy_ticks , bool ) def set_ticks_for_axis ( tick_vals , is_x ) : if is_x : tick_vals_var_name = 'x_vec' tick_set_func = axis . set_xticks tick_labs_set_func = axis . set_xticklabels else : tick_vals_var_name = 'y_vec' tick_set_func = axis . set_yticks tick_labs_set_func = axis . set_yticklabels img_axis = int ( is_x ) img_size = img . shape [ img_axis ] chosen_ticks = np . linspace ( 0 , img_size - 1 , num_ticks , dtype = int ) if tick_vals is not None : if isinstance ( tick_vals , ( int , float ) ) : if tick_vals > 0.01 : tick_labs = [ str ( np . round ( ind * tick_vals / img_size , 2 ) ) for ind in chosen_ticks ] else : tick_labs = [ '{0:.1E}' . format ( ind * tick_vals / img_size ) for ind in chosen_ticks ] print ( tick_labs ) tick_vals = np . linspace ( 0 , tick_vals , img_size ) else : if not isinstance ( tick_vals , ( np . ndarray , list , tuple , range , da . core . Array ) ) or len ( tick_vals ) != img_size : raise ValueError ( '{} should be array-like with shape equal to axis {} of img' . format ( tick_vals_var_name , img_axis ) ) if np . max ( tick_vals ) > 0.01 : tick_labs = [ str ( np . round ( tick_vals [ ind ] , 2 ) ) for ind in chosen_ticks ] else : tick_labs = [ '{0:.1E}' . format ( tick_vals [ ind ] ) for ind in chosen_ticks ] else : tick_labs = [ str ( ind ) for ind in chosen_ticks ] tick_set_func ( chosen_ticks ) tick_labs_set_func ( tick_labs ) if tick_font_size is not None : set_tick_font_size ( axis , tick_font_size ) return tick_vals if show_xy_ticks is True or x_vec is not None : x_vec = set_ticks_for_axis ( x_vec , True ) else : axis . set_xticks ( [ ] ) if show_xy_ticks is True or y_vec is not None : y_vec = set_ticks_for_axis ( y_vec , False ) else : axis . set_yticks ( [ ] ) if infer_aspect : _ = kwargs . pop ( 'infer_aspect' , None ) """
        At this stage, if x_vec and y_vec are not None, they should be arrays.
        
        This will be very useful when one dimension is coarsely sampled while another is finely sampled
        and we want to visualize the image with the physically correct aspect ratio.
        This CANNOT be performed automatically due to potentially incompatible units which are unknown to this func.
        """ if x_vec is not None or y_vec is not None : x_range = x_vec . max ( ) - x_vec . min ( ) y_range = y_vec . max ( ) - y_vec . min ( ) kwargs . update ( { 'aspect' : ( y_range / x_range ) * ( img . shape [ 1 ] / img . shape [ 0 ] ) } ) im_handle = axis . imshow ( img , ** kwargs ) cbar = None if not isinstance ( show_cbar , bool ) : show_cbar = False if show_cbar : cbar = plt . colorbar ( im_handle , ax = axis , orientation = 'vertical' , fraction = 0.046 , pad = 0.04 , use_gridspec = True ) if cbar_label is not None : if not isinstance ( cbar_label , ( str , unicode ) ) : raise TypeError ( 'cbar_label should be a string' ) if tick_font_size is not None : cbar . set_label ( cbar_label + z_suffix ) else : cbar . set_label ( cbar_label + z_suffix , fontsize = tick_font_size ) else : if z_suffix != '' : cbar . set_label ( z_suffix ) if tick_font_size is not None : cbar . ax . tick_params ( labelsize = tick_font_size ) return im_handle , cbar
Plots an image within the given axis with a color bar + label and appropriate X, Y tick labels.
Plots an image within the given axis with a color bar + label and appropriate X Y tick labels .
"""
    Plots an image within the given axis with a color bar + label and appropriate X, Y tick labels.
    This is particularly useful to get readily interpretable plots for papers

    Parameters
    ----------
    axis : matplotlib.axes.Axes object
        Axis to plot this image onto
    img : 2D numpy array with real values
        Data for the image plot
    show_xy_ticks : bool, Optional, default = None, shown unedited
        Whether or not to show X, Y ticks
    show_cbar : bool, optional, default = True
        Whether or not to show the colorbar
    x_vec : 1-D array-like or Number, optional
        if an array-like is provided, these will be used for the tick values on the X axis
        if a Number is provided, this will serve as an extent for tick values in the X axis.
        For example x_vec=1.5 would cause the x tick labels to range from 0 to 1.5
    y_vec : 1-D array-like or Number, optional
        if an array-like is provided - these will be used for the tick values on the Y axis
        if a Number is provided, this will serve as an extent for tick values in the Y axis.
        For example y_vec=225 would cause the y tick labels to range from 0 to 225
    num_ticks : unsigned int, optional, default = 4
        Number of tick marks on the X and Y axes
    stdevs : unsigned int (Optional. Default = None)
        Number of standard deviations to consider for plotting.  If None, full range is plotted.
    cbar_label : str, optional, default = None
        Labels for the colorbar. Use this for something like quantity (units)
    tick_font_size : unsigned int, optional, default = None
        Font size to apply to x, y, colorbar ticks and colorbar label
    infer_aspect : bool, Optional. Default = False
        Whether or not to adjust the aspect ratio of the image based on the provided x_vec and y_vec
        The values of x_vec and y_vec will be assumed to have the same units.
    kwargs : dictionary
        Anything else that will be passed on to matplotlib.pyplot.imshow

    Returns
    -------
    im_handle : handle to image plot
        handle to image plot
    cbar : handle to color bar
        handle to color bar

    Note
    ----
    The origin of the image will be set to the lower left corner. Use the kwarg 'origin' to change this

    """ # checks for x_vec and y_vec are done below ######################################################################################################## ######################################################################################################## # Aspect ratio determined by this function will take precedence. """
        At this stage, if x_vec and y_vec are not None, they should be arrays.
        
        This will be very useful when one dimension is coarsely sampled while another is finely sampled
        and we want to visualize the image with the physically correct aspect ratio.
        This CANNOT be performed automatically due to potentially incompatible units which are unknown to this func.
        """ # cbar = axis.cbar_axes[count].colorbar(im_handle)
axis
img
show_xy_ticks
show_cbar
x_vec
y_vec
num_ticks
stdevs
cbar_label
tick_font_size
infer_aspect