magmap.plot.plot_2d module

Plot 2D views of imaging data and graphs.

magmap.plot.plot_2d.decorate_plot(ax, title=None, xlabel=None, ylabel=None, xunit=None, yunit=None, xlim=None, ylim=None, xscale=None, yscale=None, xticks=None, yticks=None, **kwargs)[source]

Decorate a plot with text and configure limits and scaling.

Parameters:
  • ax (Axes) – Matplotlib plot.

  • title (Optional[str], default: None) – Title of figure; defaults to None.

  • xlabel (Optional[str], default: None) – X-axis label; defaults to None to use config.plot_labels. Can explicitly set to None to prevent unit display.

  • ylabel (Optional[str], default: None) – Y-axis label; defaults to None to use config.plot_labels. Can explicitly set to None to prevent unit display.

  • xunit (Optional[str], default: None) – X-axis label unit; defaults to None.

  • yunit (Optional[str], default: None) – Y-axis label unit; defaults to None.:

  • xlim (Optional[Sequence[float]], default: None) – Sequence of min and max boundaries for the x-axis; defaults to None.

  • ylim (Optional[Sequence[float]], default: None) – Sequence of min and max boundaries for the y-axis; defaults to None.

  • xscale (Optional[str], default: None) – Scale mode for plot_support.scale_axes() x-axis; defaults to None to ignore.

  • yscale (Optional[str], default: None) – Scale mode for plot_support.scale_axes() y-axis; defaults to None to ignore.

  • xticks (Optional[Sequence[Any]], default: None) – Arguments to axes.Axes.set_xticks(); defaults to None.

  • yticks (Optional[Sequence[Any]], default: None) – Arguments to axes.Axes.set_yticks(); defaults to None.

  • **kwargs – Additional arguments, which will be ignored.

Return type:

Axes

Returns:

Matplotlib plot.

magmap.plot.plot_2d.main(ax=None, df=None, kwargs_plot=None, save=True, plot_2d_type=None, **kwargs)[source]

Perform 2D plot tasks.

Parameters:
  • ax (matplotlib.image.Axes) – Matplotlib plot.

  • df (Optional[DataFrame], default: None) – Data frame; defaults to None.

  • kwargs_plot (Optional[Dict[str, Any]], default: None) – Dictionary of args to the underlying plot function; defaults to None.

  • save (bool, default: True) – True (default) to save plot.

  • plot_2d_type (Optional[Plot2DTypes], default: None) – Enum of plot type. If None (default), config.plot_2d_type will be used.

  • kwargs – Additional args to decorate_plot().

Returns:

The generated axes, or ax if given.

magmap.plot.plot_2d.plot_bars(path_to_df, data_cols=None, err_cols=None, legend_names=None, col_groups=None, groups=None, y_label=None, y_unit=None, size=None, show=True, col_vspan=None, vspan_fmt=None, col_wt=None, df=None, x_tick_labels=None, rotation=None, save=True, hline=None, ax=None, suffix=None, err_cols_abs=None, **kwargs)[source]

Plot grouped bars from Pandas data frame.

Takes a data frame in wide format. Each row represents a group, and each chosen data column will be plotted as a separate bar within each group.

