首页 > 解决方案 > 比较三个函数并绘制特定区域

问题描述

假设我们有以下函数:

f_1 = ((x[2]/(5+x[1]))**((x[1]+5)/4))
f_2 = (5+x[1]*((x[2]-5)/x[1])**((x[1]+5)/4)))/(5+x[1])
f_3 = (5*((X[2]-X[1])/5)**((x[1]+5)/4))+X[1])/(5+X[1])

此外,我们假设:

x[1] = np.linspace(0,7,0.001)
x[2]= np.linspace(0,5+x[1],0.001)

我需要绘制一个图来阐明每个函数大于其他两个函数的区域。x-axis = x[1],y-axis = x[2]

标签: pythonnumpymatplotlibscipy

解决方案


您的部分问题是,当您提到您的功能是 2D 时,使用fill_between()不是您的最佳选择。您应该做的是创建一个 2D 网格,然后在该网格上循环您的函数的值,并将最大值设置为代表该函数的数字。然后使用类似contourf()pcolormesh()为您的值区域着色。

这应该会有所帮助,但请注意,我将x[1]and更改x[2]为简单地xy使用了一个具有适度分辨率的任意大区域:

import numpy as np
from matplotlib import pyplot as plt


#Create the background x[1] and x[2] values. I used x and y instead
x = np.arange(-20,20,.1)
y = np.arange(-40,40,.2)

x,y = np.meshgrid(x,y) #Make the 2D grid

#Apply those functions on the grid
f_1 = ((y/(5.+x))**((x+5.)/4.))
f_2 = (5.+x*((y-5.)/x)**((x+5.)/4.))/(5.+x)
f_3 = (5.*((y-x)/5.)**((x+5.)/4.)+x)/(5.+x)

#Create an array to update with which function is the max
maxf = np.zeros(shape=f_1.shape)
maxf.fill(np.nan) #Fill with nans since there may be regions that are undefined


#Now loop over your grid and find which function is the largest
#If f_1 is largest, set maxf to 1, if f_2 is largest set maxf to 2,  etc.
for i in range(len(x)):
    for j in range(len(y)):
        if f_1[i,j]>f_2[i,j] and f_1[i,j]>f_3[i,j]:
            maxf[i,j] =1
        elif f_2[i,j]>f_1[i,j] and f_2[i,j]>f_3[i,j]:
            maxf[i,j] =2
        elif f_3[i,j]>f_1[i,j] and f_3[i,j]>f_2[i,j]:
            maxf[i,j] =3




#Plot the functions using contourf or pcolormesh
plt.contourf(x,y,maxf)
plt.colorbar()
plt.show() 

在此处输入图像描述


推荐阅读