Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn bug? Inconsistent in heatmap plotting

This code:

%matplotlib inline

#import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import seaborn as sns #; sns.set()

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")

sns.heatmap(flights, annot=True, linewidths=.2, fmt="d")

#plt.show()

Will get a result looks like the official result (See/verify it here):

enter image description here

However, if I disable the inline plotting and enable the plt.show() the result will look like this instead:

Annotated heatmaps?

I.e., the annotation is gone except one cell and y-label orientation is wrong if inline plotting is disabled. Since that's the only change I made, I think this is a bug with seaborn, that it cannot produce consistent results.

Can anyone confirm this please?
And is there any possible fix please?

Update, thanks to Sergey for his feedback, here are my versions of everything relevant:

Python: 3.5.0 |Anaconda 2.4.0 (64-bit)| (default, Dec  1 2015, 11:46:22) [MSC v.1900 64 bit (AMD64)]
IPython: 4.0.0
Matplotlib: 1.5.0
Seaborn: 0.6.0

So I think it is either Python3, or Matplotlib: 1.5 that is causing the problem. I'll add the Python3 tag, just in case.

Thanks

like image 331
xpt Avatar asked Dec 19 '15 21:12

xpt


1 Answers

This bug has actually been reported in the Seaborn GitHub page here. From the comments there, the problem appears when matplotlib is using the MacOSX, TkAgg or QtAgg backends (also when using %matplotlib notebook in a IPython/Jupyter notebook).

In principle, changing the backend to a different one should make the plot work as expected (as it is shown in your first figure). From matplotlib's documentation, you can check what backend you are using with

matplotlib.get_backend()

and change it to a different one with

matplotlib.use()

Unfortunately, it seems that this problem appears with all the available interactive backends. If that is what you need, you will probably have to wait until the bug is solved (you can track any advances on that on the GitHub page).

If you are happy producing a PNG/PDF file instead of an interactive window for your plot, the Agg backend should work correctly with a slight change to your code:

import matplotlib
matplotlib.use("Agg")

import matplotlib.pyplot as plt
import seaborn as sns #; sns.set()

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")

sns.heatmap(flights, annot=True, linewidths=.2, fmt="d")

plt.savefig("heatmap.png")
like image 166
Pablo Arnalte-Mur Avatar answered Oct 04 '22 07:10

Pablo Arnalte-Mur