如何制作平滑的热图?

How to make a smooth heatmap?

我有一个名为 'result' 的 pandas 数据框,其中包含经度、纬度和生产值。数据框如下所示。对于每一对纬度和经度,都有一个生产值,因此有很多 NaN 值。

> Latitude   0.00000   32.00057  32.00078  ...  32.92114  32.98220  33.11217
  Longitude                                ...                              
  -104.5213       NaN       NaN       NaN  ...       NaN       NaN       NaN
  -104.4745       NaN       NaN       NaN  ...       NaN       NaN       NaN
  -104.4679       NaN       NaN       NaN  ...       NaN       NaN       NaN
  -104.4678       NaN       NaN       NaN  ...       NaN       NaN       NaN
  -104.4660       NaN       NaN       NaN  ...       NaN       NaN       NaN

这是我的代码:

plt.rcParams['figure.figsize'] = (12.0, 10.0)
plt.rcParams['font.family'] = "serif"
plt.figure(figsize=(14,7))
plt.title('Heatmap based on ANN results')
sns.heatmap(result)

热图如下所示

但我希望它看起来更像这样

如何调整我的代码使其看起来像第二张图片上的代码?

我做了一个简单粗暴的例子来说明如何平滑 numpy 数组中的数据。它也应该直接适用于 pandas 数据帧。

我先给出代码,然后再看一遍:

# Some needed packages
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
from scipy.ndimage import gaussian_filter
np.random.seed(42)


# init an array with a lot of nans to imitate OP data
non_zero_entries = sparse.random(50, 60)
sparse_matrix = np.zeros(non_zero_entries.shape) + non_zero_entries
sparse_matrix[sparse_matrix == 0] = None

# set nans to 0
sparse_matrix[np.isnan(sparse_matrix)] = 0

# smooth the matrix
smoothed_matrix = gaussian_filter(sparse_matrix, sigma=5)

# Set 0s to None as they will be ignored when plotting
# smoothed_matrix[smoothed_matrix == 0] = None
sparse_matrix[sparse_matrix == 0] = None

# Plot the data
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,
                               sharex=False, sharey=True,
                               figsize=(9, 4))
ax1.matshow(sparse_matrix)
ax1.set_title("Original matrix")
ax2.matshow(smoothed_matrix)
ax2.set_title("Smoothed matrix")
plt.tight_layout()
plt.show()

代码相当简单。你无法平滑 NaN,我们必须摆脱它们。我将它们设置为零,但根据您的领域,您可能想要对它们进行插值。 使用 gaussian_filter 我们平滑图像,其中 sigma 控制内核的宽度。

情节代码产生以下图像