我有一些2D数据,我使用pcolormesh显示,我想在上面显示一些轮廓.我使用创建网格化数据
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
,一切看起来都很棒.添加轮廓会造成巨大的混乱.
我已经阅读了轮廓演示,API 示例,pcolormesh级别示例以及这个密切相关的SO帖子(我的数据已经网格化,因此解决方案没有帮助).但到目前为止我没有尝试过,在我的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()
它看起来好多了,