Search code examples
pythonmatplotlibgraphphysicsgraphing

How do I fill/shade a cetain section of my graph in python?


I have a function that I'd like to plot in python and shade the region of interest. I've tried using pyplot.fill_between() but can not quite get what I want. I've attached an image and shaded in orange the region I want to be filled:

Graph with the desired result

I plot the function (in blue) and then the graph is bounded by y=0, y ≈ 0.05 and x = 0.And I wish to shade the relevant region (in orange).

Any tips as to how to go about this?

Thanks in advance.

import numpy as np
import matplotlib.pyplot as plt



def fn (M, r_min):
    
    d = (1- 2*M/ r_min)
    x = M/(r_min)**2
    A_0 = d**-0.5
    
    A_dot = np.arange(-0.6,0.5,0.0001) #X axis
    a = np.zeros(len(A_dot)) 
    
    for i in range(1,len(A_dot)):
    
        a[i] = -3*d*A_dot[i]**2 -2*x*A_dot[i] + A_0**2*x**2   #Y axis      
    
    plt.plot(A_dot, a)
    plt.xlim(-0.55,0.55)
    
    plt.axhline(y = 0, color='black', linestyle='--')
    plt.axhline(y = 0.049382716, color = 'black', linestyle = '--')
    plt.axvline(x = 0,color ='black', linestyle = '--')
    idx = np.argwhere(np.diff(np.sign(a))).flatten() #Finding intersection on x+axis
    plt.plot(A_dot[idx], a[idx], 'ro')
    
    plt.xlabel('$\\frac{dA_0}{d\tau}$')
    plt.ylabel('$|a|^2$')
              
      
    plt.show()
    
    return(A_dot,a)
    
    
fn(1,3)



Solution

  • You need to give the x and y vectors as inputs to fill_between. To do that, you can define a mask selecting between the interception point and 0 (add to your fn function):

    x_min = A_dot[idx[1]]
    x_max = 0.0
    mask_x = np.logical_and(A_dot >= x_min, A_dot <= x_max)
    plt.fill_between(x=A_dot[mask_x], y1=a[mask_x], y2=0, color='orange')
    

    Result:

    Graph with the filled area