python - pandas/seaborn - plot heatmap data distributions on a square grid -


i plot spatial 2d distribution of data on heatmap through pandas , seaborn. let's have simple codes.csv file:

code,value 2,4 5,6 7,1 9,2 10,1 

plotting simple heatmap in seaborn easy, just:

df = pd.read_csv('codes.csv',index_col='code') 

then

sns.heatmap(df)  

returns

enter image description here

what plotting whole 5 x 5 square grid, index of dataframe represents cell number, i.e. starting 0, of codes of 5 x 5 grid following (top bottom):

20,21,22,23,24 15,16,17,18,19 10,11,12,13,14 5,6,7,8,9 0,1,2,3,4 

and resulting heatmap should map code column of dataframe grid representation (so cells 11 25 should colored in white, no values there).

the plot looks bit strange. :-) anyway, key steps first set background color white via sns.set(style="white"), , plot heapmap mask parameter remove unwanted values.

# data # ==============================================================  df     code  value 0     2      4 1     5      6 2     7      1 3     9      2 4    10      1   data_mat = df.set_index('code').reindex(np.arange(25)).values.reshape(5,5)[::-1] data_mat  array([[ nan,  nan,  nan,  nan,  nan],        [ nan,  nan,  nan,  nan,  nan],        [  1.,  nan,  nan,  nan,  nan],        [  6.,  nan,   1.,  nan,   2.],        [ nan,  nan,   4.,  nan,  nan]])  # create mask nan values, these values won't plotted mask = np.isnan(data_mat)  mask  array([[ true,  true,  true,  true,  true],        [ true,  true,  true,  true,  true],        [false,  true,  true,  true,  true],        [false,  true, false,  true, false],        [ true,  true, false,  true,  true]], dtype=bool)   # plot # ============================================================== import seaborn sns  sns.set(style="white") f, ax = plt.subplots() # use diverging color emphasize on negative , positive corr cmap = sns.cubehelix_palette(12, start=2.5, as_cmap=true) sns.heatmap(data_mat, mask=mask, cmap=cmap, ax=ax) 

enter image description here


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -