gpt4 book ai didi

python - matplotlib:二进制热图

转载 作者:太空宇宙 更新时间:2023-11-03 12:59:15 26 4
gpt4 key购买 nike

假设我有一个 10x10 矩阵,它由 0 和 1 组成,表示为列表的列表。我如何使用 matplotlib 将这样的矩阵表示为红色和黑色方 block 的网格? (红色代表 1,黑色代表 0)。

我进行了广泛的搜索,但我能找到的最接近的是 Plot a black-and-white binary map in matplotlib ,但颜色是小于 1 的 float 。一旦我在数据中得到 1,情节就会出错。谁能帮忙?或者指出可以帮助我克服这个问题的特定 matplotlib 文档?

最佳答案

您需要所谓的 ListedColorMap:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# random data
x = np.random.random_integers(0, 1, (10, 10))

fig, ax = plt.subplots()

# define the colors
cmap = mpl.colors.ListedColormap(['r', 'k'])

# create a normalize object the describes the limits of
# each color
bounds = [0., 0.5, 1.]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# plot it
ax.imshow(x, interpolation='none', cmap=cmap, norm=norm)

enter image description here

关于python - matplotlib:二进制热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517400/

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