【问题标题】:How does cmap work in seaborn and how to change binning?cmap 如何在 seaborn 中工作以及如何更改分箱?
【发布时间】:2020-06-15 19:40:57
【问题描述】:

这个问题的灵感来自pheatmap in R 中的中断。问题是我是否可以在 seaborn 的热图中定义我的着色和分箱有多“粗糙”、连续/离散程度。我找到了一种使用 cmap 和使用的颜色数量(例如Discrete legend in seaborn heatmap plot)的方法。但是,我不知道这些颜色组的分配是如何完成的。


所以问题是,如果我使用 cmap 并强制 seaborn 仅使用一组离散的 colours=bins,数据如何分箱?如何手动设置?例如。在 R 的情况下,我可以将间隔设置为 0 到 800,步长为 100,并将其传递给“breaks”参数。

breaksList = seq(0, 800, by = 100)

如果我的比例是线性的,那么使用 cmap 和颜色数量非​​常简单,但如果我想让我的 bins=colorbar 对数或只是不等间距,我该怎么做?


举个具体的例子,我举个航班数据集的例子。左边是原始的默认图,右边,我选择 5 种颜色有 5 个 bin。那么这些箱子的边缘是如何定义的呢?我可以重置它们以便我拥有例如。箱子 0-200、200-300、300-400、400-600、600 以上? (我故意使用不相等的 bin 来表达我的意思。)

# choose 5 colours to create 5 bins
cmap = sns.color_palette('rocket', n_colors=5)

# run this without the cmap argument to get the first image
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights, cmap = cmap)

谢谢。

【问题讨论】:

    标签: python r seaborn heatmap


    【解决方案1】:

    似乎 seaborn 中存在一个错误,导致以下想法无法正常工作,因此退回到纯 matplotlib:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors
    import seaborn as sns
    # choose 5 colours to create 5 bins
    colors = sns.color_palette('rocket', 5)
    levels = [0, 200, 300, 400, 600]
    cmap, norm = matplotlib.colors.from_levels_and_colors(levels, colors, extend="max")
    
    flights = sns.load_dataset("flights")
    flights = flights.pivot("month", "year", "passengers")
    
    fig, ax = plt.subplots()
    im = ax.imshow(flights.values, cmap = cmap, norm=norm)
    ax.set(xticks=range(flights.shape[1]), yticks=range(flights.shape[0]),
           xticklabels=flights.columns, yticklabels=flights.index)
    ax.tick_params(axis="x", rotation=90)
    fig.colorbar(im, ax=ax, spacing="propotional")
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2016-01-25
      • 2018-10-15
      • 2021-01-11
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2021-01-30
      • 2020-11-17
      相关资源
      最近更新 更多