コード例 #1
0
ファイル: _utils.py プロジェクト: lzlgboy/scanpy
def timeseries(X, **kwargs):
    """Plot X. See timeseries_subplot."""
    pl.figure(
        figsize=tuple(2 * s for s in rcParams['figure.figsize']),
        subplotpars=sppars(left=0.12, right=0.98, bottom=0.13),
    )
    timeseries_subplot(X, **kwargs)
コード例 #2
0
ファイル: plotting.py プロジェクト: charliex210/scanpy
def timeseries(X, **kwargs):
    """
    Plot X. See timeseries_subplot.
    """
    pl.figure(figsize=(2 * 4, 4),
              subplotpars=sppars(left=0.12, right=0.98, bottom=0.13))
    timeseries_subplot(X, **kwargs)
コード例 #3
0
ファイル: utils.py プロジェクト: stashkov/scanpy
def timeseries(X, **kwargs):
    """Plot X. See timeseries_subplot."""
    pl.figure(figsize=(2*rcParams['figure.figsize'][0], rcParams['figure.figsize'][1]),
              subplotpars=sppars(left=0.12, right=0.98, bottom=0.13))
    timeseries_subplot(X, **kwargs)
コード例 #4
0
ファイル: utils.py プロジェクト: stashkov/scanpy
def setup_axes(
        ax=None,
        panels='blue',
        colorbars=[False],
        right_margin=None,
        left_margin=None,
        projection='2d',
        show_ticks=False):
    """Grid of axes for plotting, legends and colorbars.
    """
    if '3d' in projection: from mpl_toolkits.mplot3d import Axes3D
    avail_projections = {'2d', '3d'}
    if projection not in avail_projections:
        raise ValueError('choose projection from', avail_projections)
    if left_margin is not None:
        raise ValueError('Currently not supporting to pass `left_margin`.')
    if np.any(colorbars) and right_margin is None:
        right_margin = 1 - rcParams['figure.subplot.right'] + 0.21  # 0.25
    elif right_margin is None:
        right_margin = 1 - rcParams['figure.subplot.right'] + 0.06  # 0.10
    # make a list of right margins for each panel
    if not isinstance(right_margin, list):
        right_margin_list = [right_margin for i in range(len(panels))]
    else:
        right_margin_list = right_margin

    # make a figure with len(panels) panels in a row side by side
    top_offset = 1 - rcParams['figure.subplot.top']
    bottom_offset = 0.15 if show_ticks else 0.08
    left_offset = 1 if show_ticks else 0.3  # in units of base_height
    base_height = rcParams['figure.figsize'][1]
    height = base_height
    base_width = rcParams['figure.figsize'][0]
    if show_ticks: base_width *= 1.1

    draw_region_width = base_width - left_offset - top_offset - 0.5  # this is kept constant throughout

    right_margin_factor = sum([1 + right_margin for right_margin in right_margin_list])
    width_without_offsets = right_margin_factor * draw_region_width  # this is the total width that keeps draw_region_width

    right_offset = (len(panels) - 1) * left_offset
    figure_width = width_without_offsets + left_offset + right_offset
    draw_region_width_frac = draw_region_width / figure_width
    left_offset_frac = left_offset / figure_width
    right_offset_frac = 1 - (len(panels) - 1) * left_offset_frac

    if ax is None:
        pl.figure(figsize=(figure_width, height),
                  subplotpars=sppars(left=0, right=1, bottom=bottom_offset))
    left_positions = [left_offset_frac, left_offset_frac + draw_region_width_frac]
    for i in range(1, len(panels)):
        right_margin = right_margin_list[i-1]
        left_positions.append(left_positions[-1] + right_margin * draw_region_width_frac)
        left_positions.append(left_positions[-1] + draw_region_width_frac)
    panel_pos = [[bottom_offset], [1-top_offset], left_positions]

    axs = []
    if ax is None:
        for icolor, color in enumerate(panels):
            left = panel_pos[2][2*icolor]
            bottom = panel_pos[0][0]
            width = draw_region_width / figure_width
            height = panel_pos[1][0] - bottom
            if projection == '2d': ax = pl.axes([left, bottom, width, height])
            elif projection == '3d': ax = pl.axes([left, bottom, width, height], projection='3d')
            axs.append(ax)
    else:
        axs = ax if isinstance(ax, list) else [ax]

    return axs, panel_pos, draw_region_width, figure_width
