python - 比较三个函数并绘制特定区域
问题描述
假设我们有以下函数:
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]
解决方案
您的部分问题是,当您提到您的功能是 2D 时,使用fill_between()
不是您的最佳选择。您应该做的是创建一个 2D 网格,然后在该网格上循环您的函数的值,并将最大值设置为代表该函数的数字。然后使用类似contourf()
或pcolormesh()
为您的值区域着色。
这应该会有所帮助,但请注意,我将x[1]
and更改x[2]
为简单地x
并y
使用了一个具有适度分辨率的任意大区域:
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()
推荐阅读
- javascript - 当我单击更新按钮时,我希望在添加具有相同值的课程中打开课程
- perl - 如何从 Perl 中的 URL 中提取域?
- sql - 整个表的 SQL Server Datediff
- c++ - 从右值引用限定的成员函数按值或按右值引用返回?
- prometheus - 对 PromQL 的 DataDog 指标查询
- sql - 从 SQL 子查询中检索特定列数据
- google-apps-script - DriveActivity API 返回函数
- ios - 在 IFrame 中播放媒体 - Ionic IOS
- c - 我正在尝试使用变量在 C 中初始化一个数组,但它不起作用
- sabre - API 在 Sabre 中提供辅助数据/设施以及搜索结果