Parameters:
  • path_to_df (str) – Path from which to read saved Pandas data frame. The figure will be saved to file if :attr:config.savefig is set, using this same path except with the savefig extension.

  • data_cols (Optional[Sequence[str]], default: None) – Sequence of names of columns to plot as separate sets of bars, where each row is part of a separate group. Defaults to None, which will plot all columns except col_groups.

  • err_cols (Optional[Sequence[str]], default: None) – Sequence of column names corresponding to data_cols. Values should be relative to the data points. Each column can be a sequence of two columns, given as lower, upper values. Defaults to None, in which case matching columns with “_err” as suffix will be used for error bars if present.

  • legend_names (Optional[Sequence[str]], default: None) – Sequence of names for each set of bars. Defaults to None, which will use data_cols for names. Use “” to not display a legend.

  • col_groups (Optional[Sequence[str]], default: None) – Name of column specifying names of each group. Defaults to None, which will use the first column for names.

  • groups (Optional[Sequence[str]], default: None) – Sequence of groups to include and by which to sort; defaults to None to include all groups found from col_groups.

  • y_label (Optional[str], default: None) – Name of y-axis; defaults to None to use config.plot_labels. (None, ) prevents label display.

  • y_unit (Optional[str], default: None) – Measurement unit for y-axis; defaults to None to use config.plot_labels. (None, ) prevents unit display.

  • size (Optional[Sequence[float]], default: None) – Sequence of width, height to size the figure; defaults to None.

  • show (bool, default: True) – True to display the image; otherwise, the figure will only be saved to file, if :attr:config.savefig is set. Defaults to True.

  • col_vspan (Optional[str], default: None) – Name of column with values specifying groups demaracted by vertical spans. Each change in value when taken in sequence will specify a new span in alternating background colors. Defaults to None.

  • vspan_fmt (Optional[str], default: None) – String to format with values from col_vspan; defaults to None to simply use the unformatted values.

  • col_wt (Optional[str], default: None) – Name of column to use for weighting, where the size of bars and error bars will be adjusted as fractions of the max value; defaults to None.

  • df (Optional[DataFrame], default: None) – Data frame to use; defaults to None. If set, this data frame will be used instead of loading from path.

  • x_tick_labels (Optional[Sequence[str]], default: None) – Sequence of labels for each bar group along the x-axis; defaults to None to use groups instead.

  • rotation (Optional[float], default: None) – Degrees of x-tick label rotation; defaults to None.

  • save (bool, default: True) – True to save the plot; defaults to True.

  • hline (Optional[str], default: None) – One of config.STR_FN for a function to apply to each list in lists for a horizontal line to be drawn at this y-value; defaults to None.

  • ax (Optional[Axes], default: None) – Matplotlib axes; defaults to None.

  • suffix (Optional[str], default: None) – String to append to output path before extension; defaults to None to ignore.

  • err_cols_abs (Optional[str], default: None) – Column(s) for error bars as absolute values. Defaults to None. Takes precdence over err_cols.

  • kwargs – Extra arguments to plot_support.decorate_plot().

Return type:

Tuple[Axes, str]

Returns:

Plot axes and save path without extension.

magmap.plot.plot_2d.plot_catplot(df, x_cols, y_cols, group_col=None, x_label=None, y_label=None, x_unit=None, y_unit=None, legend_names=None, size=None, title=None, legend_title=None, kwargs_plot=None, **kwargs)[source]

Generate a category plot in Seaborn.

Parameters:
  • df – Data frame, assumed to be in melted format.

  • x_cols – Column for x-values, typically categorical.

  • y_cols – Column for y-values, typically continuous.

  • group_col (default: None) – Column for groups plotted across x-vals and shown in the legend. Defaults to None.

  • x_label (default: None) – Label for the x-axis; defaults to None.

  • y_label (default: None) – Label for the y-axis; defaults to None.

  • x_unit (default: None) – Unit for the x-axis; defaults to None.

  • y_unit (default: None) – Unit for the y-axis; defaults to None.

  • legend_names (default: None) – Legend names. Defaults to None to use those from group_col

  • size (default: None) – Figure size in width, height as inches; defaults to None.

  • title (default: None) – Figure title; defaults to None.

  • legend_title (default: None) – Legened title; defaults to None.

  • kwargs_plot (default: None) – Dictionary of arguments to sns.catplot(); defaults to None.

  • **kwargs – Additional arguments, passed to decorate_plot().

Returns:

Seaborn grid of facets containing the plots by category.

Raises:

ImportError

magmap.plot.plot_2d.plot_histogram(df, path, col_x, ax=None, size=None, save=True, suffix=None, show=False, **kwargs)[source]

Geneate a histogram plot.

Parameters:
  • df (pandas.DataFrame) – Data frame to plot.

  • path (str) – Path to data frame to use if df is None, also used as the basis for output path.

  • col_x (str) – Name of column with values to plot.

  • ax (matplotlib.axes.Axes) – Matplotlib axes; defaults to None to generate a new figure with axes.

  • size (Sequence[float]) – Sequence of width, height to size the figure; defaults to None.

  • save (bool) – True to save the plot; defaults to True.

  • suffix (default: None) – String to append to output path before extension; defaults to None to ignore.

  • show (default: False) – True to display the image; otherwise, the figure will only be saved to file, if :attr:config.savefig is set. Defaults to True.

  • kwargs (Any) – Extra arguments to decorate_plot().

Returns:

Matplotlib axes.

Return type:

matplotlib.axes.Axes

magmap.plot.plot_2d.plot_image(img, path=None, show=False)[source]

Plot a single image in a borderless figure, with option to export directly to file.

Parameters:
  • img (np.ndarray) – Image as a Numpy array to display.

  • path (str) – Path to save image. Defaults to None to not save.

  • show (bool) – True to show the image; defaults to False, which will plot the image for saving.

