Repository navigation
Conversation
…or'. Relative sizes had been adapted to work in most conditions
…dot plot. Added options to plot pvalues and logfoldchanges
…ws and columns. Fixed order of rows and columns to match the ouput of matrixplot.
ivirshup
left a comment
There was a problem hiding this comment.
Gave this a quick once over.
One other point, I don't like that you can't see the size of the circle when the square plot background is white. Would you mind explaining this new style?
to correctly plot the results from sc.tl.rank_genes_groups is better to report the results for all genes (n_genes). The default is to keep the top 100 genes per group. Thus, for many genes, the pvalue, logfoldchange etc in other groups is not saved.
I completely agree. I personally think we should remove the top genes parameter, or at least default to all, from rank genes groups. The user can very easily filter on their own later. Thoughts @Koncopd?
| elif standard_scale is None: | ||
| pass | ||
| else: | ||
| logg.warning('Unknown type for standard_scale, ignored') |
There was a problem hiding this comment.
Could this be an ValueError instead?
| category_height = category_width = 0.35 | ||
| legends_width = 1.2 | ||
| dendro_width = 0.8 if dendrogram else 0 | ||
| if figsize is None: |
There was a problem hiding this comment.
This might explain some issues I've had with writing out dot plots.
What happens if I don't pass figsize, but specify it with:
with plt.rc_context({"figure.figsize": (5, 5)}):
sc.pl.dotplot(adata, ...)There was a problem hiding this comment.
Dotplot (and matrixplot, heatmap) by default override the rcParams['figure.figsize'], otherwise the output figure will look very bad. I know that this is a different behavior compared to sc.pl.scatter.
The solution is to pass figsize as argument in case you want to use custom values.
Do you have any other idea?
…956). Now is possible to do sc.pl.dotplot(adata, ...).add_dendrogram(size=1).show()
…code as `sc.pl.DotPlot`.
…ly the indices were kept. Useful to sort categories by name
…gories by pandas index sorting (iloc -> loc).
…max, color_map etc). Added `color` parameter to `.add_totals()`.
…currently is only DotPlot.
…f `sc.pl.matrixplot` by MatrixPlot.
…coming for **kwds. Standardize use of 'cmap' instead of 'color_map'. 'cmap' is the standard use for matplotlib.
…s into dotplot. Added option to filter genes by min_logfoldchange while plotting.
|
I just added the class from scanpy.plotting._anndata import StackedViolin, DotPlot, MatrixPlot
adata = sc.datasets.pbmc68k_reduced()
markers = {'T-cell': ['CD3D', 'CD3E', 'IL32'], 'B-cell': ['CD79A', 'CD79B', 'MS4A1'], 'myeloid': ['CST3', 'LYZ']}
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(19,5), gridspec_kw={'width_ratios': [.8, 1, 1]})
StackedViolin(adata, markers, groupby='bulk_labels', ax=ax1).add_dendrogram(True).swap_axes(True).show(False)
DotPlot(adata, markers, groupby='bulk_labels', ax=ax2).add_dendrogram(True).swap_axes(True).show(False)
_ = MatrixPlot(adata, markers, groupby='bulk_labels', ax=ax3).add_dendrogram(True).swap_axes(True).show(False) |
ivirshup
left a comment
There was a problem hiding this comment.
Sorry for taking so long to get back to you on this! Overall, I like the idea behind this PR. We have a bunch of similar kinds of plots (those with categorical axes) and it would be great if there was an easy way to consistently add marginal plots to them.
This PR takes a lot of effort to review. This PR adds a lot of code, and that code isn't all the easiest to follow. I think this is largely due to matplotlib generally resulting in hard to follow code, but I think the structure of the new code also needs more consideration. Because of that, I'm going to start with a more broad review, before diving into the code specifics that much.
Could you describe your mental model for these new classes? They seem to do a lot of things and store a lot of data. I'd like to see this cut down, but would want to hear the way you're thinking about it first. To me, these seem very similar to the ideas in seaborns ClusterGrid (https://github.com/mwaskom/seaborn/blob/5498cdb2f145b15a85adac0c8ff233656f52a943/seaborn/matrix.py#L779) and jointplot (https://github.com/mwaskom/seaborn/blob/7216552848c83b678481d5bca01a180120b0301e/seaborn/axisgrid.py#L2130) type plots. I think that code could be a very good template for how this could be structured.
I'm currently not sure I'd be up for making the object based plotting API public. One of the things that the libraries @flying-sheep mention have in common is very well defined models for the objects. In particular, I think altair does a great job with this. I would like to make sure this model is sound before making it something we promise to support. It could definitely be used internally before that.
Organization
Could this code start going into multiple files now? Github reviewing tools were not made for 5000 line files.
My main issue with the plotting code is more maintainability than number of features. I would like there to be much more clear and consistently used abstractions here. One example of that would be separating data processing from matplotlib code as much as possible. This is an area I'll address more in further review, but it's a heads up about what my priorities are here.
These classes have a lot of attributes, which make the mental overhead of figuring out what's going on in the code pretty high. Can this be reduced?
Do we have some style policies for black or the defaults are fine?
Black settings are defined in our pyproject.toml / .editorconfig.
API
I don't think results for any plots should noticeably change from this PR. Is that happening? I get the impression you want to use a diverging palette by default?
I'm not sure I like the swap_axes function. It assumes the user knows what the default axes are. I'd prefer if the x and y axes were passed as arguments to the initial function. Similar to sns.joinplot. Maybe this could end up looking like:
(
sc.pl.DotPlot(adata, x="leiden", y=gene_list, color="mean", size="frac")
.add_dendrogram(axis="y")
)Tests
This needs a lot of tests. Some ideas to start out:
- Should dendrograms look any different for different main plots? What should be the same?
- Ditto for legends.
- Does making one of these plots change any global state (i.e.
matplotlibsrc_params)? - Does the order which methods are called matter? Should it?
| if values_to_plot is not None: | ||
| # by default, the values to plot are the expression | ||
| # values. However, if rank_genes_groups has been computed | ||
| # then, also pvalues and logfold change can be plotted | ||
| df_list = [] | ||
| for group in group_names: | ||
| # df = rank_genes_groups_df(adata, group, key=key) | ||
| # TODO: other means of filtering genes are needed. | ||
| # maybe do it in place for the image | ||
| df = rank_genes_groups_df(adata, group, key='rank_genes_groups') | ||
| df['group'] = group | ||
| df_list.append(df) | ||
|
|
||
| values_df = pd.concat(df_list) | ||
| values_df = pd.pivot(values_df, index='names', columns='group', | ||
| values=values_to_plot).fillna(1) | ||
|
|
||
| if values_to_plot in ['pvals', 'pvals_adj']: | ||
| values_df = -1 * np.log10(values_df) | ||
| kwds.setdefault('color_title', "-log10(pvalue") | ||
|
|
||
| # TODO. n_genes for tl.rank_genes needs to be larger to get good results | ||
| values_df = values_df.loc[gene_names].T |
There was a problem hiding this comment.
Why run this here, and not in dotplot? Especially since that's the only function that get's passed this dataframe?
I would also subset the dataframes to the genes prior to concatenating and pivoting them. This will mean there's less allocation to do in those steps.
There was a problem hiding this comment.
This is only relevant when rank_genes_groups has been called. Thus is only relevant on that context.
| self.kwds = kwds | ||
|
|
||
| def style(self, | ||
| color_map: str = 'RdBu_r', |
There was a problem hiding this comment.
The default color for dot plots (but really most cases we have) should not default to diverging. Diverging requires a meaningful middle value, which we can't assume in many cases. Log fold change can be diverging, expression level can't unless it's been scaled.
There was a problem hiding this comment.
The default continues to be a sequential color range in the wrap function sc.pl.dotplot. However, a disadvantage of a sequential colormap in this type of plot is that the smallest dots usually can not be differentiated from the background as they tend to have the lighter color. But I can try with some of the sequential colormaps like 'autumn' which do not have very light colors.
There was a problem hiding this comment.
Sounds good. I think viridis can be fine for this as well, or a version of reds where the lowest value is light grey.
| def _plot_size_legend( | ||
| self, | ||
| size_legend_ax: Axes, | ||
| dot_min: float, | ||
| dot_max: float | ||
| ): | ||
| # for the dot size legend, use step between dot_max and dot_min | ||
| # based on how different they are. | ||
| diff = dot_max - dot_min | ||
| if 0.3 < diff <= 0.6: | ||
| step = 0.1 | ||
| elif diff <= 0.3: | ||
| step = 0.05 | ||
| else: | ||
| step = 0.2 | ||
| # a descending range that is afterwards inverted is used | ||
| # to guarantee that dot_max is in the legend. | ||
| size_range = np.arange(dot_max, dot_min, step * -1)[::-1] | ||
| if dot_min != 0 or dot_max != 1: | ||
| dot_range = dot_max - dot_min | ||
| size_values = (size_range - dot_min) / dot_range | ||
| else: | ||
| size_values = size_range | ||
| size = (size_values * 10) ** 2 | ||
| size += self.smallest_dot | ||
|
|
||
| # plot size bar | ||
| size_legend_ax.scatter( | ||
| np.arange(len(size)) + 0.5, | ||
| np.repeat(0, len(size)), | ||
| s=size, color='gray', | ||
| edgecolor='black' | ||
| ) | ||
| size_legend_ax.set_xticks(np.arange(len(size)) + 0.5) | ||
| labels = ["{}".format(int(x*100)) for x in size_range] | ||
| if dot_max < 1: | ||
| labels[-1] = ">" + labels[-1] | ||
| size_legend_ax.set_xticklabels(labels) | ||
| size_legend_ax.set_xticklabels(["{}".format(int(x*100)) for x in size_range], | ||
| fontsize='small') | ||
|
|
||
| # remove y ticks and labels | ||
| size_legend_ax.tick_params( | ||
| axis='y', left=False, labelleft=False, labelright=False | ||
| ) | ||
|
|
||
| # remove surrounding lines | ||
| size_legend_ax.spines['right'].set_visible(False) | ||
| size_legend_ax.spines['top'].set_visible(False) | ||
| size_legend_ax.spines['left'].set_visible(False) | ||
| size_legend_ax.spines['bottom'].set_visible(False) | ||
| size_legend_ax.grid(False) | ||
|
|
||
| ymin, ymax = size_legend_ax.get_ylim() | ||
| size_legend_ax.set_ylim(-0.9, 4) | ||
| size_legend_ax.set_title(self.size_title, y=ymax + 0.25, | ||
| size='small') | ||
|
|
||
| xmin, xmax = size_legend_ax.get_xlim() | ||
| size_legend_ax.set_xlim(xmin, xmax + 0.5) |
There was a problem hiding this comment.
I like this function.
It takes all of the information it needs as arguments, and its a very small set of arguments. It does one small well defined thing?
Why is it a method?
There was a problem hiding this comment.
In contrast to just being a function?
…o fully integrate it in the object model.
…es as this simplifies the code
|
This PR is replaced by #1210 |

This PR addresses issues from #562 #1103
Here is a list of changes for
sc.pl.dotplotand also forsc.pl.rank_genes_groups_dotplot:sc.rank_genes_groupscan be plotted.swap_axeshas been added.sc.pl.dotplot. Now is possible to dosc.pl.DotPlot(adata, ....).add_dendrogram(size=1.2).swap_axes().show().Open issues:
sc.tl.rank_genes_groupsis better to report the results for all genes (n_genes). The default is to keep the top 100 genes per group. Thus, for many genes, the pvalue, logfoldchange etc in other groups is not saved.stylethat has two optionssquare coloranddot color.Update
The following is now possible (notice the method chaining):
TODO: