TooLateMate
TooLateMate

Reputation: 167

Seaborn clustermap as a subplot

The seaborn clustermap seems to be a figure-level plot which creates its own figure and axes internally.

I would like to use a cluster as a subplot, to be able to add extra plots on the same figure (for instance, a boxplot at the top of the heatmap).

How can I achieve this ?

Thank you

Example for a clustermap:

import numpy as np
import pandas as pd
import seaborn as sns

nb_features = 20

tmp = [v for v in zip(np.repeat(['A', 'B'], 5), 
       np.hstack([range(5), range(5)]))]
index = pd.MultiIndex.from_tuples(tmp)

df = pd.DataFrame(np.vstack([np.random.rand(5, nb_features) + 1, 
                             np.random.rand(5, nb_features) - 1]), index=index).T

# Returns a seaborn.matrix.ClusterGrid
cax = sns.clustermap(df)

enter image description here

Upvotes: 3

Views: 2791

Answers (1)

JohanC
JohanC

Reputation: 80299

You can add some space to the figure, e.g. via subplots_adjust(). Then you can add a new axis via fig.add_axes([x, y, width, height]) (expressed in figure coordinates).

Here is an example:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

sns.set_theme(color_codes=True)
iris = sns.load_dataset("iris")
species = iris.pop("species")
g = sns.clustermap(iris)
g.fig.set_size_inches(20, 10)
g.fig.subplots_adjust(right=0.5)
ax = g.fig.add_axes([0.55, 0.05, 0.42, 0.92])
ax.plot(np.random.randn(1000).cumsum())
plt.plot()

example clustermap with new subplot

Upvotes: 1

Related Questions