matplotlib secondary_xaxis在子图中包含全局变量

pvcm50d1  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(208)

我试图做一个图,显示不同频谱的多普勒速度,但脚本似乎不喜欢我改变全局变量的事实。有没有办法解决这个问题?基本上,它只绘制全局变量的最新值的seonemic轴,见下图,顶部的一个甚至没有0。我猜它以某种方式追溯改变了以前的图。
之所以有一个glob,是因为我找不到一种方法来给予这个值,而不使secondary_xaxis函数崩溃。


的数据
最小工作示例:

  1. def doppler(wavelengths):
  2. c = 299792.458 # speed of light in km/s
  3. lambda_0 = linecore # central wavelength in Angstrom
  4. doppler_shifts = c * ((wavelengths-lambda_0) / lambda_0)
  5. return doppler_shifts
  6. def idoppler(doppler_shifts):
  7. c = 299792.458 # speed of light in km/s
  8. lambda_0 = linecore # central wavelength in Angstrom
  9. wavelengths = lambda_0 * (1 + doppler_shifts / c)-linecore
  10. return wavelengths
  11. global linecore
  12. plt.subplot(221)
  13. plt.plot(np.linspace(-1,1,10)+6000, np.random.random([10]))
  14. linecore = 6000
  15. ax1 = plt.gca() # Get the current axis (i.e., the one just created)
  16. ax1a = ax1.secondary_xaxis('top', functions=(doppler, idoppler))
  17. ax1a.set_xticks([-50,0,50])
  18. plt.subplot(222)
  19. plt.plot(np.linspace(-1,1,10)+6000, np.random.random([10]))
  20. linecore = 6000
  21. ax2 = plt.gca() # Get the current axis (i.e., the one just created)
  22. ax2a = ax2.secondary_xaxis('top', functions=(doppler, idoppler))
  23. ax2a.set_xticks([-50,0,50])
  24. plt.subplot(223)
  25. plt.plot(np.linspace(-1,1,10)+8000, np.random.random([10]))
  26. linecore = 8000
  27. ax3 = plt.gca() # Get the current axis (i.e., the one just created)
  28. ax3a = ax3.secondary_xaxis('top', functions=(doppler, idoppler))
  29. ax3a.set_xticks([-50,0,50])
  30. plt.subplot(224)
  31. plt.plot(np.linspace(-1,1,10)+8000, np.random.random([10]))
  32. linecore = 8000
  33. ax4 = plt.gca() # Get the current axis (i.e., the one just created)
  34. ax4a = ax4.secondary_xaxis('top', functions=(doppler, idoppler))
  35. ax4a.set_xticks([-50,0,50])
  36. plt.tight_layout()
  37. plt.show()

字符串

jvlzgdj9

jvlzgdj91#

你应该用咖喱。


的数据

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. C = 299792.458 # speed of light in km/s
  4. def doppler_shifts(wavelengths, λ0):
  5. return C*wavelengths0 - C
  6. def wavelenghts(doppler_shifts, λ0):
  7. return λ0*doppler_shifts/C + λ0
  8. y = iter([np.random.random(10) for _ in range(4)])
  9. fig, ax_2D = plt.subplots(2,2, layout='constrained')
  10. for ax_row, λ0 in zip(ax_2D, (6000, 8000)):
  11. wl = λ0+np.linspace(-1, 1, 10)
  12. # here comes the currying
  13. # note we must trick lambda, otherwise late binding of λ0 is a problem
  14. f0 = lambda wl, λ00: doppler_shifts(wl, λ0)
  15. f1 = lambda ds, λ00: wavelenghts(ds, λ0)
  16. for ax1 in ax_row:
  17. ax1.plot(wl, next(y))
  18. ax2 = ax1.secondary_xaxis('top', functions=(f0, f1))
  19. ax1.set_xlabel('Wave Lenghts')
  20. ax2.set_xlabel('Doppler Shifts')
  21. plt.show()

字符串

展开查看全部

相关问题