【问题标题】:Python heatmap: distorting colour mappingPython热图:扭曲颜色映射
【发布时间】:2017-12-02 15:44:15
【问题描述】:

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

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] 映射到线性的、完整的颜色值?不幸的是,到目前为止我看到的所有颜色图都是预设的。

【问题讨论】:

标签: python matplotlib plotly seaborn


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2016-07-20
    • 2013-07-14
    相关资源
    最近更新 更多