简体   繁体   English

在pcolormesh数据上绘制轮廓图

[英]Plotting contours over pcolormesh data

I have some 2D data that I am displaying using pcolormesh that I would like to display a few contours on top of. 我有一些2D数据,我用pcolormesh显示,我想在上面显示一些轮廓。 I create the gridded data using 我使用创建网格化数据

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

When I plot only the output of pcolormesh , everything looks great . 当我只绘制pcolormesh的输出时,一切看起来都很棒 Adding the contours makes a giant mess . 添加轮廓会造成巨大的混乱


I have read through the contour demo , the API examples , the pcolormesh levels example , and this closely-related SO post (my data is already gridded, so the solution doesn't help). 我已经阅读了轮廓演示 ,API 示例 ,pcolormesh级别示例以及这个密切相关的SO帖子(我的数据已经网格化,因此解决方案没有帮助)。 But nothing I have tried thus far has created 4 simple contour lines atop my pcolormesh data. 但到目前为止我没有尝试过,在我的pcolormesh数据上创建了4条简单的轮廓线。

I've put together minimal example with Gaussian filter (and scipy) which I think looks like it may do what you want. 我把高斯滤波器(和scipy)的最小例子放在一起,我认为看起来它可能会做你想要的。 First, set up some dummy data (a Gaussian) and add noise, 首先,设置一些虚拟数据(高斯)并添加噪声,

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)

and try to pcolormesh/contour, 并尝试pcolormesh / contour,

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

which looks like this, 看起来像这样,

在此输入图像描述

If we add filtering as follows, 如果我们按如下方式添加过滤,

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

it looks much better, 看起来好多了, 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM