Last active
October 20, 2019 16:07
-
-
Save FBosler/0e185311dd6fd7122e0fbab383c9e239 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def draw_heatmap(data,inner_row, inner_col, outer_row, outer_col, values, vmin,vmax): | |
sns.set(font_scale=1) | |
fg = sns.FacetGrid( | |
data, | |
row=outer_row, | |
col=outer_col, | |
margin_titles=True | |
) | |
position = left, bottom, width, height = 1.4, .2, .1, .6 | |
cbar_ax = fg.fig.add_axes(position) | |
fg.map_dataframe( | |
draw_heatmap_facet, | |
x_col=inner_col, | |
y_col=inner_row, | |
values=values, | |
cbar_ax=cbar_ax, | |
vmin=vmin, | |
vmax=vmax | |
) | |
fg.fig.subplots_adjust(right=1.3) | |
plt.show() | |
def draw_heatmap_facet(*args, **kwargs): | |
data = kwargs.pop('data') | |
x_col = kwargs.pop('x_col') | |
y_col = kwargs.pop('y_col') | |
values = kwargs.pop('values') | |
d = data.pivot(index=y_col, columns=x_col, values=values) | |
annot = round(d,4).values | |
cmap = sns.color_palette("Blues",30) + sns.color_palette("Blues",30)[0::2] | |
#cmap = sns.color_palette("Blues",30) | |
sns.heatmap( | |
d, | |
**kwargs, | |
annot=annot, | |
center=0, | |
cmap=cmap, | |
linewidth=.5 | |
) | |
# Data preparation | |
_ = data.copy() | |
_['Year'] = pd.cut(_['Year'],bins=[2006,2008,2012,2018]) | |
_['GDP per Capita'] = _.groupby(['Continent','Year'])['Log GDP per capita'].transform( | |
pd.qcut, | |
q=3, | |
labels=(['Low','Medium','High']) | |
).fillna('Low') | |
_['Corruption'] = _.groupby(['Continent','GDP per Capita'])['Perceptions of corruption'].transform( | |
pd.qcut, | |
q=3, | |
labels=(['Low','Medium','High']) | |
) | |
_ = _[_['Continent'] != 'Oceania'].groupby(['Year','Continent','GDP per Capita','Corruption'])['Life Ladder'].mean().reset_index() | |
_['Life Ladder'] = _['Life Ladder'].fillna(-10) | |
draw_heatmap( | |
data=_, | |
outer_row='Corruption', | |
outer_col='GDP per Capita', | |
inner_row='Year', | |
inner_col='Continent', | |
values='Life Ladder', | |
vmin=3, | |
vmax=8, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment