gpt4 book ai didi

python - Matplotlib 干扰图奇怪图案

转载 作者:行者123 更新时间:2023-12-04 09:30:51 25 4
gpt4 key购买 nike

我正在尝试制作 interference figure像这样的动画:
enter image description here
不同的是,上图显示了随时间变化的干涉图,因此相长干涉点和相消干涉点保持固定。相反,我正在尝试制作一个动画,在其中更改两个源的频率,将它们固定在空间中。
这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

source = 0.5
sources = [-source, source]
axlim = max(sources)*2 + 1
N = 1000

x = np.linspace(-axlim, axlim, N)
y = np.linspace(-axlim, axlim, N)
X, Y = np.meshgrid(x, y)

fig = plt.figure()

def update(f):
plt.gca().cla()
C1 = np.sin(2*np.pi*f*((X - sources[0])**2 + Y**2))
C2 = np.sin(2*np.pi*f*((X - sources[1])**2 + Y**2))
Z = C1 + C2

plt.contour(X, Y, Z)

plt.plot(sources, [0, 0], 'ro')
plt.gca().set_aspect('equal')
plt.axis('off')

ani = FuncAnimation(fig = fig, func = update, frames = 11, interval = 100)

plt.show()
enter image description here
问题是奇怪的图案出现在最后一帧中:
enter image description here
这些模式不是物理的(它们不符合物理定律),所以我的代码中一定有错误。我不知道在哪里,但我认为问题出在 matplotlib contour功能:我怀疑它引入了一种别名......

最佳答案

问题在于您对 C1 的定义和 C2 :您将正弦函数应用于 x 和 y 距离的平方和,而不应用平方根。你应该使用:

C1 = np.sin(2*np.pi*f*np.sqrt((X - sources[0])**2 + Y**2))
C2 = np.sin(2*np.pi*f*np.sqrt((X - sources[1])**2 + Y**2))
contour 没有问题plot 方法,但是,我建议您将其替换为 contourf或者,甚至更好, imshow .原因是 contour在您的字段具有相同值的地方绘制线条,保持绘图的其余部分为空。相反, contourfimshow使用您选择的颜色图填充空白区域,以便您可以更好地显示您的字段并避免模糊的空白区域。
请参阅此代码以供引用:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.animation import FuncAnimation

source = 0.5
sources = [-source, source]
axlim = max(sources)*2 + 1
N = 1000

x = np.linspace(-axlim, axlim, N)
y = np.linspace(-axlim, axlim, N)
X, Y = np.meshgrid(x, y)

norm = plt.Normalize(-2, 2)
cmap = LinearSegmentedColormap.from_list('', ['black', 'white', 'black'])
fig, ax = plt.subplots()

def update(f):
ax.cla()
C1 = np.sin(2*np.pi*f*np.sqrt((X - sources[0])**2 + Y**2))
C2 = np.sin(2*np.pi*f*np.sqrt((X - sources[1])**2 + Y**2))
Z = C1 + C2

ax.imshow(Z,
cmap = cmap,
norm = norm)
ax.plot(N/2*(1 + source/axlim), N/2, 'ro')
ax.plot(N/2*(1 - source/axlim), N/2, 'ro')

ax.set_title(f'f = {f} Hz')
ax.set_aspect('equal')
ax.axis('off')

ani = FuncAnimation(fig = fig, func = update, frames = 11, interval = 100)

plt.show()
enter image description here
由于您场的波峰和波谷都是 build 性干扰点,而在破坏性点中场为空,我选择了黑-白-黑颜色图,您无法区分波峰和波谷,但更容易区分 build 性干扰点和破坏性干扰点.

关于python - Matplotlib 干扰图奇怪图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62853745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com