【问题标题】:Apply seaborn heatmap columnwise on pandas dataframe在 pandas 数据框中应用 seaborn 热图列
【发布时间】:2017-05-17 06:31:12
【问题描述】:

我试图在一个旋转的 pandas 数据框上使用 seaborn 的热图形式,就像在超链接中那样工作

df = pd.DataFrame(np.random.randint(1,100,size = (3,2)))
df.columns = ['A','B']
df
sns.heatmap(df, annot=True, fmt="d", linewidths=.5,cmap="RdYlGn")

Output of code block - Entire Dataframe formatted as single heatmap 输出选择 45 作为最小值,86 作为最大值,并对整个数据帧进行颜色编码

但我无法做的是明智地应用热图列 即像条件格式一样按列而不是整个数据框应用列。就像这个超链接中的例子一样 -

Output required/expected

对于 col1,选择最小的 45 和最大的 88 并格式化,对于 col2,分别选择 70 和 86 条件格式的列,但仍显示为表格。 .在示例中,我看到 df 的其余部分被设为零,并且只有 1 列被格式化,或者整个数据框得到了格式化

谁能帮忙解决这个问题

【问题讨论】:

  • 从我有限的知识...看来,您尝试绘制的内容似乎无法单独使用本机 seaborn 热图功能实现。但是我知道你可以使用子图来做到这一点。我不熟悉seaborn ...使用matplotlib怎么样?有一个 example here 在概念上似乎与您想要的相似

标签: python dataframe heatmap seaborn


【解决方案1】:

您还可以将每列缩放到最小值为零和最大值为 1,将其传递给热图,并使用原始值进行注释。

scaled_df = (df - df.min(axis=0))/(df.max(axis=0) - df.min(axis=0))
sns.heatmap(scaled_df, annot=df, fmt="d", linewidths=.5, cmap="RdYlGn")

请注意,您可能希望使用cbar=False 删除颜色条,因为该解决方案必然要求每列具有不同的比例。

或者,可以使用sklearn.preprocessing.minmax_scale 代替手动缩放。

from sklearn.preprocessing import minmax_scale

scaled_df = minmax_scale(df)
sns.heatmap(scaled_df, annot=df, fmt="d", linewidths=.5, cmap="RdYlGn")

【讨论】:

    【解决方案2】:

    感谢@Implus3H 这个例子有帮助 这是代码的修改版本作为函数,它可以按列进行条件格式,以防万一它对其他人有用

    df 是一个输入数据帧,在下面的示例函数中,其列将默认获得红色的颜色编码阴影

    def columnwise_conditionalformat(df, color = 'Reds'):
        nrows = len(df)
        ncols = len(df.columns)
        fig, ax = plt.subplots()
        for i in range(ncols):
            truthar = [True]*ncols
            truthar[i] = False
            mask = truthar = np.array(nrows * [truthar], dtype=bool)
            red = np.ma.masked_where(mask, df)
            ax.pcolormesh(red, cmap=color)
    
        for y in range(df.shape[0]):
            for x in range(df.shape[1]):
                plt.text(x+.5,y+.5,'%.1f'% df.ix[y, x],
                        horizontalalignment='center',
                         verticalalignment='center'
                        )
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-05
      • 2015-09-27
      • 2019-05-16
      • 2016-11-21
      • 2020-04-24
      • 2018-12-16
      • 2018-05-15
      • 2015-09-12
      相关资源
      最近更新 更多