Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Hierarchical clustering of the correlation matrix #19

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions mriqc_learn/viz/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ def plot_corrmat(
cbarlabel="",
symmetric=True,
figsize=None,
sort=False,
celprov marked this conversation as resolved.
Show resolved Hide resolved
**kwargs,
):
"""
Expand All @@ -204,14 +205,40 @@ def plot_corrmat(
A dictionary with arguments to `matplotlib.Figure.colorbar`. Optional.
cbarlabel
The label for the colorbar. Optional.
sort
celprov marked this conversation as resolved.
Show resolved Hide resolved
Flag to perform hierachical clustering on the correlation plot
**kwargs
All other arguments are forwarded to `imshow`.

"""
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

# Cluster rows (if arguments enabled)
if sort:
celprov marked this conversation as resolved.
Show resolved Hide resolved
import pandas as pd
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster

Z = linkage(data, 'complete', optimal_ordering=True)

dendrogram(Z, labels=data.columns, no_plot=True)

# Clusterize the data
threshold = 0.1
labels = fcluster(Z, threshold, criterion='distance')
# Keep the indices to sort labels
labels_order = np.argsort(labels)

# Build a new dataframe with the sorted columns
for idx, i in enumerate(data.columns[labels_order]):
if idx == 0:
clustered = pd.DataFrame(data[i])
else:
df_to_append = pd.DataFrame(data[i])
clustered = pd.concat([clustered, df_to_append], axis=1)
data = clustered
Copy link
Member

Choose a reason for hiding this comment

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

Numpy should be sufficient to reorder, something like

Suggested change
# Build a new dataframe with the sorted columns
for idx, i in enumerate(data.columns[labels_order]):
if idx == 0:
clustered = pd.DataFrame(data[i])
else:
df_to_append = pd.DataFrame(data[i])
clustered = pd.concat([clustered, df_to_append], axis=1)
data = clustered
data = np.take(data, labels_order, axis=0)

Q2 - don't you want to also sort the rows?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Wow very fast, thanks.
The panda implementation reorder both the rows and the columns.

Copy link
Member

Choose a reason for hiding this comment

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

Okay, I think np.take will then work for you with something like (labels_order, labels_order) or zip((labels_order, labels_order)) for the indexes and no axis argument.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Unfortunately, none of the suggestions work and with a quick search on internet, I couldn't figure out how to reorder both rows and columns in a np.array. I thus suggest we keep the panda implementation.

Copy link
Member

Choose a reason for hiding this comment

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

I think this is easier than you think:

reordered_idx = (0, 1, 2, 4, 5, 3, 6, 7, 8, 9)
data.take(indices=reordered_idx, axis=0).take(indices=reordered_idx, axis=1)

The only caveat is that you need to do the reordering on the full correlation matrix, and only after the reordering drop the upper triangle (if you want to do so).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thanks a lot, it works with this suggestion. I really could not figure out how to do the reordering on np.array.
It indeed greatly simplifies the code.
Can I merge the PR now?


if hasattr(data, "columns"):
col_labels = data.columns.tolist()
col_labels = data.columns
data = data.values

if figsize is not None:
Expand All @@ -220,6 +247,7 @@ def plot_corrmat(
if not ax:
ax = plt.gca()

# If matrix is symmetric, keep only lower triangle
if symmetric:
data[np.triu(np.ones(data.shape, dtype=bool))] = np.nan

Expand Down Expand Up @@ -252,7 +280,7 @@ def plot_corrmat(
ax.tick_params(top=False, bottom=True, labeltop=False, labelbottom=True)

# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", rotation_mode="anchor")
plt.setp(ax.get_xticklabels(), rotation=90, ha="right", va="center", rotation_mode="anchor")

# Turn spines off and create white grid.
ax.spines[:].set_visible(False)
Expand Down