I've stumbled upon the following issue when trying to represent 2 clusterings at the same time:
I used sns.clustermap to generate a heatmap with hierarchical clustering. In addition, I performed another clustering and represent the resulting clusters in the plot. I now would like to rotate the arms of the dendrogram so that the resulting groups go together, i.e. the colors in the plot's left blue-green-red column are not separated as they are now. The assumption is always that there is a way to arrange arms without violating the hierarchy of the tree. Here's a quick minimal example code to get the initial step that I want to modify:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage
# Generate 6-dimensional data
np.random.seed(0)
data = np.random.rand(50, 6)
df = pd.DataFrame(data, columns=[f'Dim_{i+1}' for i in range(6)])
# Perform hierarchical clustering
linkage_matrix = linkage(df, method='ward')
# Perform k-means clustering
kmeans = KMeans(n_clusters=3, random_state=0).fit(df)
clusters = kmeans.labels_
# Create a custom colormap for clusters
cluster_colormap = sns.color_palette("Set1", len(np.unique(clusters)))
# Plot using seaborn's clustermap
sns.clustermap(df, row_linkage=linkage_matrix, col_cluster=False, row_colors=[cluster_colormap[i] for i in clusters])
plt.show()
I think there should either be a tool or at least a general approach to e.g. use a sorting-algorithm-like approach to rotate the arms and check for the closeness of colors, but I still can't figure it out.
