Skip to content

Instantly share code, notes, and snippets.

@do-me
Created May 25, 2019 11:33
Show Gist options
  • Save do-me/7aac3486b568e3c784d1ffe9a1075aa3 to your computer and use it in GitHub Desktop.
Save do-me/7aac3486b568e3c784d1ffe9a1075aa3 to your computer and use it in GitHub Desktop.
# heatmap with seaborn
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
import os
pd.set_option('precision', 10)
os.chdir("C:/Users/Dome/Desktop/nu/Wahl- und Strukturdaten/Tabellen/")
ma = pd.read_csv("MASTERENG.csv",float_precision='round_trip')
# subsetting of master table required for desired factors
collist=[ "INSERT ALL COLUMNS FOR CORRELATION" # ma.columns.values
# AND add following columns for correlation
,'Area','selfindex17', 'deltaindex', 'linke17', 'gruenen17','spd17',
'fdp17','cducsu17', 'afd17']
df = ma[collist].copy() # new df with columns above
# loc for subsetted East or West datasets
west = df.loc[df['Area'] == "West"]
east = df.loc[df['Area'] == "East"]
# Alternative: Berlin only with AreaB == Berlin, or for each county
# Compute the correlation matrix
corr = East.corr()
# or West.corr()
# or df.corr()
# mask for the triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, center=0, square=True, linewidths=.5,
cbar_kws={"shrink": .5})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment