简体   繁体   中英

fill space between 3 graphs in Matplotlib

I need to fill in the shaded area between my graphs.What should I write in fill_between to do this?

在此处输入图片说明

import numpy as np
import matplotlib.pyplot as plt

y = lambda z: (2 * z - z ** 2) ** (1 / 2)
y1 = lambda x: (6 * x - x ** 2) ** (1 / 2)
y2 = lambda c: c
x = np.linspace(0, 12, 500)
z = np.linspace(0, 12, 500)
c = np.linspace(0, 12, 500)
plt.ylim(0, 4)
plt.xlim(0, 4)

plt.plot(z, y(z), color='blue', label="$y=\\sqrt{2x-x^2}$")
plt.plot(c, y2(c), color='black', label='$y=x$')
plt.plot(x, y1(x), color='red', label='$y=\\sqrt{6x-x^2}$')
plt.plot([0, 4], [0, 0], color='yellow', label='y=0')
plt.grid(True, zorder=5)
miny = np.minimum(y2(c), y1(x))
plt.fill_between(x, y(z), miny, where=(miny > y(x)), alpha=0.5)
plt.legend()
plt.show()

Make the domain of your functions to be the same (eg [0, 4] ). The below code does what you want:

import numpy as np
import matplotlib.pyplot as plt

x =  np.linspace(0, 4, 500)

y = np.piecewise(x, [x <= 2, x > 2], [lambda x: np.sqrt(2 * x - x ** 2), 0])
y1 = np.sqrt(6 * x - x ** 2)
y2 = x
y3 = 0*x


plt.plot(x, y, color='blue', label="$y=\\sqrt{2x-x^2}$")
plt.plot(x, y1, color='red', label='$y1=\\sqrt{6x-x^2}$')
plt.plot(x, y2, color='black', label='$y2=x$')
plt.plot(x, y3, color='yellow', label='y3=0')
plt.grid(True, zorder=5)
miny = np.minimum(y2, y1)
plt.fill_between(x, y, miny, where = (miny > y), alpha=0.5)
plt.legend()
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM