【问题标题】:Plotting contours over pcolormesh data在 pcolormesh 数据上绘制等高线
【发布时间】:2015-12-21 23:07:21
【问题描述】:

我有一些使用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 的输出时,所有looks great。添加轮廓会生成giant mess


我已经阅读了contour demo、API examples、pcolormesh 级别examplethis 密切相关的 SO 帖子(我的数据已经网格化,所以解决方案没有帮助)。但到目前为止,我没有尝试在我的 pcolormesh 数据上创建 4 条简单的轮廓线。

【问题讨论】:

  • 您的数据看起来很嘈杂,这可能是轮廓看起来不理想的原因。您可以在使用等高线图之前尝试平滑数据。手动指定级别,例如levels = np.linspace(-4, 6, 4) for plt.contour(... , levels = levels) 也可能有帮助...我建议上传您的数据以提供一个最低限度的示例,以便人们可以提供帮助。
  • @EdSmith,我忘了提到我也尝试过指定自己的轮廓级别,但没有任何运气。我目前无法上传我的数据,因为它是专有的(也是 4GB)。

标签: python matplotlib contour


【解决方案1】:

我已经用高斯滤波器(和 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()

看起来好多了,

【讨论】:

  • 这正是问题所在!我快要疯了,以为我做了一些程序上不正确的事情,但那只是嘈杂的数据。
猜你喜欢
  • 1970-01-01
  • 2023-02-09
  • 2012-07-23
  • 2021-05-19
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多