import matplotlib.pyplot as plt
import numpy as np
def domain():
x = np.arange(0, 10, 0.001)
f1 = lambda x: (2*x - x**2)**0.5
plt.plot(x, f1(x), label = '$y = \sqrt{2x - x^2}$')
plt.plot(f1(x), x, label = '$x = \sqrt{2y - y^2}$')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
axes = plt.gca()
axes.set_xlim([0, 5])
axes.set_ylim([0, 5])
plt.show()
domain()
如何利用fill_between()
填充2行之间的区域?换句话说,我怎样才能在绿线和蓝线之间填充小花瓣?
答案 0 :(得分:5)
@user 5061在代码上是正确的,反函数在那里
import matplotlib.pyplot as plt
import numpy as np
def domain():
x = np.arange(0, 10, 0.001)
f1 = lambda x: (2*x - x**2)**0.5
f2 = lambda x: 1 - (1-x*x)**0.5 # other part is f2 = lambda x: 1 + (1-x*x)**0.5
plt.plot(x, f1(x), label = '$y = \sqrt{2x - x^2}$')
plt.plot(f1(x), x, label = '$x = \sqrt{2y - y^2}$')
plt.fill_between(x, f1(x), f2(x), where=f1(x)>=f2(x), interpolate=True, color='yellow')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
axes = plt.gca()
axes.set_xlim([0, 5])
axes.set_ylim([0, 5])
plt.show()
domain()
不采用正面成分1 + (1-x*x)**0.5
,因为它不会影响交叉点。
答案 1 :(得分:2)
您可以使用fill_between()
并在满足条件时在两行之间填写。
(我改变了你的代码,因为你写它的方式我必须找到f1
的反函数)
import matplotlib.pyplot as plt
import numpy as np
def domain():
x = np.arange(0, 2, 0.001)
f = lambda x: x**0.5
g = lambda x: x**2
plt.plot(x, f(x), label = '$y = \sqrt{2x - x^2}$')
plt.plot(x, g(x), label = '$x = \sqrt{2y - y^2}$')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.fill_between(x, f(x), g(x),where=f(x) > g(x))
axes = plt.gca()
axes.set_xlim([0, 2])
axes.set_ylim([0, 2])
plt.show()
domain()