dpeerlab / Palantir

Single cell trajectory detection
https://palantir.readthedocs.io
GNU General Public License v2.0
226 stars 52 forks source link

Error while running plot_gene_trends #118

Closed ryanhchung closed 9 months ago

ryanhchung commented 1 year ago

Hi Team,

From my understanding, it is possible not to specify genes in the plot_gene_trends function. In the tutorial, you guys already used known genes for your data but I want to discover unbiased gene trends so I didn't use it, and I got this error:

palantir.plot.plot_gene_trends(adata_331)
plt.show()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/IPython/core/formatters.py:340, in BaseFormatter.__call__(self, obj)
    338     pass
    339 else:
--> 340     return printer(obj)
    341 # Finally look for special method names
    342 method = get_real_method(obj, self.print_method)

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/IPython/core/pylabtools.py:152, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
    149     from matplotlib.backend_bases import FigureCanvasBase
    150     FigureCanvasBase(fig)
--> 152 fig.canvas.print_figure(bytes_io, **kw)
    153 data = bytes_io.getvalue()
    154 if fmt == 'svg':

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backend_bases.py:2336, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2329     bbox_inches = rcParams['savefig.bbox']
   2331 if (self.figure.get_layout_engine() is not None or
   2332         bbox_inches == "tight"):
   2333     # we need to trigger a draw before printing to make sure
   2334     # CL works.  "tight" also needs a draw to get the right
   2335     # locations:
-> 2336     renderer = _get_renderer(
   2337         self.figure,
   2338         functools.partial(
   2339             print_method, orientation=orientation)
   2340     )
   2341     with getattr(renderer, "_draw_disabled", nullcontext)():
   2342         self.figure.draw(renderer)

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backend_bases.py:1598, in _get_renderer(figure, print_method)
   1595     print_method = stack.enter_context(
   1596         figure.canvas._switch_canvas_and_return_print_method(fmt))
   1597 try:
-> 1598     print_method(io.BytesIO())
   1599 except Done as exc:
   1600     renderer, = exc.args

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backend_bases.py:2232, in FigureCanvasBase._switch_canvas_and_return_print_method.<locals>.<lambda>(*args, **kwargs)
   2228     optional_kws = {  # Passed by print_figure for other renderers.
   2229         "dpi", "facecolor", "edgecolor", "orientation",
   2230         "bbox_inches_restore"}
   2231     skip = optional_kws - {*inspect.signature(meth).parameters}
-> 2232     print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
   2233         *args, **{k: v for k, v in kwargs.items() if k not in skip}))
   2234 else:  # Let third-parties do as they see fit.
   2235     print_method = meth

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:509, in FigureCanvasAgg.print_png(self, filename_or_obj, metadata, pil_kwargs)
    462 def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
    463     """
    464     Write the figure to a PNG file.
    465 
   (...)
    507         *metadata*, including the default 'Software' key.
    508     """
--> 509     self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:457, in FigureCanvasAgg._print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata)
    452 def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):
    453     """
    454     Draw the canvas, then save it using `.image.imsave` (to which
    455     *pil_kwargs* and *metadata* are forwarded).
    456     """
--> 457     FigureCanvasAgg.draw(self)
    458     mpl.image.imsave(
    459         filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",
    460         dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:394, in FigureCanvasAgg.draw(self)
    392 def draw(self):
    393     # docstring inherited
--> 394     self.renderer = self.get_renderer()
    395     self.renderer.clear()
    396     # Acquire a lock on the shared font cache.

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/_api/deprecation.py:384, in delete_parameter.<locals>.wrapper(*inner_args, **inner_kwargs)
    379 @functools.wraps(func)
    380 def wrapper(*inner_args, **inner_kwargs):
    381     if len(inner_args) <= name_idx and name not in inner_kwargs:
    382         # Early return in the simple, non-deprecated case (much faster than
    383         # calling bind()).
--> 384         return func(*inner_args, **inner_kwargs)
    385     arguments = signature.bind(*inner_args, **inner_kwargs).arguments
    386     if is_varargs and arguments.get(name):

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:411, in FigureCanvasAgg.get_renderer(self, cleared)
    409 reuse_renderer = (self._lastKey == key)
    410 if not reuse_renderer:
--> 411     self.renderer = RendererAgg(w, h, self.figure.dpi)
    412     self._lastKey = key
    413 elif cleared:

File ~/miniconda3/envs/cellrank/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py:84, in RendererAgg.__init__(self, width, height, dpi)
     82 self.width = width
     83 self.height = height
---> 84 self._renderer = _RendererAgg(int(width), int(height), dpi)
     85 self._filter_renderers = []
     87 self._update_methods()

ValueError: Image size of 700x7852500 pixels is too large. It must be less than 2^16 in each direction.

Do you have any idea how to solve this? If I misunderstood, please don't hesitate to tell me. As I want to know unbiased terminal states and gene trends, I didn't specify anything except starting cell to proceed.

Thank you!

ManuSetty commented 1 year ago

Hello

By applying this function to the entire dataset, the plotting function tries to plot the trend of every single gene which appears to be overloading the system. We recommend subsetting the genes to make this more amenable. Some options: (1) Highly variable genes, (2) List of all transcription factors, (3) Receptor or ligand genes.

katosh commented 1 year ago

Hello @ryanhchung,

Thanks for bringing this up. Applying the plotting function to the entire dataset can indeed be computationally intensive. @ManuSetty has already given valuable suggestions for subsetting genes—like focusing on highly variable genes, transcription factors, or receptor/ligand genes.

Additional Approaches

  1. Random Gene Selection: A representative random set of 100 genes can be displayed using:

    palantir.plot.plot_gene_trends(ad, ad.var.sample(100).index)
  2. Cluster-Based Overview: You can get a comprehensive view by clustering gene trends and then plotting them:

    palantir.presults.cluster_gene_trends(ad, branch_name)
    palantir.plot.plot_gene_trend_clusters(ad, branch_name)

    To find available branches, use:

    palantir.plot.plot_branch_selection(ad)
  3. Batch Plotting for All Genes: To plot all genes in batches:

    import numpy as np
    
    for genes in np.array_split(ad.var_names, ad.n_vars // 10):
        palantir.plot.plot_gene_trends(ad, genes)
        plt.show()

    Note: This will result in a large number of plots.

Please let us know if ay of our suggestions resolved your issue.

katosh commented 9 months ago

Closing due to inactivity.