Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plt.tight_layout() with sns.clustermap

Seaborns clustermap doesn't work with plt.tight_layout().

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

np.random.seed(98)
df = pd.DataFrame(np.random.rand(10,10))
cm = sns.clustermap(df)

plt.tight_layout()
plt.show()

gives the following error ValueError: max() arg is an empty sequence. I've also used sns.heatmap() with the exact same data set and this gave no errors. Is there a work around? Note: The actual labels I'm using are a lot longer than the ones in this example but the codes too long to show. Thanks for any help!

like image 403
Michael Berry Avatar asked Dec 09 '15 12:12

Michael Berry


People also ask

Does tight_layout work with clustermap?

I don't think tight_layout works with clustermap. However, from the sns.clustermap documentation, it says that: The returned object has a savefig method that should be used if you want to save the figure object without clipping the dendrograms.

What is the use of tight_layout in Matplotlib?

tight_layout automatically adjusts subplot params so that the subplot (s) fits in to the figure area. This is an experimental feature and may not work for some cases. It only checks the extents of ticklabels, axis labels, and titles.

Does tight_layout work with subplots created from gridspec?

In general, subplots created from the gridspec ( Customizing Figure Layouts Using GridSpec and Other Functions) will work. Although not thoroughly tested, it seems to work for subplots with aspect != "auto" (e.g., axes with images). tight_layout considers all artists on the axes by default.

What are the alternatives to tight_layout?

An alternative to tight_layout is constrained_layout. In matplotlib, the location of axes (including subplots) are specified in normalized figure coordinates. It can happen that your axis labels or titles (or sometimes even ticklabels) go outside the figure area, and are thus clipped. To prevent this, the location of axes needs to be adjusted.


2 Answers

I got this error when I placed the plt.tight_layout() before the plt.plot() and plt.xlabel() I just had to move it to the last command before plt.show() and it worked.

like image 31
ashley Avatar answered Oct 18 '22 22:10

ashley


Another part of the error is the message:

This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.

I don't think tight_layout works with clustermap. However, from the sns.clustermap documentation, it says that:

The returned object has a savefig method that should be used if you want to save the figure object without clipping the dendrograms.

So, in your example, you could use cm.savefig('myfigure.png'), which seems to perform similar actions to tight_layout.

like image 68
tmdavison Avatar answered Oct 18 '22 22:10

tmdavison