Skip to content

Commit

Permalink
Improved legends
Browse files Browse the repository at this point in the history
  • Loading branch information
artuurC committed Aug 21, 2023
1 parent 2f63eaf commit f86aacd
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 18 deletions.
10 changes: 1 addition & 9 deletions src/FlowSOM/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,6 @@ def update_derived_values(self):
df = self.mudata["cell_data"].X[self.mudata["cell_data"].X[:, 0].argsort()]
df = np.c_[self.mudata["cell_data"].obs["metaclustering"], df]
metacluster_median_values = pd.DataFrame(df).groupby(0).median()
"""metacluster_median_values = np.vstack(
[
np.median(df[df[:, 0] == cl + 1], axis=0)
if df[df[:, 0] == cl + 1].shape[0] != 0
else np.repeat(np.nan, df[df[:, 0] == cl + 1].shape[1])
for cl in range(self.mudata["cell_data"].uns["n_metaclusters"])
]
)"""
self.mudata["cluster_data"].uns["metacluster_MFIs"] = metacluster_median_values

return self
Expand Down Expand Up @@ -268,7 +260,7 @@ def metacluster(self, n_clus):
# metaclusters = (self.hierarchical_clustering(self.mudata["cluster_data"].obsm["codes"], n_clus)).astype(str)
metaclusters = self.consensus_hierarchical_clustering(self.mudata["cluster_data"].obsm["codes"], n_clus)
self.mudata["cell_data"].uns["n_metaclusters"] = n_clus
self.mudata["cluster_data"].obs["metaclustering"] = metaclusters
self.mudata["cluster_data"].obs["metaclustering"] = metaclusters.astype(str)
self.mudata["cell_data"].obs["metaclustering"] = np.asarray(
[np.array(metaclusters)[int(i)] for i in np.asarray(self.mudata["cell_data"].obs["clustering"])]
)
Expand Down
16 changes: 13 additions & 3 deletions src/FlowSOM/pl/plot_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,9 @@ def plot_variable(fsom, variable, cmap=FlowSOM_colors(), lim=None, title=None, *
n.set_linewidth(0.5)
n.set_zorder(2)
ax.add_collection(n)
ax, fig = add_legend(fig=fig, ax=ax, data=variable, title="Marker", cmap=cmap)
ax, fig = add_legend(
fig=fig, ax=ax, data=variable, title="Marker", cmap=cmap, location="upper left", bbox_to_anchor=(1.04, 1)
)
ax.axis("equal")
if title is not None:
plt.title(title)
Expand Down Expand Up @@ -218,7 +220,8 @@ def plot_marker(fsom, marker, ref_markers=None, lim=None, cmap=FlowSOM_colors(),
lim = (mfis[:, indices_markers].min(), mfis[:, indices_markers].max())
marker = list(get_channels(fsom, marker).keys())[0]
marker_index = np.where(fsom.get_cell_data().var_names == marker)[0][0]
plot_variable(fsom, variable=mfis[:, marker_index], cmap=cmap, lim=lim, **kwargs)
fig = plot_variable(fsom, variable=mfis[:, marker_index], cmap=cmap, lim=lim, **kwargs)
return fig


def plot_stars(fsom, markers=None, cmap=FlowSOM_colors(), title=None, **kwargs):
Expand Down Expand Up @@ -304,7 +307,14 @@ def plot_pies(

ax.axis("equal")
ax, fig = add_legend(
fig=fig, ax=ax, data=cell_types, title="", cmap=cmap, location="upper right", orientation="vertical"
fig=fig,
ax=ax,
data=cell_types,
title="",
cmap=cmap,
location="upper left",
orientation="vertical",
bbox_to_anchor=(1.04, 1),
)
if title is not None:
plt.title(title)
Expand Down
17 changes: 14 additions & 3 deletions src/FlowSOM/pl/plot_helper_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def gg_color_hue():
return cmap


def add_legend(fig, ax, data, title, cmap, location="best", orientation="horizontal", ticks=None, labels=None):
def add_legend(fig, ax, data, title, cmap, location="best", orientation="horizontal", bbox_to_anchor=None):
if data.dtype == np.float64 or data.dtype == np.int64:
norm = matplotlib.colors.Normalize(vmin=min(data), vmax=max(data))
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
Expand All @@ -40,7 +40,17 @@ def add_legend(fig, ax, data, title, cmap, location="best", orientation="horizon
Line2D([0], [0], marker="o", color="w", label=unique_data[i], markerfacecolor=colors[i], markersize=5)
for i in range(len(unique_data))
]
legend = plt.legend(handles=legend_elements, loc=location, frameon=False, title=title)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
legend = plt.legend(
handles=legend_elements,
loc=location,
frameon=False,
title=title,
bbox_to_anchor=bbox_to_anchor, # (1, 0.5),
fontsize="small",
title_fontsize="small",
)
plt.gca().add_artist(legend)
return ax, fig

Expand Down Expand Up @@ -124,7 +134,8 @@ def plot_FlowSOM(
data=background_values,
title="Background",
cmap=background_cmap,
location="lower right",
location="lower left",
bbox_to_anchor=(1.04, 0),
)

# Add MST
Expand Down
9 changes: 6 additions & 3 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,33 @@ def test_FlowSOM_type(FlowSOM_res):


def test_plot_stars(FlowSOM_res):
FlowSOM.pl.plot_stars(
pl = FlowSOM.pl.plot_stars(
FlowSOM_res,
background_values=FlowSOM_res.get_cluster_data().obs["metaclustering"],
view="MST",
equal_node_size=False,
)
pl.savefig("plotstars.pdf")


def test_plot_marker(FlowSOM_res):
FlowSOM.pl.plot_marker(
pl = FlowSOM.pl.plot_marker(
FlowSOM_res,
marker=["CD3"],
background_values=FlowSOM_res.get_cluster_data().obs["metaclustering"],
view="grid",
equal_node_size=True,
)
pl.savefig("plotmarker.pdf")


def test_plot_pies(FlowSOM_res, gating_results):
FlowSOM.pl.plot_pies(
pl = FlowSOM.pl.plot_pies(
FlowSOM_res,
cell_types=gating_results,
background_values=FlowSOM_res.get_cluster_data().obs["metaclustering"],
)
pl.savefig("plotpies.pdf")


def test_new_data(fcs):
Expand Down

0 comments on commit f86aacd

Please sign in to comment.