i using data present here construct heat map using seaborn , pandas.
the input csv file here: https://www.dropbox.com/s/5jc1vr6u8j7058v/luh2_trans_matrix.csv?dl=0
code:
import pandas import seaborn.apionly sns # read in csv file df_trans = pandas.read_csv('luh2_trans_matrix.csv') sns.set(font_scale=0.8) cmap = sns.cubehelix_palette(start=2.8, rot=.1, light=0.9, as_cmap=true) cmap.set_under('gray') # 0 values in activity matrix shown in gray (inactive transitions) df_trans = df_trans.set_index(['unnamed: 0']) ax = sns.heatmap(df_trans, cmap=cmap, linewidths=.5, linecolor='lightgray') # x - y axis labels ax.set_ylabel('from') ax.set_xlabel('to') # rotate tick labels locs, labels = plt.xticks() plt.setp(labels, rotation=0) locs, labels = plt.yticks() plt.setp(labels, rotation=0) # revert matplotlib params sns.reset_orig()
as can see csv file, contains 3 discrete values: 0, -1 , 1. want discrete legend instead of colorbar. labeling 0 a, -1 b , 1 c. how can that?
well, there's more 1 way accomplish this. in case, 3 colors needed, pick colors myself creating linearsegmentedcolormap
instead of generating them cubehelix_palette
. if there enough colors warrant using cubehelix_palette
, define segments on colormap using boundaries
option of cbar_kws
parameter. either way, ticks can manually specified using set_ticks
, set_ticklabels
.
the following code sample demonstrates manual creation of linearsegmentedcolormap
, , includes comments on how specify boundaries if using cubehelix_palette
instead.
import matplotlib.pyplot plt import pandas import seaborn.apionly sns matplotlib.colors import linearsegmentedcolormap sns.set(font_scale=0.8) dataframe = pandas.read_csv('luh2_trans_matrix.csv').set_index(['unnamed: 0']) # 3 colors, it's easier choose them yourself. # if still want generate colormap cubehelix_palette instead, # add cbar_kws={"boundaries": linspace(-1, 1, 4)} heatmap invocation # have generate discrete colorbar instead of continous one. mycolors = ((0.8, 0.0, 0.0, 1.0), (0.0, 0.8, 0.0, 1.0), (0.0, 0.0, 0.8, 1.0)) cmap = linearsegmentedcolormap.from_list('custom', mycolors, len(mycolors)) ax = sns.heatmap(dataframe, cmap=cmap, linewidths=.5, linecolor='lightgray') # manually specify colorbar labelling after it's been generated colorbar = ax.collections[0].colorbar colorbar.set_ticks([-0.667, 0, 0.667]) colorbar.set_ticklabels(['b', 'a', 'c']) # x - y axis labels ax.set_ylabel('from') ax.set_xlabel('to') # y-axis labels need rotation set, x-axis labels have rotation of 0 _, labels = plt.yticks() plt.setp(labels, rotation=0) plt.show()
Comments
Post a Comment