Heatmap
Now that we have this we can create a heatmap from seaborn, with seaborn.heatmap()
sns.heatmap(pivot)
plt.show()
We could also write the numbers for each cell over the cell by using annot=True
sns.heatmap(pivot, annot=True)
plt.show()
We can invert the axis by setting the heatmap call equal to a variable then calling invert_yaxis() axis on it….
ax = sns.heatmap(pivot, annot=True)
ax.invert_yaxis()
plt.show()
Another common use for heatmaps is to map correlation between variables. Let’s get some variables from FRED.
df = pdr.fred.FredReader(["FEDFUNDS","CPIAUCSL","AAA","UNRATE","GS5","MSACSR","PCE","M2NS"],start,end).read()
df["CPIAUCSL"] = df["CPIAUCSL"].pct_change()
df["PCE"] = df["PCE"].pct_change()
df["M2NS"] = df["M2NS"].pct_change()
df.dropna(inplace=True)
df.columns = ["Fed Funds","CPI Change","AAA Yield","Unemployment","5 Year Treasury","Housing Supply","Consumption Change","M2 Money Change"]
df
Let’s find the correlation.
corr = df.corr()
corr
We can now feed this to the heatmap call, let’s see what it looks like.
sns.heatmap(corr)
plt.show()
And annotate.
sns.heatmap(corr,annot=True)
plt.show()
Let’s turn the square into a triangle so that we have no repeat correlations and we get rid of the diagonal which is going to be equal to 1 for everything since the correlation of a variable with itself is 1.
First, let’s find out how to get the dimensions. We use shape().
print(corr.shape)
Numpy has the ability to create arrays where every element is 0 if you give it dimensions. The call to do this is np.zeros().
import numpy as np
np.zeros(corr.shape)