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

定义坐标轴时DataArray绘图丢失数据点,如何避免信息损失?

解决xarray DataArray自定义坐标轴绘图丢失最后一个数据点的问题

问题重现

使用xarray的DataArray(含掩码值)调用matplotlib的pcolor绘图时,手动传入自定义坐标轴后,两个维度的最后一个数据点会丢失。示例代码如下:

import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

DATA = xr.DataArray(np.random.rand(74,13),dims=('section','lag'))
DATA = DATA.where(DATA>.98,drop=True)

fig,(ax0,ax1) = plt.subplots(1,2,figsize=(10,2))

ax0.pcolor(DATA)
ax0.set(title='Axes not defined')

ax1.pcolor(DATA.lag, DATA.section, DATA)
ax1.set(title='Axes defined')

plt.show()

左图未自定义坐标轴,数据完整显示;右图自定义坐标轴后丢失最后一个维度的数据点

原因分析

matplotlib的pcolor(以及pcolormesh)默认绘制的是网格单元格,而非单个数据点:

  • 若数据维度为(n, m),则需要(n+1, m+1)的坐标数组来定义每个单元格的边缘位置。
  • 直接传入DATA.lag和DATA.section时,这些是数据点的中心坐标,长度与数据维度一致,因此pcolor会丢弃最后一行/列的单元格,导致数据丢失。
  • 直接调用ax0.pcolor(DATA)时,xarray自动为matplotlib生成了适配的边缘坐标,因此数据完整显示。

解决方案

方案1:使用xarray内置的plot方法(推荐)

xarray的plot.pcolor方法会自动处理坐标边缘,无需手动传入坐标轴,同时支持自定义轴标签、标题等配置:

import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

DATA = xr.DataArray(np.random.rand(74,13),dims=('section','lag'))
DATA = DATA.where(DATA>.98,drop=True)

fig,(ax0,ax1) = plt.subplots(1,2,figsize=(10,2))

ax0.pcolor(DATA)
ax0.set(title='Axes not defined')

# 用xarray内置plot方法自动处理坐标
DATA.plot.pcolor(ax=ax1, x='lag', y='section')
ax1.set(title='Axes defined (xarray plot)')

plt.show()

方案2:手动生成坐标轴边缘坐标

若坚持使用matplotlib原生pcolor,可手动计算坐标的边缘值,让坐标数组长度比数据维度多1:

import xarray as xr
import numpy as np
import matplotlib.pyplot as plt

DATA = xr.DataArray(np.random.rand(74,13),dims=('section','lag'))
DATA = DATA.where(DATA>.98,drop=True)

# 生成边缘坐标的辅助函数
def get_edge_coords(da_coord):
    diffs = np.diff(da_coord)
    # 首尾扩展量取相邻坐标差的一半
    start = da_coord[0] - diffs[0]/2
    end = da_coord[-1] + diffs[-1]/2
    # 生成包含边缘的坐标数组
    return np.linspace(start, end, len(da_coord)+1)

# 获取边缘坐标
lag_edges = get_edge_coords(DATA.lag)
section_edges = get_edge_coords(DATA.section)

fig,(ax0,ax1) = plt.subplots(1,2,figsize=(10,2))

ax0.pcolor(DATA)
ax0.set(title='Axes not defined')

# 使用边缘坐标绘图
ax1.pcolor(lag_edges, section_edges, DATA)
ax1.set(title='Axes defined (edge coords)')

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:37:07