Plotting seaborn heatmap from XYZ data saved as different sized numpy arrays

Viewed 2382

I have three arrays from a certain experiment that looks like the following

X : array of shape 19 X 1

Y : array of shape 350 X 1

Z : array of shape 350 X 19

If I do the following:

sns.heatmap(Z,cmap='jet', cbar=True);

The map is correct but X and Y axis tick labels are not correct.

Any idea how I can include all three (X, Y, and Z) information in the heatmap?

Edit:

say,

import numpy as np
import seaborn as sns

X = np.arange(5,190,10, dtype= int)
Y = np.arange(450,800,1)
Z = np.random.rand(350,19)



sns.heatmap(Z)

This form does not consider X and Y values for plotting Z. I would want a way to plot the Z values at the corresponding X and Y values. As if, Z = f(X,Y).

1 Answers

Directly creating a seaborn heatmap will result in too many yticklabels as seaborn creates categorical ticks.

sns.heatmap(Z, xticklabels=X, yticklabels=Y, square=False)

standard heatmap

With matplotlib, you can create a heatmap as:

plt.imshow(Z, extent=[X[0] - 5, X[-1] + 5, Y[0] - 0.5, Y[-1] + 0.5], 
           aspect='auto', cmap='magma', interpolation='nearest')
plt.colorbar()

For Seaborn to create the desired heatmap, a dataframe needs to be created with X as the columns and Y as the index:

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

X = np.arange(5, 190, 10, dtype=int)
Y = np.arange(450, 800, 1)
Z = np.random.rand(350, 19)

df = pd.DataFrame(data=Z, columns=X, index=Y)
sns.heatmap(df, square=False)
plt.show()

example plot

Note that for most applications, the 'jet' colormap is strongly advised against.

Related