在pcolormesh数据上绘制轮廓图

时间:2015-12-21 05:16:32

标签: python matplotlib contour

我有一些我使用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帖子(我的数据已经网格化,所以解决方案没有帮助)。但到目前为止我没有尝试过,在我的pcolormesh数据上创建了4条简单的轮廓线。

1 个答案:

答案 0 :(得分:5)

我把高斯滤镜(和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()

看起来像这样,

enter image description here

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

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()

看起来好多了,enter image description here