コード例 #5
0
ファイル: _utils.py プロジェクト: lzlgboy/scanpy
def setup_axes(
    ax: Union[Axes, Sequence[Axes]] = None,
    panels='blue',
    colorbars=(False, ),
    right_margin=None,
    left_margin=None,
    projection: Literal['2d', '3d'] = '2d',
    show_ticks=False,
):
    """Grid of axes for plotting, legends and colorbars.
    """
    make_projection_available(projection)
    if left_margin is not None:
        raise NotImplementedError('We currently don’t support `left_margin`.')
    if np.any(colorbars) and right_margin is None:
        right_margin = 1 - rcParams['figure.subplot.right'] + 0.21  # 0.25
    elif right_margin is None:
        right_margin = 1 - rcParams['figure.subplot.right'] + 0.06  # 0.10
    # make a list of right margins for each panel
    if not isinstance(right_margin, list):
        right_margin_list = [right_margin for i in range(len(panels))]
    else:
        right_margin_list = right_margin

    # make a figure with len(panels) panels in a row side by side
    top_offset = 1 - rcParams['figure.subplot.top']
    bottom_offset = 0.15 if show_ticks else 0.08
    left_offset = 1 if show_ticks else 0.3  # in units of base_height
    base_height = rcParams['figure.figsize'][1]
    height = base_height
    base_width = rcParams['figure.figsize'][0]
    if show_ticks:
        base_width *= 1.1

    draw_region_width = (base_width - left_offset - top_offset - 0.5
                         )  # this is kept constant throughout

    right_margin_factor = sum(
        [1 + right_margin for right_margin in right_margin_list])
    width_without_offsets = (
        right_margin_factor * draw_region_width
    )  # this is the total width that keeps draw_region_width

    right_offset = (len(panels) - 1) * left_offset
    figure_width = width_without_offsets + left_offset + right_offset
    draw_region_width_frac = draw_region_width / figure_width
    left_offset_frac = left_offset / figure_width
    right_offset_frac = 1 - (len(panels) - 1) * left_offset_frac

    if ax is None:
        pl.figure(
            figsize=(figure_width, height),
            subplotpars=sppars(left=0, right=1, bottom=bottom_offset),
        )
    left_positions = [
        left_offset_frac, left_offset_frac + draw_region_width_frac
    ]
    for i in range(1, len(panels)):
        right_margin = right_margin_list[i - 1]
        left_positions.append(left_positions[-1] +
                              right_margin * draw_region_width_frac)
        left_positions.append(left_positions[-1] + draw_region_width_frac)
    panel_pos = [[bottom_offset], [1 - top_offset], left_positions]

    axs = []
    if ax is None:
        for icolor, color in enumerate(panels):
            left = panel_pos[2][2 * icolor]
            bottom = panel_pos[0][0]
            width = draw_region_width / figure_width
            height = panel_pos[1][0] - bottom
            if projection == '2d':
                ax = pl.axes([left, bottom, width, height])
            elif projection == '3d':
                ax = pl.axes([left, bottom, width, height], projection='3d')
            axs.append(ax)
    else:
        axs = ax if isinstance(ax, cabc.Sequence) else [ax]

    return axs, panel_pos, draw_region_width, figure_width
