code: def plot_epochs_image(
      epochs,
      picks=None,
      sigma=0.0,
      vmin=None,
      vmax=None,
      colorbar=True,
      order=None,
      show=True,
      units=None,
      scalings=None,
      cmap=None,
      fig=None,
      axes=None,
      overlay_times=None,
      combine=None,
      group_by=None,
      evoked=True,
      ts_args=None,
      title=None,
      clear=False,
  ):
      """Plot Event Related Potential / Fields image.
  
      Parameters
      ----------
      epochs : instance of Epochs
          The epochs.
      %(picks_good_data)s
          ``picks`` interacts with ``group_by`` and ``combine`` to determine the
          number of figures generated; see Notes.
      sigma : float
          The standard deviation of a Gaussian smoothing window applied along
          the epochs axis of the image. If 0, no smoothing is applied.
          Defaults to 0.
      vmin : None | float | callable
          The min value in the image (and the ER[P/F]). The unit is µV for
          EEG channels, fT for magnetometers and fT/cm for gradiometers.
          If vmin is None and multiple plots are returned, the limit is
          equalized within channel types.
          Hint: to specify the lower limit of the data, use
          ``vmin=lambda data: data.min()``.
      vmax : None | float | callable
          The max value in the image (and the ER[P/F]). The unit is µV for
          EEG channels, fT for magnetometers and fT/cm for gradiometers.
          If vmin is None and multiple plots are returned, the limit is
          equalized within channel types.
      colorbar : bool
          Display or not a colorbar.
      order : None | array of int | callable
          If not ``None``, order is used to reorder the epochs along the y-axis
          of the image. If it is an array of :class:`int`, its length should
          match the number of good epochs. If it is a callable it should accept
          two positional parameters (``times`` and ``data``, where
          ``data.shape == (len(good_epochs), len(times))``) and return an
          :class:`array <numpy.ndarray>` of indices that will sort ``data`` along
          its first axis.
      show : bool
          Show figure if True.
      units : dict | None
          The units of the channel types used for axes labels. If None,
          defaults to ``units=dict(eeg='µV', grad='fT/cm', mag='fT')``.
      scalings : dict | None
          The scalings of the channel types to be applied for plotting.
          If None, defaults to ``scalings=dict(eeg=1e6, grad=1e13, mag=1e15,
          eog=1e6)``.
      cmap : None | colormap | (colormap, bool) | 'interactive'
          Colormap. If tuple, the first value indicates the colormap to use and
          the second value is a boolean defining interactivity. In interactive
          mode the colors are adjustable by clicking and dragging the colorbar
          with left and right mouse button. Left mouse button moves the scale up
          and down and right mouse button adjusts the range. Hitting space bar
          resets the scale. Up and down arrows can be used to change the
          colormap. If 'interactive', translates to ('RdBu_r', True).
          If None, "RdBu_r" is used, unless the data is all positive, in which
          case "Reds" is used.
      fig : Figure | None
          :class:`~matplotlib.figure.Figure` instance to draw the image to.
          Figure must contain the correct number of axes for drawing the epochs
          image, the evoked response, and a colorbar (depending on values of
          ``evoked`` and ``colorbar``). If ``None`` a new figure is created.
          Defaults to ``None``.
      axes : list of Axes | dict of list of Axes | None
          List of :class:`~matplotlib.axes.Axes` objects in which to draw the
          image, evoked response, and colorbar (in that order). Length of list
          must be 1, 2, or 3 (depending on values of ``colorbar`` and ``evoked``
          parameters). If a :class:`dict`, each entry must be a list of Axes
          objects with the same constraints as above. If both ``axes`` and
          ``group_by`` are dicts, their keys must match. Providing non-``None``
          values for both ``fig`` and ``axes``  results in an error. Defaults to
          ``None``.
      overlay_times : array_like, shape (n_epochs,) | None
          Times (in seconds) at which to draw a line on the corresponding row of
          the image (e.g., a reaction time associated with each epoch). Note that
          ``overlay_times`` should be ordered to correspond with the
          :class:`~mne.Epochs` object (i.e., ``overlay_times[0]`` corresponds to
          ``epochs[0]``, etc).
      %(combine)s
          If callable, the callable must accept one positional input (data of
          shape ``(n_epochs, n_channels, n_times)``) and return an
          :class:`array <numpy.ndarray>` of shape ``(n_epochs, n_times)``. For
          example::
  
              combine = lambda data: np.median(data, axis=1)
  
          If ``combine`` is ``None``, channels are combined by computing GFP,
          unless ``group_by`` is also ``None`` and ``picks`` is a list of
          specific channels (not channel types), in which case no combining is
          performed and each channel gets its own figure. See Notes for further
          details. Defaults to ``None``.
      group_by : None | dict
          Specifies which channels are aggregated into a single figure, with
          aggregation method determined by the ``combine`` parameter. If not
          ``None``, one :class:`~matplotlib.figure.Figure` is made per dict
          entry; the dict key will be used as the figure title and the dict
          values must be lists of picks (either channel names or integer indices
          of ``epochs.ch_names``). For example::
  
              group_by=dict(Left_ROI=[1, 2, 3, 4], Right_ROI=[5, 6, 7, 8])
  
          Note that within a dict entry all channels must have the same type.
          ``group_by`` interacts with ``picks`` and ``combine`` to determine the
          number of figures generated; see Notes. Defaults to ``None``.
      evoked : bool
          Draw the ER[P/F] below the image or not.
      ts_args : None | dict
          Arguments passed to a call to `~mne.viz.plot_compare_evokeds` to style
          the evoked plot below the image. Defaults to an empty dictionary,
          meaning `~mne.viz.plot_compare_evokeds` will be called with default
          parameters.
      title : None | str
          If :class:`str`, will be plotted as figure title. Otherwise, the
          title will indicate channel(s) or channel type being plotted. Defaults
          to ``None``.
      clear : bool
          Whether to clear the axes before plotting (if ``fig`` or ``axes`` are
          provided). Defaults to ``False``.
  
      Returns
      -------
      figs : list of Figure
          One figure per channel, channel type, or group, depending on values of
          ``picks``, ``group_by``, and ``combine``. See Notes.
  
      Notes
      -----
      You can control how channels are aggregated into one figure or plotted in
      separate figures through a combination of the ``picks``, ``group_by``, and
      ``combine`` parameters. If ``group_by`` is a :class:`dict`, the result is
      one :class:`~matplotlib.figure.Figure` per dictionary key (for any valid
      values of ``picks`` and ``combine``). If ``group_by`` is ``None``, the
      number and content of the figures generated depends on the values of
      ``picks`` and ``combine``, as summarized in this table:
  
      .. cssclass:: table-bordered
      .. rst-class:: midvalign
  
      +----------+----------------------------+------------+-------------------+
      | group_by | picks                      | combine    | result            |
      +==========+============================+============+===================+
      |          | None, int, list of int,    | None,      |                   |
      | dict     | ch_name, list of ch_names, | string, or | 1 figure per      |
      |          | ch_type, list of ch_types  | callable   | dict key          |
      +----------+----------------------------+------------+-------------------+
      |          | None,                      | None,      |                   |
      |          | ch_type,                   | string, or | 1 figure per      |
      |          | list of ch_types           | callable   | ch_type           |
      | None     +----------------------------+------------+-------------------+
      |          | int,                       | None       | 1 figure per pick |
      |          | ch_name,                   +------------+-------------------+
      |          | list of int,               | string or  | 1 figure          |
      |          | list of ch_names           | callable   |                   |
      +----------+----------------------------+------------+-------------------+
      """
      from ..epochs import EpochsArray
  
      _validate_type(group_by, (dict, None), "group_by")
  
      units = _handle_default("units", units)
      scalings = _handle_default("scalings", scalings)
      if set(units) != set(scalings):
          raise ValueError(
              "Scalings and units must have the same keys."
          )
  
      # is picks a channel type (or None)?
      picks, picked_types = _picks_to_idx(
          epochs.info, picks, return_kind=True
      )
      ch_types = epochs.info.get_channel_types(picks)
  
      # `combine` defaults to 'gfp' unless picks are specific channels and
      # there was no group_by passed
      combine_given = combine is not None
      if combine is None and (group_by is not None or picked_types):
          combine = "gfp"
      # convert `combine` into callable (if None or str)
      combine_func = _make_combine_callable(combine)
  
      # handle ts_args (params for the evoked time series)
      ts_args = dict() if ts_args is None else ts_args
      manual_ylims = "ylim" in ts_args
      if combine is not None:
          ts_args["show_sensors"] = False
      vlines = [0] if (epochs.times[0] < 0 < epochs.times[-1]) else []
      ts_defaults = dict(
          colors={"cond": "k"},
          title="",
          show=False,
          truncate_yaxis=False,
          truncate_xaxis=False,
          vlines=vlines,
          legend=False,
      )
      ts_defaults.update(**ts_args)
      ts_args = ts_defaults.copy()
  
      # construct a group_by dict if one wasn't supplied
      if group_by is None:
          if picked_types:
              # one fig per ch_type
              group_by = {
                  ch_type: picks[np.array(ch_types) == ch_type]
                  for ch_type in set(ch_types)
                  if ch_type in _DATA_CH_TYPES_SPLIT + ("ref_meg",)
              }
          elif combine is None:
              # one fig per pick
              group_by = {
                  epochs.ch_names[pick]: [pick] for pick in picks
              }
          else:
              # one fig to rule them all
              ch_names = np.array(epochs.ch_names)[picks].tolist()
              key = _set_title_multiple_electrodes(
                  None, combine, ch_names
              )
              group_by = {key: picks}
      else:
          group_by = deepcopy(group_by)
      # check for heterogeneous sensor type combinations / "combining" 1 channel
      for this_group, these_picks in group_by.items():
          this_ch_type = np.array(ch_types)[np.isin(picks, these_picks)]
          if len(set(this_ch_type)) > 1:
              types = ", ".join(set(this_ch_type))
              raise ValueError(
                  f'Cannot combine sensors of different types; "{this_group}" contains '
                  f"types {types}."
              )
          # now we know they're all the same type...
          group_by[this_group] = dict(
              picks=these_picks, ch_type=this_ch_type[0], title=title
          )
  
          # are they trying to combine a single channel?
          if len(these_picks) < 2 and combine_given:
              warn(
                  f'Only one channel in group "{this_group}"; cannot combine by method '
                  f'"{combine}".'
              )
  
      # check for compatible `fig` / `axes`; instantiate figs if needed; add
      # fig(s) and axes into group_by
      needs_colorbar = colorbar and (
          axes is not None or fig is not None
      )
      group_by = _validate_fig_and_axes(
          fig,
          axes,
          group_by,
          evoked,
          colorbar=needs_colorbar,
          clear=clear,
      )
      del fig, axes, needs_colorbar, clear
  
      # prepare images in advance to get consistent vmin/vmax.
      # At the same time, create a subsetted epochs object for each group
      data = epochs._get_data(on_empty="raise")
      vmin_vmax = {
          ch_type: dict(images=list(), norm=list())
          for ch_type in set(ch_types)
      }
      for this_group, this_group_dict in group_by.items():
          these_picks = this_group_dict["picks"]
          this_ch_type = this_group_dict["ch_type"]
          this_ch_info = [epochs.info["chs"][n] for n in these_picks]
          these_ch_names = np.array(epochs.info["ch_names"])[
              these_picks
          ]
          this_data = data[:, these_picks]
          # create subsetted epochs object
          this_info = create_info(
              sfreq=epochs.info["sfreq"],
              ch_names=list(these_ch_names),
              ch_types=[this_ch_type] * len(these_picks),
          )
          with this_info._unlock():
              this_info["chs"] = this_ch_info
          this_epochs = EpochsArray(
              this_data, this_info, tmin=epochs.times[0]
          )
          # apply scalings (only to image, not epochs object), combine channels
          this_image = combine_func(this_data * scalings[this_ch_type])
          # handle `order`. NB: this can potentially yield different orderings
          # in each figure!
          this_image, _overlay_times = _order_epochs(
              this_image, epochs.times, order, overlay_times
          )
          this_norm = np.all(this_image > 0)
          # apply smoothing
          if sigma > 0.0:
              this_image = gaussian_filter1d(
                  this_image, sigma=sigma, axis=0, mode="nearest"
              )
          # update the group_by and vmin_vmax dicts
          group_by[this_group].update(
              image=this_image, epochs=this_epochs, norm=this_norm
          )
          vmin_vmax[this_ch_type]["images"].append(this_image)
          vmin_vmax[this_ch_type]["norm"].append(this_norm)
  
      # compute overall vmin/vmax for images
      for ch_type, this_vmin_vmax_dict in vmin_vmax.items():
          image_list = this_vmin_vmax_dict["images"]
          image_stack = np.stack(image_list)
          norm = all(this_vmin_vmax_dict["norm"])
          vmin_vmax[ch_type] = _setup_vmin_vmax(
              image_stack, vmin, vmax, norm
          )
      del image_stack, vmin, vmax
  
      # prepare to plot
      auto_ylims = {ch_type: [0.0, 0.0] for ch_type in set(ch_types)}
  
      # plot
      for this_group, this_group_dict in group_by.items():
          this_ch_type = this_group_dict["ch_type"]
          this_axes_dict = this_group_dict["axes"]
          vmin, vmax = vmin_vmax[this_ch_type]
  
          # plot title
          if this_group_dict["title"] is None:
              title = _handle_default("titles").get(
                  this_group, this_group
              )
              if isinstance(combine, str) and len(title):
                  _comb = (
                      combine.upper() if combine == "gfp" else combine
                  )
                  _comb = "std. dev." if _comb == "std" else _comb
                  title += f" ({_comb})"
  
          # plot the image
          this_fig = _plot_epochs_image(
              this_group_dict["image"],
              epochs=this_group_dict["epochs"],
              picks=picks,
              colorbar=colorbar,
              vmin=vmin,
              vmax=vmax,
              cmap=cmap,
              style_axes=True,
              norm=this_group_dict["norm"],
              unit=units[this_ch_type],
              ax=this_axes_dict,
              show=False,
              title=title,
              combine=combine,
              combine_given=combine_given,
              overlay_times=_overlay_times,
              evoked=evoked,
              ts_args=ts_args,
          )
          group_by[this_group].update(fig=this_fig)
  
          # detect ylims across figures
          if evoked and not manual_ylims:
              # ensure get_ylim works properly
              this_axes_dict["evoked"].figure.canvas.draw_idle()
              this_bot, this_top = this_axes_dict["evoked"].get_ylim()
              this_min = min(this_bot, this_top)
              this_max = max(this_bot, this_top)
              curr_min, curr_max = auto_ylims[ch_type]
              auto_ylims[this_ch_type] = [
                  min(curr_min, this_min),
                  max(curr_max, this_max),
              ]
  
      # equalize ylims across figures (does not adjust ticks)
      if evoked:
          for this_group_dict in group_by.values():
              ax = this_group_dict["axes"]["evoked"]
              ch_type = this_group_dict["ch_type"]
              if not manual_ylims:
                  args = auto_ylims[ch_type]
                  if "invert_y" in ts_args:
                      args = args[::-1]
                  ax.set_ylim(*args)
      plt_show(show)
      # impose deterministic order of returned objects
      return_order = np.array(sorted(group_by))
      are_ch_types = np.isin(return_order, _VALID_CHANNEL_TYPES)
      if any(are_ch_types):
          return_order = np.concatenate(
              (return_order[are_ch_types], return_order[~are_ch_types])
          )
      return [group_by[group]["fig"] for group in return_order]
  
file_path: mne-python/mne/viz/epochs.py
imports: from collections import Counter
  from copy import deepcopy
  import numpy
  from scipy.ndimage import gaussian_filter1d
  from .._fiff.meas_info import create_info
  from .._fiff.pick import _DATA_CH_TYPES_SPLIT, _VALID_CHANNEL_TYPES, _picks_to_idx
  from ..defaults import _handle_default
  from ..fixes import _sharex
  from ..utils import _check_option, fill_doc, legacy, logger, verbose, warn
  from ..utils.spectrum import _split_psd_kwargs
  from .raw import _setup_channel_selections
  from .utils import DraggableColorbar, _check_cov, _compute_scalings, _get_channel_plotting_order, _handle_decim, _handle_precompute, _make_combine_callable, _make_event_color_dict, _set_title_multiple_electrodes, _set_window_title, _setup_cmap, _setup_vmin_vmax, _validate_type, plt_show
label_desc: Use image node_id 1 for calling a global function with example usage: plot_epochs_image(epochs, picks, sigma, vmin, vmax, colorbar, order, show, units, scalings, cmap, fig, axes, overlay_times, combine, group_by, evoked, ts_args, title, clear) and returns: unknown