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

Python中x变量非均匀时如何基于二维矩阵Z绘制colormap?

非均匀坐标轴pcolormesh绘图解决方案

pcolormesh本身原生支持非均匀的坐标轴输入,无需对非均匀的x序列做特殊预处理,以下是两种可行的实现方案:

方案1:最简实现(推荐)

使用shading='nearest'参数,直接将原始x、y序列作为每个数据点的中心坐标传入,不需要调整坐标维度,适配你当前的所有数据结构:

import numpy as np
import matplotlib.pyplot as plt

# 初始化原始数据
x = np.array([1e-5,5e-5,1e-4,5e-4,1e-3,5e-3,1e-2])
y = np.array([300,400,500,600,700,800])
Z = np.random.rand(7,6) # 替换为你实际计算得到的Z矩阵

# 绘图
plt.figure(figsize=(8,4))
# 转置Z是为了匹配x(横轴,长度7)、y(纵轴,长度6)的维度对应关系
pcm = plt.pcolormesh(x, y, Z.T, shading='nearest')
# 你的x取值跨3个数量级,使用对数坐标轴展示效果更合理,不需要可以删除这行
plt.xscale('log')
plt.colorbar(pcm, label='Z值')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

方案2:色块边界对齐坐标

如果需要使用默认的shading='flat'模式,让填充色块的边界严格对齐坐标刻度,只需要先计算x、y序列的边界值即可:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1e-5,5e-5,1e-4,5e-4,1e-3,5e-3,1e-2])
y = np.array([300,400,500,600,700,800])
Z = np.random.rand(7,6)

# 计算x的边界:中间点取相邻x的中点,首尾边界按最近间隔外扩
x_edge = np.zeros(len(x)+1)
x_edge[1:-1] = (x[1:] + x[:-1])/2
x_edge[0] = x[0] - (x[1]-x[0])/2
x_edge[-1] = x[-1] + (x[-1]-x[-2])/2

# 计算y的边界
y_edge = np.zeros(len(y)+1)
y_edge[1:-1] = (y[1:] + y[:-1])/2
y_edge[0] = y[0] - (y[1]-y[0])/2
y_edge[-1] = y[-1] + (y[-1]-y[-2])/2

# 绘图
plt.figure(figsize=(8,4))
pcm = plt.pcolormesh(x_edge, y_edge, Z.T)
plt.xscale('log')
plt.colorbar(pcm, label='Z值')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

两种方案都可以完美适配你的非均匀x序列,不需要额外做插值或者meshgrid预处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:36:00