Seaborn HeatMap - How to set colour grading throughout multiple different datasets

我怕爱的太早我们不能终老 提交于 2019-12-11 01:31:12

问题


So I need to create a number of heatmaps in seaborn with varying datascales. Some range from 0-100 and some +100 to -100. What I need to do is to keep the colour grading the same throughout all graphs. So for example I want anything below 0 to be steadily getting from dark blue to light blue and anything above 0 to be getting darker red such as the terrible example graph below.

What I need that is not shown below very well is a fluid colour transition as currently I am not fully sure how seaborn is working it out as I have just listed a number of colours - Code below

sns.heatmap(df.T, cmap=ListedColormap(['#000066','#000099','#0000cc','#1a1aff','#6666ff','#b3b3ff','#ffff00','#ffcccc','#ff9999','#ff6666','#ff3333','#ff0000']), annot=False)

Thanks for any advise.


回答1:


To specify the color normalization, you can use a Normalize instance, plt.Normalize(vmin, vmax) and supply it to the heatmap using the norm keyword (which is routed to the underlying pcolormesh).

To obtain a colormap with gradually changing colors, you may use the static LinearSegmentedColormap.from_list method and supply it with a list of colors.

import numpy as np; np.random.seed(0)
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

x1 = np.random.randint(0,100,size=(12,8))
x2 = np.random.randint(-100,100,size=(12,8))

fig, axes = plt.subplots(ncols=2)

cmap = mcolors.LinearSegmentedColormap.from_list("n",['#000066','#000099','#0000cc','#1a1aff','#6666ff','#b3b3ff',
                       '#ffff00','#ffcccc','#ff9999','#ff6666','#ff3333','#ff0000'])
norm = plt.Normalize(-100,100)

sns.heatmap(x1, ax=axes[0], cmap=cmap, norm=norm)
sns.heatmap(x2, ax=axes[1], cmap=cmap, norm=norm)

plt.show()



来源:https://stackoverflow.com/questions/44736213/seaborn-heatmap-how-to-set-colour-grading-throughout-multiple-different-datase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!