pcolormesh 缺少值?

发布于 2024-12-09 18:20:55 字数 584 浏览 0 评论 0原文

我有 3 个 1-D ndarrays:x、y、z

和以下代码:

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as spinterp

## define data
npoints = 50
xreg = np.linspace(x.min(),x.max(),npoints)
yreg = np.linspace(y.min(),y.max(),npoints)
X,Y = np.meshgrid(xreg,yreg)
Z = spinterp.griddata(np.vstack((x,y)).T,z,(X,Y),
                      method='linear').reshape(X.shape)

## plot
plt.close()
ax = plt.axes()
col = ax.pcolormesh(X,Y,Z.T)
plt.draw()

我的图显示为空白,我怀疑这是因为 method='线性' 插值与 nan 一起出现。我尝试转换为屏蔽数组,但无济于事 - 绘图仍然是空白。你能告诉我我做错了什么吗?谢谢。

I have 3 1-D ndarrays: x, y, z

and the following code:

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as spinterp

## define data
npoints = 50
xreg = np.linspace(x.min(),x.max(),npoints)
yreg = np.linspace(y.min(),y.max(),npoints)
X,Y = np.meshgrid(xreg,yreg)
Z = spinterp.griddata(np.vstack((x,y)).T,z,(X,Y),
                      method='linear').reshape(X.shape)

## plot
plt.close()
ax = plt.axes()
col = ax.pcolormesh(X,Y,Z.T)
plt.draw()

My plot comes out blank, and I suspect it is because the method='linear' interpolation comes out with nans. I've tried converting to a masked array, but to no avail - plot is still blank. Can you tell me what I am doing wrong? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一笑百媚生 2024-12-16 18:20:55

知道了。这似乎是迂回的,但这就是解决方案:

import numpy.ma as ma

Zm = ma.masked_where(np.isnan(Z),Z)
plt.pcolormesh(X,Y,Zm.T)

如果 Z 矩阵包含 nan,它必须是 pcolormesh 的掩码数组,必须创建该数组与ma.masked_where,或者,

Zm = ma.array(Z,mask=np.isnan(Z))

Got it. This seems round-about, but this was the solution:

import numpy.ma as ma

Zm = ma.masked_where(np.isnan(Z),Z)
plt.pcolormesh(X,Y,Zm.T)

If the Z matrix contains nan's, it has to be a masked array for pcolormesh, which has to be created with ma.masked_where, or, alternatively,

Zm = ma.array(Z,mask=np.isnan(Z))
很快妥协 2024-12-16 18:20:55

对所选答案的轻微改进

import numpy.ma as ma
Zm = ma.masked_invalid(Z)
plt.pcolormesh(X, Y, Zm.T)

masked_invalid 屏蔽所有 NaN 值,从而无需指定

mask = np.isnan(Z)

A slight improvement on the chosen answer

import numpy.ma as ma
Zm = ma.masked_invalid(Z)
plt.pcolormesh(X, Y, Zm.T)

masked_invalid masks all NaN values, thereby saving the need to specify

mask = np.isnan(Z)
永言不败 2024-12-16 18:20:55

请注意,在 matplotlib master 中不再需要显式屏蔽,因为数组现在在内部自动屏蔽。将合并到 matplotlib >2.1 中。查看我合并的拉取请求 https://github.com/matplotlib/matplotlib/pull/5451

所以现在就这么简单

plt.pcolormesh(X,Y,Z.T)

Note that the explicit masking is no longer necessary in matplotlib master as arrays are now masked automatically internally. Will be incorporated into matplotlib >2.1. See my merged pull request https://github.com/matplotlib/matplotlib/pull/5451

So now it's as simple as

plt.pcolormesh(X,Y,Z.T)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文