matplotlib:二进制热图
matplotlib: binary heat plot
假设我有一个 10x10 矩阵,它由 0 和 1 组成,表示为列表列表。我如何使用 matplotlib
将这样的矩阵表示为红色和黑色方块的网格? (红色代表 1,黑色代表 0)。
我进行了广泛的搜索,但我能找到的最接近的是 Plot a black-and-white binary map in matplotlib
,但颜色是小于 1 的浮点数。一旦我在数据中得到 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)
假设我有一个 10x10 矩阵,它由 0 和 1 组成,表示为列表列表。我如何使用 matplotlib
将这样的矩阵表示为红色和黑色方块的网格? (红色代表 1,黑色代表 0)。
我进行了广泛的搜索,但我能找到的最接近的是 Plot a black-and-white binary map in matplotlib
,但颜色是小于 1 的浮点数。一旦我在数据中得到 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)