You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib中无需set_bad等方法指定矩阵值对应颜色生成图像

Fixing Matplotlib Colormap for Binary Matrix Visualization

Hey there! Let's figure out why your all-1 matrix is showing up black instead of white. The issue lies in how Matplotlib's imshow handles color mapping when all data points are the same value. Here's the breakdown and solution:

Why It's Happening

  • When using a ListedColormap without explicit normalization, imshow auto-sets the color range based on your data's min and max.
    • For an all-0 matrix: min/max = 0, which maps to the first color (black) — this works as expected.
    • For an all-1 matrix: min/max = 1, so imshow maps this single value to the start of your colormap (black) instead of the second color (white).
    • For mixed 0s and 1s: range is 0 to 1, so 0 → black and 1 → white — that's why your diagonal case works.

The Fix: Explicit Normalization with BoundaryNorm

We'll use colors.BoundaryNorm to explicitly define which values map to which colors, eliminating the auto-range issue. Here's the updated code:

import matplotlib
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

N = 2
# Uncomment the data case you want to test below:
# Case 1: All 0s (all black)
# data = np.zeros((N, N))
# Case 2: All 1s (all white)
data = np.ones((N, N))
# Case 3: Diagonal 1s (white squares at top-left & bottom-right)
# data = np.zeros((N, N))
# data[0,0] = 1
# data[1,1] = 1
print(data)

fig, ax = plt.subplots(1, 1, tight_layout=True)

# Define custom colormap
my_cmap = matplotlib.colors.ListedColormap(['black', 'white'])
# Create boundary norm to map values to colors explicitly
# Boundaries split the range: ≤0.5 → black, >0.5 → white
norm = colors.BoundaryNorm([0, 0.5, 1], my_cmap.N)

# Draw grid lines
for x in range(N + 1):
    ax.axhline(x, lw=2, color='k', zorder=5)
    ax.axvline(x, lw=2, color='k', zorder=5)

# Render matrix with custom norm
ax.imshow(data, interpolation='none', cmap=my_cmap, norm=norm, extent=[0, N, 0, N], zorder=0)

# Turn off axis labels
ax.axis('off')

plt.show()

Key Changes Explained

  • BoundaryNorm([0, 0.5, 1], my_cmap.N) creates two color bins:
    • Values ≤ 0.5 are assigned to the first color (black)
    • Values > 0.5 are assigned to the second color (white)
  • This ensures consistent color mapping regardless of whether your data has only 0s, only 1s, or a mix.
  • Your grid drawing code and axis settings stay unchanged — we just add the normalization to fix the color mapping issue.

内容的提问来源于stack exchange,提问作者Mel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:39:22