在 pcolormesh 数据上绘制等高线

Plotting contours over pcolormesh data

我有一些使用 pcolormesh 显示的 2D 数据,我想在其上显示一些等高线。我使用

创建网格化数据
import numpy as np
import matplotlib.pyplot as plt

def bin(x, y, nbins, weights=None):
    hist, X, Y = np.histogram2d(x, y, bins=nbins, weights=weights)
    x_grid, y_grid = np.meshgrid(X,Y)
    return hist, x_grid, y_grid

data = ... # read from binary file
h,x_grid,y_grid = bin(data.x,data.y,512)
# do some calculations with h
h = masked_log(h) # "safe" log that replaces <0 elements by 0 in output

pcm = plt.pcolormesh(x_grid,y_grid,h,cmap='jet')

# Just pretend that the data are lying on the center of the grid
# points, rather than on the edges
cont = plt.contour(x_grid[0:-1,0:-1],y_grid[0:-1,0:-1],h,4,colors='k',origin='lower')

当我只绘制 pcolormesh 的输出时,所有 looks great. Adding the contours makes a giant mess.


我已经通读了 contour demo, the API examples, the pcolormesh levels example, and this 密切相关的 SO post(我的数据已经网格化,所以解决方案没有帮助)。但到目前为止,我没有尝试在我的 pcolormesh 数据上创建 4 条简单的等高线。

我已经将最小示例与高斯滤波器(和 scipy)放在一起,我认为它看起来可以满足您的需求。首先,设置一些虚拟数据(高斯)并添加噪声,

import matplotlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z += 0.1*np.random.random(Z.shape)

并尝试 pcolormesh/contour,

plt.figure()
CS = plt.pcolormesh(X, Y, Z)
plt.contour(X, Y, Z, 4, colors='k')
plt.colorbar(CS)
plt.show()

看起来像这样,

如果我们按如下方式添加过滤,

import matplotlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z += 0.1*np.random.random(Z.shape)

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

CS = plt.contour(X, Y, gaussian_filter(Z, 5.), 4, colors='k',interpolation='none')
plt.colorbar()
plt.show()

看起来好多了,