在pyplot中插值NaN值而不使用scipy.interpolate.griddata

3 投票
1 回答
1453 浏览
提问于 2025-04-18 07:38

我想知道怎么在不对数据本身进行插值的情况下,使用plt.contourf来绘制图。问题是我尝试过scipy.interpolate.griddata,但因为我的数据量太大,耗时很长。

我想知道有没有更快的方法,比如用pyplot,来绘制包含NaNs的数据,而不出现这些空白。

举个例子:

如果我有:

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

a = np.array([[  9.,   3.,   2.,   5.,   9.,   3.,   2.,   5.],
              [  3.,  nan,   5.,   1.,   3.,  nan,   5.,   1.],
              [  5.,   8.,   2.,   9.,   5.,   8.,   2.,   9.],
              [  9.,   3.,   2.,   5.,   9.,   3.,   2.,   5.],
              [  3.,  nan,   5.,   1.,   3.,  nan,   5.,   1.],
              [  5.,   8.,   2.,   9.,   5.,   8.,   2.,   9.],
              [  9.,   3.,   2.,   5.,   9.,   3.,   2.,   5.],
              [  3.,  nan,   5.,   1.,   3.,  nan,   5.,   1.],
              [  5.,   8.,   2.,   9.,   5.,   8.,   2.,   9.],
              [  9.,   3.,   2.,   5.,   9.,   3.,   2.,   5.],
              [  3.,  nan,   5.,   1.,   3.,  nan,   5.,   1.],
              [  5.,   8.,   2.,   9.,   5.,   8.,   2.,   9.]])

xa = np.arange(8)+2

ya = -np.arange(12)

plt.figure()
plt.contourf(xa,ya,a,100)
plt.show()

我想得到:

这里输入图片描述

我希望能更简单、更快地填补这些空白...

1 个回答

2

Pandas有一个很棒的插值接口,你只需要这样做:

import pandas as pd

a_interp = pd.DataFrame(a).interpolate(method='linear', axis=0).values
plt.contourf(xa, ya, a_interp, 100)
plt.show()

enter image description here

撰写回答