magmap.plot.plot_2d.plot_lines(path_to_df, x_col, data_cols, linestyles=None, labels=None, title=None, size=None, show=True, suffix=None, colors=None, df=None, groups=None, ignore_invis=False, units=None, marker=None, err_cols=None, prefix=None, save=True, ax=None, col_annot=None, line_label_style=None, linewidth=None)[source]

Plot a line graph from a Pandas data frame.

Parameters:
  • path_to_df – Path from which to read saved Pandas data frame. The figure will be saved to file if :attr:config.savefig is set, using this same path except with the savefig extension.

  • x_col – Name of column to use for x.

  • data_cols – Sequence of column names to plot as separate lines. Hierarchical columns will be plotted with the same color and style unless groups is specified. Legend names will correspond to these colum names.

  • linestyles (default: None) – Sequence of styles to use for each line; defaults to None, in which case “-” will be used for all lines if groups is None, or each group will use a distinct style.

  • labels (List[str]) – (y_label, x_label) to display; defaults to None to use config.plot_labels. Can explicitly set a value to None to prevent unit display.

  • title (default: None) – Title of figure; defaults to None.

  • size (default: None) – Sequence of width, height to size the figure; defaults to None.

  • show (default: True) – True to display the image; otherwise, the figure will only be saved to file, if :attr:config.savefig is set. Defaults to True.

  • suffix (default: None) – String to append to output path before extension; defaults to None to ignore.

  • colors (default: None) – Sequence of colors for plot lines; defaults to None to use :meth:colormaps.discrete_colormap while prioritizing the default CN color cycler (C0, C1, etc).

  • df (default: None) – Data frame to use; defaults to None. If set, this data frame will be used instead of loading from path.

  • groups (List[str]) – Sequence of groups names within each data column to plot separately, assuming that each data column has sub-columns that include these group names. If given, all lines within a group will have the same style, and a separate group legend will be displayed with these line styles. To simply plot with different colors, use separate data colums in data_cols instead. Defaults to None.

  • ignore_invis (default: False) – True to ignore lines that aren’t displayed, such as those with only a single value; defaults to False.

  • units (List[str]) – (y_unit, x_unit) to display; defaults to None to use config.plot_labels. Can explicitly set a value to None to prevent unit display.

  • marker (str) – Marker style for points; defaults to None.

  • err_cols (List[str]) – Sequence of column names with relative error values corresponding to data_cols; defaults to None.

  • prefix (default: None) – Base path for figure output if :attr:config.savefig is set; defaults to None to use path_to_df.

  • save (bool) – True to save the plot; defaults to True.

