pythonmatplotlibspectra

Shading Using Matplotlib


I am trying to shade the region under the emission line, but I am having trouble cutting off the shading at the continuum (represented by the straight red line). Anyone have a fix for this? I have been unable to find an answer.

These are the lines of code that handle the plotting and region shading.

` # 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')

# Shade the region for equivalent width calculation
plt.fill_between(wavelengths, fluxes, 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()

`

enter image description here

Listed previously...


Solution

  • plt.fill_between can take a second height argument, y2, so you can fill between two curves (by default it is set to 0).

    plt.fill_between(x=wavelengths, y1=fluxes, y2=y_values)
    

    This will only work if len(fluxes) == len(y_values), but you did not give enough information to run the code, so I cannot test it.