Python,如何填充多个(4个)曲线之间的区域?
fig = plt.figure(num=1)
ax=fig.add_subplot(111)
def f1(x):
return 1/x
def f2(x):
return 2/x
def f3(x):
return np.sqrt(x**2-1)
def f4(x):
return np.sqrt(x**2-2)
s= np.arange(np.sqrt(2),5,0.05)
t=np.arange(1,5,0.05)
y1=f1(t)
y2=f2(t)
y3=f3(t)
y4=f4(s)
ax.plot(t,y1,'k-',t,y2,'k-',t,y3,'k-',s,y4,'k-')
plt.xlim([1.1,2.1])
plt.ylim([0.5,1.5])
plt.show()
我想要填充这四个函数所描述的曲线之间的区域。但是我不太确定在这种情况下怎么使用 fill_between
这个选项。
1 个回答
2
你只能用 fill_between
来填充两条曲线,而不是四条。所以,利用你手上的四条曲线,你可以先创建两条新的曲线,分别叫 y5
和 y6
,我在下面展示了这个过程,然后再用这两条曲线来进行 fill_between
。下面是一个示例:
我还用符号绘制了各个函数,这样你就能很清楚地看到刚刚创建的不同新曲线……
import pylab as plt
import numpy as np
fig = plt.figure(num=1)
ax=fig.add_subplot(111)
def f1(x): return 1/x
def f2(x): return 2/x
def f3(x): return np.sqrt(x**2-1)
def f4(x): return np.sqrt(x**2-2)
t=np.arange(1,5,1e-4) # use this if you want a better fill
t=np.arange(1,5,0.05)
y1=f1(t)
y2=f2(t)
y3=f3(t)
y4=f4(t*(t**2>2) + np.sqrt(2)*(t**2<=2) ) # Condition checking
y5 = np.array(map(min, zip(y2, y3)))
y6 = np.array(map(max, zip(y1, y4)))
ax.plot(t,y1, 'red')
ax.plot(t,y2, 'blue')
ax.plot(t,y3, 'green')
ax.plot(t,y4, 'purple')
ax.plot(t, y5, '+', ms=5, mfc='None', mec='black')
ax.plot(t, y6, 's', ms=5, mfc='None', mec='black')
ax.fill_between(t, y5, y6, where=y5>=y6)
plt.xlim([1.1,2.1])
plt.ylim([0.5,1.5])
plt.show()