【问题标题】:How do I fill/shade a cetain section of my graph in python?如何在 python 中填充/着色图表的某个部分?
【发布时间】:2021-05-27 16:21:13
【问题描述】:

我想在 python 中绘制一个函数并为感兴趣的区域着色。我试过使用 pyplot.fill_between() 但不能完全得到我想要的。我附上了一张图片,并用橙色阴影填充了我想要填充的区域:

我绘制函数(蓝色),然后图形以 y=0、y ≈ 0.05 和 x = 0 为界。我希望对相关区域进行着色(橙色)。

关于如何解决这个问题的任何提示?

提前致谢。

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)


【问题讨论】:

    标签: python matplotlib graph physics graphing


    【解决方案1】:

    您需要将xy 向量作为fill_between 的输入。为此,您可以定义一个在截取点和 0 之间选择的掩码(添加到您的 fn 函数):

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

    结果:

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2013-10-22
    • 2015-12-01
    • 2014-11-08
    • 2014-07-20
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2017-12-30
    相关资源
    最近更新 更多