Home > OS >  Can I overlay a matplotlib contour over a seaborn heatmap?
Can I overlay a matplotlib contour over a seaborn heatmap?

Time:12-09

I have a heatmap done in seaborn and a contour plotted via matplotlib.pyplot.

Is it possible to overlay the two?

CodePudding user response:

Seaborn uses matplotlib under the hood. You can combine seaborn plots as if they were directly created by matplotlib. To draw onto the same subplot, the same ax should be used. To align the centers of the heatmap cells with the contour lines, you need to add 0.5 to the x and the y coordinates.

Here is an example to get you started:

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
from scipy.ndimage.filters import gaussian_filter

data = gaussian_filter(np.random.randn(20, 40), sigma=2)

fig, ax = plt.subplots(figsize=(15, 5))
sns.heatmap(data=data, cbar_kws={'pad': 0.02}, ax=ax)
ax.contour(np.arange(.5, data.shape[1]), np.arange(.5, data.shape[0]), data, colors='yellow')
plt.show()

combining sns.heatmap with plt.contour

  • Related