【问题标题】:Use center diverging colormap in a pandas dataframe heatmap display在熊猫数据框热图显示中使用中心发散颜色图
【发布时间】:2020-04-22 13:15:26
【问题描述】:

我想使用发散色图为 pandas 数据框的背景着色。使这比人们想象的更棘手的方面是居中。在下面的示例中,使用了红色到蓝色的颜色图,但颜色图的中间不用于零附近的值。如何创建一个居中的背景颜色显示,其中零是白色,所有负片都是红色调,所有正片都是蓝色调?

import pandas as pd
import numpy as np
import seaborn as sns

np.random.seed(24)
df = pd.DataFrame()
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4)*10, columns=list('ABCD'))],
               axis=1)
df.iloc[0, 2] = 0.0
cm = sns.diverging_palette(5, 250, as_cmap=True)
df.style.background_gradient(cmap=cm).set_precision(2)

上面显示中的零具有红色调,最接近白色背景的用于负数。

【问题讨论】:

  • 我认为 background_gradient 函数是逐行应用颜色图,你需要将它应用到整个数据框。这个答案可能会对您有所帮助:stackoverflow.com/a/42563850/4314229

标签: pandas dataframe heatmap colormap


【解决方案1】:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import colors

np.random.seed(24)
df = pd.DataFrame()
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4)*10, columns=list('ABCD'))],
               axis=1)
df.iloc[0, 2] = 0.0
cm = sns.diverging_palette(5, 250, as_cmap=True)

def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

even_range = np.max([np.abs(df.values.min()), np.abs(df.values.max())])
df.style.apply(background_gradient,
               cmap=cm,
               m=-even_range,
               M=even_range).set_precision(2)

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2019-01-18
    • 2019-01-23
    • 2017-05-07
    • 1970-01-01
    • 2023-04-04
    • 2019-01-03
    • 2015-03-29
    • 1970-01-01
    相关资源
    最近更新 更多