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

使用matplotlib imshow展示分类数据时背景颜色异常求助

问题描述

尝试用imshow()展示分类数据时,无法可靠控制颜色:

  • 当dummy=True(虚拟数据),生成的图表背景为红色
  • 当dummy=False(真实数据),生成的图表背景为浅灰色,偶尔也会是红色
    预期背景为白色,但缩小图表尺寸(比如设置fig.set_size_inches(10,4.4))时问题消失。

附代码:

from random import choice
import matplotlib.pyplot as plt # draw pretty stuff
from matplotlib import colors

def draw_trace2(mem_trace):
    print(f"Matrix: {mem_trace.block_size} rows, {mem_trace.len()} cols")
    # this prints: 'Matrix: 80 rows, 178 cols'

    dummy = True
    if dummy:
        # create dummy data
        access_matrix = [
            [choice([10,10,10,10,20,30]) for x in range(mem_trace.len())]
            for y in range(mem_trace.block_size)]
    else:
        # create real data
        access_matrix = [
            [10 for x in range(mem_trace.len())]
            for y in range(mem_trace.block_size)]
        for ac in mem_trace.access_list:
            for i in range(ac.size):
                access_matrix[ac.offset+i][ac.time] = 20 if ac.action=='R' else 30

    # paranoically check correct values
    for row in access_matrix:
        for cell in row:
            if cell not in [10,20,30]:
                raise ValueError("Wrong Value")

    # create discrete colormap. Credit to the previously cited SO answer
    cmap = colors.ListedColormap(['white', 'green', 'red'])
    bounds = [0,15,25,35]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    # draw and export image
    fig, axe1 = plt.subplots()
    axe1.imshow(access_matrix, cmap=cmap, norm=norm)
    fig.set_size_inches(100,44)
    fig.savefig('mem_trace_plot.pdf', bbox_inches='tight')
    return
解决方案

问题根源是大尺寸图表下,imshow()默认的插值方式(如bilinear)会让相邻像素的颜色混合,导致原本应该是白色的背景(对应值10)被周围的绿色/红色像素混合,呈现出灰色或偏红的视觉效果。而小尺寸图表中单元格相对较大,混合效果不明显,所以问题消失。

解决方法很简单,在调用imshow()时显式设置interpolation='nearest',强制每个单元格使用单一颜色渲染,避免颜色混合:

axe1.imshow(access_matrix, cmap=cmap, norm=norm, interpolation='nearest')

另外可以额外优化可读性:添加网格线分隔单元格,隐藏不需要的坐标轴刻度:

# draw and export image
fig, axe1 = plt.subplots()
axe1.imshow(access_matrix, cmap=cmap, norm=norm, interpolation='nearest')
# 可选:添加网格线增强单元格区分度
axe1.grid(which='both', color='black', linewidth=0.5)
# 可选:隐藏坐标轴刻度(如果不需要的话)
axe1.set_xticks([])
axe1.set_yticks([])
fig.set_size_inches(100,44)
fig.savefig('mem_trace_plot.pdf', bbox_inches='tight')

这样无论图表尺寸多大,背景都会稳定显示为白色,分类颜色也不会出现混合失真。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:27:37