コード例 #6
0
ファイル: plotting.py プロジェクト: charliex210/scanpy
def scatter_base(Y,
                 colors='blue',
                 highlights=[],
                 highlights_labels=[],
                 title='',
                 right_margin=None,
                 layout='2d',
                 titles=None,
                 component_name='DC',
                 component_indexnames=[1, 2, 3],
                 axlabels=None,
                 colorbars=[False],
                 sizes=[1],
                 cmap='viridis'):
    """
    Plot scatter plot of data.

    Parameters
    ----------
    Y : np.ndarray
        Data array.
    layout : str
        Either '2d' or '3d'.
    comps : iterable
        Iterable that stores the component indices.

    Returns
    -------
    axs : matplotlib.axis or list of matplotlib.axis
        Depending on whether supplying a single array or a list of arrays,
        return a single axis or a list of axes.
    """
    # if we have a single array, transform it into a list with a single array
    avail_layouts = {'2d', '3d'}
    if layout not in avail_layouts:
        raise ValueError('choose layout from', avail_layouts)
    if type(colors) == str:
        colors = [colors]
    if len(sizes) != len(colors):
        if len(sizes) == 1:
            sizes = [sizes[0] for i in range(len(colors))]
    # try importing Axes3D
    if '3d' in layout:
        from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import gridspec
    # grid of axes for plotting and legends/colorbars
    if np.any(colorbars) and right_margin is None:
        right_margin = 0.25
    elif right_margin is None:
        right_margin = 0.01
    # make a figure with panels len(colors) x 1
    top_offset = 1 - rcParams['figure.subplot.top']
    bottom_offset = 0.08
    left_offset = 0.3  # in units of base_height
    base_height = 4
    height = base_height
    draw_region_width = base_height - left_offset - top_offset - 0.5  # this is kept constant throughout

    right_margin_factor = (1 + right_margin / (1 - right_margin))
    width_without_offsets = right_margin_factor * len(
        colors
    ) * draw_region_width  # this is the total width that keeps draw_region_width

    right_offset = (len(colors) - 1) * left_offset
    width = width_without_offsets + left_offset + right_offset
    left_offset_frac = left_offset / width
    right_offset_frac = 1 - (len(colors) - 1) * left_offset_frac

    figsize = (width, height)
    fig = pl.figure(figsize=figsize,
                    subplotpars=sppars(left=0, right=1, bottom=bottom_offset))
    gs = gridspec.GridSpec(nrows=1,
                           ncols=2 * len(colors),
                           width_ratios=[
                               r for i in range(len(colors))
                               for r in [1 - right_margin, right_margin]
                           ],
                           left=left_offset_frac,
                           right=right_offset_frac,
                           wspace=0)
    pos = gs.get_grid_positions(fig)
    fig.suptitle(title)
    count = 1
    bool3d = True if layout == '3d' else False
    axs = []
    for icolor, color in enumerate(colors):
        # set up panel
        if layout == 'unfolded 3d' and count != 3:
            ax = fig.add_subplot(2, 2, count)
            bool3d = False
        elif layout == 'unfolded 3d' and count == 3:
            ax = fig.add_subplot(2, 2, count, projection='3d')
            bool3d = True
        elif layout == '2d':
            ax = pl.subplot(gs[2 * (count - 1)])
        elif layout == '3d':
            ax = pl.subplot(gs[2 * (count - 1)], projection='3d')
        if not bool3d:
            data = Y[:, 0], Y[:, 1]
        else:
            data = Y[:, 0], Y[:, 1], Y[:, 2]
        # do the plotting
        if type(color) != str or color != 'white':
            sct = ax.scatter(*data,
                             c=color,
                             edgecolors='face',
                             s=sizes[icolor],
                             cmap=cmap)
        if colorbars[icolor]:
            pos = gs.get_grid_positions(fig)
            left = pos[2][2 * (count - 1) + 1]
            bottom = pos[0][0]
            width = 0.006 * draw_region_width
            # print(0.2*(pos[3][2*(count-1)+1] - left))
            height = pos[1][0] - bottom
            # again shift to left
            left = pos[3][2 * (count - 1)] + width
            rectangle = [left, bottom, width, height]
            ax_cb = fig.add_axes(rectangle)
            cb = pl.colorbar(sct,
                             format=ticker.FuncFormatter(ticks_formatter),
                             cax=ax_cb)
        # set the titles
        if titles is not None:
            ax.set_title(titles[icolor])
        # output highlighted data points
        for iihighlight, ihighlight in enumerate(highlights):
            data = [Y[ihighlight, 0]], [Y[ihighlight, 1]]
            if bool3d:
                data = [Y[ihighlight, 0]], [Y[ihighlight,
                                              1]], [Y[ihighlight, 2]]
            ax.scatter(*data,
                       c='black',
                       facecolors='black',
                       edgecolors='black',
                       marker='x',
                       s=40,
                       zorder=20)
            highlight = (highlights_labels[iihighlight]
                         if len(highlights_labels) > 0 else str(ihighlight))
            # the following is a Python 2 compatibility hack
            ax.text(*([d[0] for d in data] + [highlight]), zorder=20)
        ax.set_xticks([])
        ax.set_yticks([])
        if bool3d:
            ax.set_zticks([])
        # scale limits to match data
        ax.autoscale_view()
        axs.append(ax)
        count += 1
    # set default axlabels
    if axlabels is None:
        if layout == '2d':
            axlabels = [[
                component_name + str(i) for i in idcs
            ] for idcs in [component_indexnames for iax in range(len(axs))]]
        elif layout == '3d':
            axlabels = [[
                component_name + str(i) for i in idcs
            ] for idcs in [component_indexnames for iax in range(len(axs))]]
        elif layout == 'unfolded 3d':
            axlabels = [[
                component_name + str(component_indexnames[i - 1]) for i in idcs
            ] for idcs in [[2, 3], [1, 2], [1, 2, 3], [1, 3]]]
    # set axlabels
    bool3d = True if layout == '3d' else False
    for iax, ax in enumerate(axs):
        if layout == 'unfolded 3d' and iax != 2:
            bool3d = False
        elif layout == 'unfolded 3d' and iax == 2:
            bool3d = True
        if axlabels is not None:
            ax.set_xlabel(axlabels[iax][0])
            ax.set_ylabel(axlabels[iax][1])
            if bool3d:
                # shift the label closer to the axis
                ax.set_zlabel(axlabels[iax][2], labelpad=-7)
    return axs