Skip to content

[WIP] Dotplot (aka bubble plot) improvements - #1127

Closed
fidelram wants to merge 54 commits into
masterfrom
better_dotplot
Closed

fidelram wants to merge 54 commits into
masterfrom
better_dotplot

Conversation

@fidelram

@fidelram fidelram commented Mar 25, 2020 •

Copy link
Copy Markdown
Collaborator

This PR addresses issues from #562 #1103

Here is a list of changes for sc.pl.dotplot and also for sc.pl.rank_genes_groups_dotplot:

  • Colorbar and dot size legends had been improved. Now is also possible to set a title for them.
  • The dotplot functionality has been separated from the main function. This allows to take any two pandas dataFrames, one containing the color values and other containing the size to be plotted.
  • A new dotplot style is added, in which a background square is colored according to the colormap instead of the dot. The style can be chosen as parameter.
  • Now p-values, score and in general any parameter from sc.rank_genes_groups can be plotted.
  • swap_axes has been added.
  • update: method chaining was added to avoid explosion of parameters as suggested in Avoid argument explosion in plotting functions #956. The caveat is that a different name is needed to keep the current functionality of sc.pl.dotplot. Now is possible to do sc.pl.DotPlot(adata, ....).add_dendrogram(size=1.2).swap_axes().show().

image

image

Open issues:

  • we need a better way to filter the output from rank_genes_groups (and I would also consider a better name). One option is to filter while plotting.
  • 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.
  • added new parameters, for some I would be happy to have some feedback. One is style that has two options square color and dot color.

Update
The following is now possible (notice the method chaining):

adata = sc.datasets.pbmc68k_reduced()
markers = {'T-cell': ['CD3D', 'CD3E', 'IL32'], 'B-cell': ['CD79A', 'CD79B', 'MS4A1'], 'myeloid': ['CST3', 'LYZ']}
sc.pl.DotPlot(adata, markers, groupby='bulk_labels') \
               .add_totals(sort='descending', size=1.2) \
               .legend(color_title='log(UMI count+1)', width=1.6)\
               .style(color_map='RdBu_r', dot_min=0.3)\
               .show()

image

TODO:

  • Remove small secondary ticks
  • Adapt matrixplot to new object model
  • Adapt heatmap to object model
  • Adapt stackedviolin to object model
  • Incorporate modifications from Plotting overhaul #1116
  • Fix call from rank_genes_groups
  • 'black' code
  • Update docstrings
  • Update tests
  • Update tutorial and readthedocs

…ws and columns. Fixed order of rows and columns to match the ouput of matrixplot.
@fidelram fidelram mentioned this pull request Mar 25, 2020

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread scanpy/plotting/_anndata.py Outdated
elif standard_scale is None:
pass
else:
logg.warning('Unknown type for standard_scale, ignored')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be an ValueError instead?

Comment thread scanpy/plotting/_anndata.py Resolved
Comment thread scanpy/plotting/_anndata.py Outdated
category_height = category_width = 0.35
legends_width = 1.2
dendro_width = 0.8 if dendrogram else 0
if figsize is None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, ...)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread scanpy/plotting/_anndata.py Resolved
Comment thread scanpy/plotting/_anndata.py Resolved
fidelram added 17 commits March 26, 2020 13:12
…956). Now is possible to do sc.pl.dotplot(adata, ...).add_dendrogram(size=1).show()
…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()`.
@fidelram
fidelram marked this pull request as draft April 9, 2020 09:44
@fidelram

fidelram commented Apr 9, 2020

Copy link
Copy Markdown
Collaborator Author

I just added the class ViolinPlot to the group plots. Now is possible to do this:

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)

image

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. matplotlibs rc_params)?
  • Does the order which methods are called matter? Should it?

Comment thread scanpy/plotting/_tools/__init__.py Outdated
Comment on lines +390 to +412
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only relevant when rank_genes_groups has been called. Thus is only relevant on that context.

Comment thread scanpy/plotting/_anndata.py Outdated
self.kwds = kwds

def style(self,
color_map: str = 'RdBu_r',

@ivirshup ivirshup Apr 3, 2020 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good. I think viridis can be fine for this as well, or a version of reds where the lowest value is light grey.

Comment thread scanpy/plotting/_anndata.py Outdated
Comment on lines +4135 to +4194
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In contrast to just being a function?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

Comment thread scanpy/plotting/_utils.py Resolved
Comment thread scanpy/plotting/_tools/__init__.py Resolved
Comment thread scanpy/plotting/_anndata.py Resolved
@fidelram

Copy link
Copy Markdown
Collaborator Author

This PR is replaced by #1210

@fidelram fidelram closed this May 13, 2020
@fidelram
fidelram deleted the better_dotplot branch July 22, 2020 14:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants