Python热图:扭曲颜色映射

时间:2017-06-29 05:00:00

标签: python matplotlib plotly seaborn

我有一组值(想象一下这些是小部件销售):

year | Sarah | Elizabeth | Jones | Robert |
-------------------------------------------
2003 | 11    | 0         |  0    | 0      |
2004 | 16    | 0         |  0    | 6      |
2005 | 12    | 0         |  4    | 11     |
2006 | 33    | 0         |  0    | 3      |
2007 | 18    | 0         |  0    | 0      |
2008 | 18    | 0         |  0    | 0      |
2009 | 110   | 0         |  0    | 0      |
2010 | 83    | 0         |  0    | 0      |
2011 | 1553  | 20        |  25   | 0      |
2012 | 785   | 27        |  0    | 186    |
2013 | 561   | 73        |  0    | 3      |

我用seaborn和matplotlib做了一个热图,但不幸的是,大数字占主导地位,所以它看起来像一个非常苍白的正方形中的一个非常黑暗的正方形。

有没有办法用分段函数进行颜色映射,例如将整个范围包括:[0,200],然后(550,1600)映射到线性,不间断的颜色值?不幸的是,到目前为止我看到的所有颜色都是预设的。

1 个答案:

答案 0 :(得分:2)

您似乎正在为discrete bounds寻找Colormap Normalization方法。以下是使用您的数据的示例:

import StringIO

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import pandas as pd
import seaborn as sns

s = """year Sarah Elizabeth Jones Robert
2003 11 0 0 0
2004 16 0 0 6
2005 12 0 4 11
2006 33 0 0 3
2007 18 0 0 0
2008 18 0 0 0
2009 110 0 0 0
2010 83 0 0 0
2011 1553 20 25 0
2012 785 27 0 186
2013 561 73 0 3"""
df = pd.read_table(StringIO.StringIO(s), sep=' ', header=0, index_col=0)

fig = plt.figure(figsize=(16, 6))
sns.set(font_scale=2) 

ax1 = plt.subplot(121)
sns.heatmap(df, ax=ax1)
ylabels = ax1.get_yticklabels()
plt.setp(ylabels, rotation=0)

ax2=plt.subplot(122)
bounds = np.concatenate((np.linspace(0, 200, 1050), np.linspace(550, 1600, 1050)))
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
sns.heatmap(df, ax=ax2, norm=norm)
ylabels = ax2.get_yticklabels()
plt.setp(ylabels, rotation=0)
cbar = ax2.collections[0].colorbar
cbar_ticks = np.concatenate((np.arange(0, 201, 50), np.arange(700, 1601, 200)))
cbar.set_ticks(cbar_ticks)
cbar.set_ticklabels(cbar_ticks)

fig.tight_layout()
plt.show()

enter image description here