gpt4 book ai didi

python - cmap 在seaborn 中如何工作以及如何更改分箱?

转载 作者:行者123 更新时间:2023-12-02 02:58:38 24 4
gpt4 key购买 nike

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


所以问题是,如果我使用cmap并强制seaborn仅使用一组离散的colors=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 以上?(我故意使用不等的垃圾箱来表达我的意思。)

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

Original heatmap WITHOUT using cmap. Heatmap with 5 discrete sections created using cmap and choosing 5 colours.

谢谢。

最佳答案

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

enter image description here

关于python - cmap 在seaborn 中如何工作以及如何更改分箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60506990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com