【问题标题】:matplotlib shift pcolormesh plot to symmetrized coordinatesmatplotlib 将 pcolormesh 绘图转移到对称坐标
【发布时间】:2020-09-21 05:10:26
【问题描述】:

我有一些二维数据,x 和 y 坐标都在 [0,1] 内,使用 pcolormesh 绘制。 现在我想将 x 和 y 坐标的图对称化为 [-0.5, 0.5]。在 Matlab 中,我可以通过改变 x 和 y 来实现这一点,例如[0, 0.2, 0.4, 0.6, 0.8] 到 [0, 0.2, 0.4, -0.4, -0.2],无需重新排列数据。但是,使用 pcolormesh 我无法得到想要的结果。

下面是一个最小的例子,数据简单地用x+y表示:

import matplotlib.pyplot as plt
import numpy as np

x,y = np.mgrid[0:1:5j,0:1:5j] 

fig,(ax1,ax2,ax3) = plt.subplots(1,3,figsize=(9,3.3),constrained_layout=1)
# original plot spanning [0,1]
img1 = ax1.pcolormesh(x,y,x+y,shading='auto')

# shift x and y from [0,1] to [-0.5,0.5]
x = x*(x<0.5)+(x-1)*(x>0.5)
y = y*(y<0.5)+(y-1)*(y>0.5)
img2 = ax2.pcolormesh(x,y,x+y,shading='auto') # similar code works in Matlab

# for this specific case, the following is close to the desired result, I can just rename x and y tick labels
# to [-0.5,0.5], but in general data is not simply x+y
img3 = ax3.pcolormesh(x+y,shading='auto') 
fig.colorbar(img1,ax=[ax1,ax2,ax3],orientation='horizontal')

对应图如下,如有遗漏,不胜感激!

【问题讨论】:

  • 你必须重新排列数据,即使在 Matlab 中也是如此。
  • @JodyKlymak 我只是仔细检查了在 Matlab 中我正在做相同问题的 3D 版本并使用了等值面,它有效。在 Matlab 中使用 pcolor 确实是不够的。我天真地想通过移动 X 和 Y 坐标来有效地重新排列“Z”数据,但也许这只适用于散点图......

标签: python-3.x numpy matplotlib


【解决方案1】:

让我们看看你想在一维示例中实现什么。 您有介于 0 和 1 之间的 x 值和一个虚拟函数 f(x) = 20*x 来生成一些值。

# x  = [0, .2, .4, .6, .8] -> [0, .2, .4, -.4, -.2] -> [-.4, .2, .0, .2, .4])
# fx = [0,  4,  8, 12, 16] -> [0,  4,  8,  12,  16] -> [ 12, 16,  0,  4,  8]
#                                          ^ only flip and shift x not fx ^

您可以使用np.roll() 来实现最后的操作。 我使用n=14 使结果更清晰可见,并表明这种方法适用于任意n

import numpy as np
import matplotlib.pyplot as plt

n = 14
x, y = np.meshgrid(np.linspace(0, 1, n, endpoint=False),
                   np.linspace(0, 1, n, endpoint=False))

z = x + y

x_sym = x*(x <= .5)+(x-1)*(x > .5)
# array([[ 0. ,  0.2,  0.4, -0.4, -0.2], ...
x_sym = np.roll(x_sym, n//2, axis=(0, 1))
# array([[-0.4, -0.2,  0. ,  0.2,  0.4], ...

y_sym = y*(y <= .5)+(y-1)*(y > .5)
y_sym = np.roll(y_sym, n//2, axis=(0, 1))

z_sym = np.roll(z, n//2, axis=(0, 1))
# array([[1.2, 1.4, 0.6, 0.8, 1. ],
#        [1.4, 1.6, 0.8, 1. , 1.2],
#        [0.6, 0.8, 0. , 0.2, 0.4],
#        [0.8, 1. , 0.2, 0.4, 0.6],
#        [1. , 1.2, 0.4, 0.6, 0.8]])

fig, (ax1, ax2) = plt.subplots(1, 2)
img1 = ax1.imshow(z, origin='lower', extent=(.0, 1., .0, 1.))
img2 = ax2.imshow(z_sym,  origin='lower', extent=(-.5, .5, -.5, .5))

【讨论】:

  • 通过对称我的意思是每个“x”在坐标中有一个“-x”:[.0, .2, .4, .6, .8] -> [0, . 2、.4、-.4、-.2]。但是,“数据”并不明确取决于坐标,因此 [0, 4, 8, 12, 16] -> [0, 4, 8, 12, 16] 在您的示例中。我想要的最后一步实际上只是 [0, .2, .4, -.4, -.2]->[-.4, -.2, 0, .2, .4] 和 [0, 4, 8, 12, 16]->[12, 16, 0, 4, 8].
  • 感谢有关使用 np.roll() 的提示!现在效果很好。
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多