def __configPlot2(df: pd.DataFrame, ax: matplotlib.axes.Axes): """グラフの描画設定を行う。 """ ax.get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True)) ax.get_yaxis().set_major_locator(ticker.MaxNLocator(integer=True)) ax.ticklabel_format(style='plain', axis='both', useOffset=False, useMathText=False) ax.margins(x=0, y=0) ax.set_xticks(list(df.index)) ax.set_xticklabels(list(df['Gregorian']), rotation=30)
def plot( self, figsize: Tuple[float, float] = (15, 10), same_plot: bool = False, hide_cells: bool = False, perc: Tuple[float, float] = None, abs_prob_cmap: mcolors.ListedColormap = cm.viridis, cell_color: str = "black", lineage_color: str = "black", alpha: float = 0.8, lineage_alpha: float = 0.2, title: Optional[str] = None, size: int = 15, lw: float = 2, show_cbar: bool = True, margins: float = 0.015, xlabel: str = "pseudotime", ylabel: str = "expression", show_conf_int: bool = True, dpi: int = None, fig: mpl.figure.Figure = None, ax: mpl.axes.Axes = None, return_fig: bool = False, save: Optional[str] = None, ) -> Optional[mpl.figure.Figure]: """ Plot the smoothed gene expression. Parameters ---------- figsize Size of the figure. same_plot Whether to plot all trends in the same plot. hide_cells Whether to hide the cells. perc Percentile by which to clip the absorption probabilities./ abs_prob_cmap Colormap to use when coloring in the absorption probabilities. cell_color Color for the cells when not coloring absorption probabilities. lineage_color Color for the lineage. alpha Alpha channel for cells. lineage_alpha Alpha channel for lineage confidence intervals. title Title of the plot. size Size of the points. lw Line width for the smoothed values. show_cbar Whether to show colorbar. margins Margins around the plot. xlabel Label on the x-axis. ylabel Label on the y-axis. show_conf_int Whether to show the confidence interval. dpi Dots per inch. fig Figure to use, if `None`, create a new one. ax: :class:`matplotlib.axes.Axes` Ax to use, if `None`, create a new one. return_fig If `True`, return the figure object. save Filename where to save the plot. If `None`, just shows the plots. Returns ------- %(just_plots)s """ if fig is None or ax is None: fig, ax = plt.subplots(figsize=figsize, constrained_layout=True) if dpi is not None: fig.set_dpi(dpi) vmin, vmax = _minmax(self.w, perc) if not hide_cells: _ = ax.scatter( self.x_all.squeeze(), self.y_all.squeeze(), c=cell_color if same_plot or np.allclose(self.w_all, 1.0) else self.w_all.squeeze(), s=size, cmap=abs_prob_cmap, vmin=vmin, vmax=vmax, alpha=alpha, ) if title is None: title = f"{self._gene} @ {self._lineage}" _ = ax.plot(self.x_test, self.y_test, color=lineage_color, lw=lw, label=title) ax.set_title(title) ax.set_ylabel(ylabel) ax.set_xlabel(xlabel) ax.margins(margins) if show_conf_int and self.conf_int is not None: ax.fill_between( self.x_test.squeeze(), self.conf_int[:, 0], self.conf_int[:, 1], alpha=lineage_alpha, color=lineage_color, linestyle="--", ) if (show_cbar and not hide_cells and not same_plot and not np.allclose(self.w_all, 1)): norm = mcolors.Normalize(vmin=vmin, vmax=vmax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2.5%", pad=0.1) _ = mpl.colorbar.ColorbarBase(cax, norm=norm, cmap=abs_prob_cmap, label="absorption probability") if save is not None: save_fig(fig, save) if return_fig: return fig
def plot( self, figsize: Tuple[float, float] = (8, 5), same_plot: bool = False, hide_cells: bool = False, perc: Tuple[float, float] = None, abs_prob_cmap: mcolors.ListedColormap = cm.viridis, cell_color: str = "black", lineage_color: str = "black", alpha: float = 0.8, lineage_alpha: float = 0.2, title: Optional[str] = None, size: int = 15, lw: float = 2, cbar: bool = True, margins: float = 0.015, xlabel: str = "pseudotime", ylabel: str = "expression", conf_int: bool = True, lineage_probability: bool = False, lineage_probability_conf_int: Union[bool, float] = False, lineage_probability_color: Optional[str] = None, dpi: int = None, fig: mpl.figure.Figure = None, ax: mpl.axes.Axes = None, return_fig: bool = False, save: Optional[str] = None, **kwargs, ) -> Optional[mpl.figure.Figure]: """ Plot the smoothed gene expression. Parameters ---------- figsize Size of the figure. same_plot Whether to plot all trends in the same plot. hide_cells Whether to hide the cells. perc Percentile by which to clip the absorption probabilities. abs_prob_cmap Colormap to use when coloring in the absorption probabilities. cell_color Color for the cells when not coloring absorption probabilities. lineage_color Color for the lineage. alpha Alpha channel for cells. lineage_alpha Alpha channel for lineage confidence intervals. title Title of the plot. size Size of the points. lw Line width for the smoothed values. cbar Whether to show colorbar. margins Margins around the plot. xlabel Label on the x-axis. ylabel Label on the y-axis. conf_int Whether to show the confidence interval. lineage_probability Whether to show smoothed lineage probability as a dashed line. Note that this will require 1 additional model fit. lineage_probability_conf_int Whether to compute and show smoothed lineage probability confidence interval. If :paramref:`self` is :class:`cellrank.ul.models.GAMR`, it can also specify the confidence level, the default is `0.95`. Only used when ``show_lineage_probability=True``. lineage_probability_color Color to use when plotting the smoothed ``lineage_probability``. If `None`, it's the same as ``lineage_color``. Only used when ``show_lineage_probability=True``. dpi Dots per inch. fig Figure to use, if `None`, create a new one. ax: :class:`matplotlib.axes.Axes` Ax to use, if `None`, create a new one. return_fig If `True`, return the figure object. save Filename where to save the plot. If `None`, just shows the plots. **kwargs Keyword arguments for :meth:`matplotlib.axes.Axes.legend`, e.g. to disable the legend, specify ``loc=None``. Only available when ``show_lineage_probability=True``. Returns ------- %(just_plots)s """ if self.y_test is None: raise RuntimeError("Run `.predict()` first.") if fig is None or ax is None: fig, ax = plt.subplots(figsize=figsize, constrained_layout=True) if dpi is not None: fig.set_dpi(dpi) conf_int = conf_int and self.conf_int is not None hide_cells = (hide_cells or self.x_all is None or self.w_all is None or self.y_all is None) lineage_probability_color = (lineage_color if lineage_probability_color is None else lineage_probability_color) scaler = kwargs.pop( "scaler", self._create_scaler( lineage_probability, show_conf_int=conf_int, ), ) if lineage_probability: if ylabel in ("expression", self._gene): ylabel = f"scaled {ylabel}" vmin, vmax = None, None if not hide_cells: vmin, vmax = _minmax(self.w_all, perc) _ = ax.scatter( self.x_all.squeeze(), scaler(self.y_all.squeeze()), c=cell_color if same_plot or np.allclose(self.w_all, 1.0) else self.w_all.squeeze(), s=size, cmap=abs_prob_cmap, vmin=vmin, vmax=vmax, alpha=alpha, ) if title is None: title = (f"{self._gene} @ {self._lineage}" if self._lineage is not None else f"{self._gene}") ax.plot(self.x_test, scaler(self.y_test), color=lineage_color, lw=lw, label=title) if title is not None: ax.set_title(title) if ylabel is not None: ax.set_ylabel(ylabel) if xlabel is not None: ax.set_xlabel(xlabel) ax.margins(margins) if conf_int: ax.fill_between( self.x_test.squeeze(), scaler(self.conf_int[:, 0]), scaler(self.conf_int[:, 1]), alpha=lineage_alpha, color=lineage_color, linestyle="--", ) if (lineage_probability and not isinstance(self, FittedModel) and not np.allclose(self.w, 1.0)): from cellrank.pl._utils import _is_any_gam_mgcv model = deepcopy(self) model._y = self._reshape_and_retype(self.w).copy() model = model.fit() if not lineage_probability_conf_int: y = model.predict() elif _is_any_gam_mgcv(model): y = model.predict( level=lineage_probability_conf_int if isinstance( lineage_probability_conf_int, float) else 0.95) else: y = model.predict() model.confidence_interval() ax.fill_between( model.x_test.squeeze(), model.conf_int[:, 0], model.conf_int[:, 1], alpha=lineage_alpha, color=lineage_probability_color, linestyle="--", ) handle = ax.plot( model.x_test, y, color=lineage_probability_color, lw=lw, linestyle="--", zorder=-1, label="probability", ) if kwargs.get("loc", "best") is not None: ax.legend(handles=handle, **kwargs) if (cbar and not hide_cells and not same_plot and not np.allclose(self.w_all, 1.0)): norm = mcolors.Normalize(vmin=vmin, vmax=vmax) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2%", pad=0.1) _ = mpl.colorbar.ColorbarBase( cax, norm=norm, cmap=abs_prob_cmap, ticks=np.linspace(norm.vmin, norm.vmax, 5), ) if save is not None: save_fig(fig, save) if return_fig: return fig