我有一些要使用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。添加轮廓将生成giant mess

我已经阅读了contour demo,API examples,pcolormesh级别examplethis紧密相关的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/轮廓,
plt.figure()
CS = plt.pcolormesh(X, Y, Z)
plt.contour(X, Y, Z, 4, colors='k')
plt.colorbar(CS)
plt.show()

看起来像这样

python - 在pcolormesh数据上绘制轮廓-LMLPHP

如果我们按如下所示添加过滤条件,
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()

看起来好多了,python - 在pcolormesh数据上绘制轮廓-LMLPHP

10-01 23:49
查看更多