You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Matplotlib在连续谱红线处截断发射线下方填充区域?

解决发射线填充区域在连续谱处截断的问题

你当前的填充代码是将光谱通量与0之间的区域进行填充,要实现填充区域在红色连续谱处截断,核心是利用fill_between的y2参数,把填充的下限指定为连续谱的通量值。具体操作步骤如下:

  1. 对齐连续谱与光谱的波长点
    由于连续谱是基于x_values拟合得到的,而填充使用的是wavelengths数组,需要通过插值方法,得到每个wavelengths对应的连续谱通量值:

    import numpy as np
    
    # 插值得到连续谱在wavelengths每个点的通量
    continuum_flux = np.interp(wavelengths, x_values, y_values)
    
  2. 修改填充代码
    将原有的fill_between调用替换为以下形式,用y2=continuum_flux指定填充的下限,这样填充区域就会被连续谱截断。如果需要精准限定发射线范围,还可以加上where参数:

    # 填充发射线与连续谱之间的区域,仅限定在交点范围内
    plt.fill_between(wavelengths, continuum_flux, fluxes, 
                     where=(wavelengths >= min(x_intersect)) & (wavelengths <= max(x_intersect)),
                     color='gray', alpha=0.5, label='Equivalent Width')
    
  3. 完整修改后的代码

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Plot the spectrum
    plt.plot(wavelength1, fluxe1, color='blue', label='Spectrum')
    plt.scatter(x_values, [yl, yr], color='red', label='Data Points')
    plt.plot(x_values, y_values, color='red', label='Linear Equation')
    
    # 插值得到连续谱在填充波长点上的通量
    continuum_flux = np.interp(wavelengths, x_values, y_values)
    
    # Shade the region for equivalent width calculation
    plt.fill_between(wavelengths, continuum_flux, fluxes, 
                     where=(wavelengths >= min(x_intersect)) & (wavelengths <= max(x_intersect)),
                     color='gray', alpha=0.5, label='Equivalent Width')
    
    # Plot the intersection point
    plt.axvline(x_intersect, color='red', linestyle='--', label='Intersection Point')
    
    # Set the plot limits
    plt.xlim(5650, 5750)
    plt.ylim(0, 2.5)
    
    # Add labels and legend
    plt.xlabel('Wavelength (angstroms)')
    plt.ylabel('Flux')
    plt.legend()
    
    # Show the plot
    plt.show()
    

关键说明

  • np.interp用于将连续谱的线性拟合结果映射到填充所用的所有波长点上,保证两者维度一致。
  • fill_between的前两个参数分别对应填充的下限和上限,这里发射线通量高于连续谱,因此填充continuum_flux(下限)与fluxes(上限)之间的区域。
  • where参数可以精准限制填充的波长范围,避免填充到连续谱以外的区域。

内容的提问来源于stack exchange,提问作者AnalysisR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:05:08