:param ax (matplotlib.image.Axes: Image axes object; defaults to

None to generate a new figure and subplot.

Parameters:
  • col_annot (str) – Name of column for point annotations; defaults to None. The first line will be annotated based on this column.

  • line_label_style (str) – “legend” to label lines through a legend, “end” to label the last point of each line, and any other string to not label lines; defaults to None to use “legend”.

  • linewidth (float) – Line width; defaults to None.

Returns:

Axes object.

Return type:

matplotlib.Axes

magmap.plot.plot_2d.plot_overlays(imgs, z, cmaps, title=None, aspect=1.0)[source]

Plot images in a single row, with the final subplot showing an overlay of all images.

Parameters:
  • imgs – List of 3D images to show.

  • z – Z-plane to view for all images.

  • cmaps – List of colormap names, which should be be the same length as imgs, with the colormap applied to the corresponding image.

  • title (default: None) – Figure title; if None, will be given default title.

  • aspect (default: 1.0) – Aspect ratio, which will be applied to all images; defaults to 1.0.

magmap.plot.plot_2d.plot_overlays_reg(exp, atlas, atlas_reg, labels_reg, cmap_exp, cmap_atlas, cmap_labels, translation=None, title=None, out_plane=None, show=True)[source]

Plot overlays of registered 3D images, showing overlap of atlas and experimental image planes.

Shows the figure on screen. If :attr:config.savefig is set, the figure will be saved to file with the extensive given by savefig.

Parameters:
  • exp – Experimental image.

  • atlas – Atlas image, unregistered.

  • atlas_reg – Atlas image, after registration.

  • labels_reg – Atlas labels image, also registered.

  • cmap_exp – Colormap for the experimental image.

  • cmap_atlas – Colormap for the atlas.

  • cmap_labels – Colormap for the labels.

  • translation (default: None) – Translation in (z, y, x) order for consistency with operations on Numpy rather than SimpleITK images here; defaults to None, in which case the chosen plane index for the unregistered atlast will be the same fraction of its size as for the registered image.

  • title (default: None) – Figure title; if None, will be given default title.

  • out_plane (default: None) – Output planar orientation.

  • show (default: True) – True if the plot should be displayed on screen; defaults to True.

magmap.plot.plot_2d.plot_probability(path, conds, metric_cols, col_size, **kwargs)[source]

Generate a probability plot such as that used in Q-Q or P-P plots.

Serves as a wrapper for plot_scatter() with the assumption that matching columns for each of two conditions describe each point.

Parameters:
  • path – Path from which to read a saved Pandas data frame and the path basis to save the figure if :attr:config.savefig is set.

  • conds – Sequence of conditions, the first of which will be used to find the x-values for each metric, and the second for y-values.

  • metric_cols – Sequence of column name prefixes for each metric to plot. Metric column names are assumed to have these values combined with a condition, separated by “_”.

  • col_size – Name of column from which to scale point sizes, where the max value in the column is 1; defaults to None.

  • **kwargs – Additional keyword arguments to pass to :meth:plot_scatter.

magmap.plot.plot_2d.plot_roc(df, show=True, annot_arri=None, **kwargs)[source]

Plot ROC curve generated from :meth:mlearn.grid_search.

Parameters:
  • df (DataFrame) – Data frame generated from :meth:mlearn.parse_grid_stats.

  • show (bool, default: True) – True to display the plot in :meth:plot_scatter; defaults to True.

  • annot_arri (Optional[int], default: None) – Int as index or slice of indices of annotation value if the annotation is a string that can be converted into a Numpy array; defaults to None.

  • kwargs – Extra arguments to plot_support.plot_scatter().

Return type:

Axes

Returns:

Matplotlib plot axes.

magmap.plot.plot_2d.plot_scatter(path, col_x, col_y=None, col_annot=None, cols_group=None, names_group=None, fig_size=None, show=True, suffix=None, df=None, xy_line=False, col_size=None, size_mult=5, annot_arri=None, alpha=None, legend_loc='best', ax=None, save=True, annot_thresh_fn=None, colors=None, jitter=0, rotation=0, **kwargs)[source]

Generate a scatter plot from a data frame or CSV file.

Parameters:
  • path (Optional[str]) – Path from which to read a saved Pandas data frame and the path basis to save the figure if :attr:config.savefig is set.

  • col_x (Union[str, Sequence[str]]) – Name of column to plot as x-values. Can also be a sequence of names to define groups with corresponding col_y values.

  • col_y (Union[str, Sequence[str], None], default: None) – Name of column to plot as corresponding y-values; defaults to None. Can also be a sequence corresponding to that of col_x. If not found, y-values are set to 0 if col_x is only one column.

  • col_annot (Optional[str], default: None) – Name of column with annotations for each point; defaults to None. Can be the name of the index column.

  • cols_group (Optional[Sequence[str]], default: None) – Sequence of column names; defaults to None. Each unique combination in these columns specifies a group to plot separately.

  • names_group (Union[Sequence[str], Callable[[str], str], None], default: None) – Sequence of names to display; defaults to None, in which case a name based on cols_groups will be used instead. Length should equal that of groups based on cols_group.

  • fig_size (Optional[Sequence[float]], default: None) – Sequence of width, height to size the figure; defaults to None.

  • show (bool, default: True) – True to display the image; otherwise, the figure will only be saved to file, if :attr:config.savefig is set. Defaults to True.

  • suffix (Optional[str], default: None) – String to append to output path before extension; defaults to None to ignore.

  • df (Optional[DataFrame], default: None) – Data frame to use; defaults to None. If set, this data frame will be used instead of loading from path.

  • xy_line (bool, default: False) – Show an xy line; defaults to False.

  • col_size (Optional[str], default: None) – Name of column from which to scale point sizes, where the max value in the column is 1; defaults to None.

  • size_mult (float, default: 5) – Point size multiplier; defaults to 5.

  • annot_arri (Optional[int], default: None) – Int as index or slice of indices of annotation value if the annotation is a string that can be converted into a Numpy array; defaults to None.

  • alpha (Optional[float], default: None) – Point transparency value, from 0-1; defaults to None, in which case 1.0 will be used.

  • legend_loc (str, default: 'best') – Legend location, which should be one of :attr:plt.legend.loc values; defaults to “best”.

  • ax (Optional[Axes], default: None) – Matplotlib axes; defaults to None.

  • save (bool, default: True) – True to save the plot; defaults to True.

  • annot_thresh_fn (Optional[Callable[[int, int], bool]], default: None) – Function accepting x, y and returning a boolean indicated whether to annotate the given point; defaults to False.

  • colors (Optional[Sequence[str]], default: None) – Sequence of colors for each point. If None (default), distinct colors are auto-generated for each pair of x-y column or for each group.

  • jitter (float, default: 0) – Jitter width in x-units; defaults to 0. If given, x-values will randomly “jitter” by this value, centered on the original position.

  • rotation (int, default: 0) – Degrees to rotate x-tick labels; defaults to 0.

  • kwargs – Extra arguments to plot_support.decorate_plot().

Return type:

Axes

Returns:

Matplotlib plot axes.

magmap.plot.plot_2d.plot_swarm(df, x_cols, y_cols, x_order=None, group_col=None, x_label=None, y_label=None, x_unit=None, y_unit=None, legend_names=None, col_vspan=None, vspan_fmt=None, size=None, ax=None, rotation=None, legend_title=None, kwargs_plot=None, fn_plot=None, **kwargs)[source]

Generate a swarm/jitter plot in Seaborn.

Supports x-axis scaling and vertical spans.

Parameters:
  • df (DataFrame) – Data frame, assumed to be in melted format.

  • x_cols (Union[str, Sequence[str]]) – Column for x-values, typically categorical.

  • y_cols (Union[str, Sequence[str]]) – Column for y-values, typically continuous.

  • x_order (Optional[Sequence[str]], default: None) – Order of values in x_cols, given as the values in which to reorder the data frame. Defaults to None.

  • group_col (Optional[str], default: None) – Column for groups plotted across x-vals and shown in the legend. Defaults to None.

  • x_label (Optional[str], default: None) – Label for the x-axis; defaults to None.

  • y_label (Optional[str], default: None) – Label for the y-axis; defaults to None.

  • x_unit (Optional[str], default: None) – Unit for the x-axis; defaults to None.

  • y_unit (Optional[str], default: None) – Unit for the y-axis; defaults to None.

  • legend_names (Optional[Sequence[str]], default: None) – Legend names. Defaults to None to use those from group_col

  • col_vspan (Optional[str], default: None) – Column for delineating vertical span groups. Groups are determined by contiguous values after reordering by x_order. Defaults to None.

  • vspan_fmt (Optional[str], default: None) – Vertical span label string format.

  • size (Optional[Sequence[float]], default: None) – Figure size in width, height as inches; defaults to None.

  • ax (Optional[Axes], default: None) – Matplotlib axes; defaults to None.

  • rotation (Optional[float], default: None) – x-axis ttext angle rotation in degrees. Defaults to None, which will rotate by 45 degrees.

  • legend_title (Optional[str], default: None) – Legend title; defaults to None.

  • kwargs_plot (Optional[Dict[str, Any]], default: None) – Dictionary of arguments to sns.swarmplot(); defaults to None.

  • fn_plot (Optional[Callable], default: None) – Plotting function. If None (default), will use sns.swarmplot(). Typically, only similar Seaborn functions are compatible.

  • **kwargs – Additional arguments, passed to decorate_plot().

Return type:

Axes

Returns:

Matplotlib axes with the plot.

Raises:

ImportError

magmap.plot.plot_2d.post_plot(ax, out_path=None, save_ext=None, show=False)[source]

Post plot adjustments, followed by saving and display.

Handles additional config.plot_labels values.

:param ax (matplotlib.image.Axes: Image axes object. :type out_path: default: None :param out_path: String to save path without extension; defaults

to None. Both out_path and save_ext must be given to save.

Parameters:
  • save_ext (str) – String to save extension; defaults to None.

  • show (bool) – True to show the plot.

magmap.plot.plot_2d.setup_style(style=None, rc_params=None)[source]

Set up Matplotlib styles and RC parameter themes.

Both styles and themes default to those specified in config.

Parameters:
  • style (Optional[str], default: None) – Name of Matplotlib style to apply. Defaults to None to use the style specified in :attr:config.matplotlib_style.

  • rc_params (Optional[Sequence[Themes]], default: None) – Sequence of config.Themes enums specifying custom themes to apply after setting the style. Themes will be applied in the order listed. Defaults to None, which will use the config.rc_params value.