zktuong / ktplotspy

Python library for plotting Cellphonedb results. Ported from ktplots R package.
https://ktplotspy.readthedocs.io/
MIT License
46 stars 12 forks source link

AttributeError: QuadMesh.set() got an unexpected keyword argument 'adata' #43

Closed lihaowhusos closed 11 months ago

lihaowhusos commented 11 months ago

Hi, thank you for developing such a great package. I meet some problems in plotting my data with ktplotspy. The "adata" file is the one analyzed by cellphnedb. However, it donot work with ktplotspy. I run the plot like this:

kpy.plot_cpdb_heatmap(
        adata = adata,
        pvals = pvals,
        celltype_key = "cluster_2",
        figsize = (5,5),
        title = "Number of significant interactions",
        symmetrical = False,
    )

It created this error:

AttributeError                            Traceback (most recent call last)
Cell In[19], line 1
----> 1 kpy.plot_cpdb_heatmap(
      2         adata = adata,
      3         pvals = pvals,
      4         celltype_key = "cluster_2",
      5         figsize = (5,5),
      6         title = "Number of significant interactions",
      7         symmetrical = False,
      8     )

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/ktplotspy/plot/plot_cpdb_heatmap.py:108, in plot_cpdb_heatmap(pvals, degs_analysis, log1p_transform, alpha, linewidths, row_cluster, col_cluster, low_col, mid_col, high_col, cmap, title, return_tables, symmetrical, **kwargs)
    106     colmap = cmap
    107 if not return_tables:
--> 108     g = sns.clustermap(
    109         count_mat,
    110         row_cluster=row_cluster,
    111         col_cluster=col_cluster,
    112         linewidths=linewidths,
    113         tree_kws={"linewidths": 0},
    114         cmap=colmap,
    115         **kwargs
    116     )
    117     if title != "":
    118         g.fig.suptitle(title)

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/seaborn/matrix.py:1258, in clustermap(data, pivot_kws, method, metric, z_score, standard_scale, figsize, cbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, row_colors, col_colors, mask, dendrogram_ratio, colors_ratio, cbar_pos, tree_kws, **kwargs)
   1250     raise RuntimeError("clustermap requires scipy to be available")
   1252 plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize,
   1253                       row_colors=row_colors, col_colors=col_colors,
   1254                       z_score=z_score, standard_scale=standard_scale,
   1255                       mask=mask, dendrogram_ratio=dendrogram_ratio,
   1256                       colors_ratio=colors_ratio, cbar_pos=cbar_pos)
-> 1258 return plotter.plot(metric=metric, method=method,
   1259                     colorbar_kws=cbar_kws,
   1260                     row_cluster=row_cluster, col_cluster=col_cluster,
   1261                     row_linkage=row_linkage, col_linkage=col_linkage,
   1262                     tree_kws=tree_kws, **kwargs)

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/seaborn/matrix.py:1142, in ClusterGrid.plot(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, tree_kws, **kws)
   1139     yind = np.arange(self.data2d.shape[0])
   1141 self.plot_colors(xind, yind, **kws)
-> 1142 self.plot_matrix(colorbar_kws, xind, yind, **kws)
   1143 return self

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/seaborn/matrix.py:1093, in ClusterGrid.plot_matrix(self, colorbar_kws, xind, yind, **kws)
   1091 # Setting ax_cbar=None in clustermap call implies no colorbar
   1092 kws.setdefault("cbar", self.ax_cbar is not None)
-> 1093 heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar,
   1094         cbar_kws=colorbar_kws, mask=self.mask,
   1095         xticklabels=xtl, yticklabels=ytl, annot=annot, **kws)
   1097 ytl = self.ax_heatmap.get_yticklabels()
   1098 ytl_rot = None if not ytl else ytl[0].get_rotation()

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/seaborn/matrix.py:459, in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, xticklabels, yticklabels, mask, ax, **kwargs)
    457 if square:
    458     ax.set_aspect("equal")
--> 459 plotter.plot(ax, cbar_ax, kwargs)
    460 return ax

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/seaborn/matrix.py:306, in _HeatMapper.plot(self, ax, cax, kws)
    303     kws.setdefault("vmax", self.vmax)
    305 # Draw the heatmap
--> 306 mesh = ax.pcolormesh(self.plot_data, cmap=self.cmap, **kws)
    308 # Set the axis limits
    309 ax.set(xlim=(0, self.data.shape[1]), ylim=(0, self.data.shape[0]))

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/__init__.py:1446, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
   1443 @functools.wraps(func)
   1444 def inner(ax, *args, data=None, **kwargs):
   1445     if data is None:
-> 1446         return func(ax, *map(sanitize_sequence, args), **kwargs)
   1448     bound = new_sig.bind(ax, *args, **kwargs)
   1449     auto_label = (bound.arguments.get(label_namer)
   1450                   or bound.kwargs.get(label_namer))

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/axes/_axes.py:6227, in Axes.pcolormesh(self, alpha, norm, cmap, vmin, vmax, shading, antialiased, *args, **kwargs)
   6223     C = C.ravel()
   6225 kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap'])
-> 6227 collection = mcoll.QuadMesh(
   6228     coords, antialiased=antialiased, shading=shading,
   6229     array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs)
   6230 collection._scale_norm(norm, vmin, vmax)
   6232 coords = coords.reshape(-1, 2)  # flatten the grid structure; keep x, y

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/collections.py:1939, in QuadMesh.__init__(self, coordinates, antialiased, shading, **kwargs)
   1936 self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
   1937 # super init delayed after own init because array kwarg requires
   1938 # self._coordinates and self._shading
-> 1939 super().__init__(**kwargs)
   1940 self.set_mouseover(False)

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/collections.py:201, in Collection.__init__(self, edgecolors, facecolors, linewidths, linestyles, capstyle, joinstyle, antialiaseds, offsets, offset_transform, norm, cmap, pickradius, hatch, urls, zorder, **kwargs)
    198 self._offset_transform = offset_transform
    200 self._path_effects = None
--> 201 self._internal_update(kwargs)
    202 self._paths = None

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/artist.py:1223, in Artist._internal_update(self, kwargs)
   1216 def _internal_update(self, kwargs):
   1217     """
   1218     Update artist properties without prenormalizing them, but generating
   1219     errors as if calling `set`.
   1220 
   1221     The lack of prenormalization is to maintain backcompatibility.
   1222     """
-> 1223     return self._update_props(
   1224         kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
   1225         "{prop_name!r}")

File ~/miniconda3/envs/cpdb/lib/python3.8/site-packages/matplotlib/artist.py:1197, in Artist._update_props(self, props, errfmt)
   1195             func = getattr(self, f"set_{k}", None)
   1196             if not callable(func):
-> 1197                 raise AttributeError(
   1198                     errfmt.format(cls=type(self), prop_name=k))
   1199             ret.append(func(v))
   1200 if ret:

AttributeError: QuadMesh.set() got an unexpected keyword argument 'adata'
zktuong commented 11 months ago

hi @lihaowhusos, my apologies. i didn't update the tutorial. the new way to call plot_cpdb_heatmap does not require adata nor celltype_key

so your command can simply be:

kpy.plot_cpdb_heatmap(
        pvals = pvals,
        figsize = (5,5),
        title = "Number of significant interactions",
        symmetrical = False,
    )
lihaowhusos commented 11 months ago

@zktuong Thank you very much for your response. I tried the code as you suggested and I was able to successfully get the images.