首页 > 解决方案 > fill space between graphs in Matplotlib

问题描述

I need to fill the area between y, y1 and y2 but I am filling up the extra space under the y graph.How do I fix 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)

plt.fill_between(x, np.minimum(y2(c), y1(x)), y1(x), alpha=0.5)
plt.legend()
plt.show()

标签: pythonnumpymatplotlibmathplot

解决方案


我不使用numpy,所以我想可以通过另一种方式获得综合列表。

    x_before = np.array([a for a in x if y(a) > y2(a)])
    x_after = np.array([a for a in x if a >= max(x_before) and y1(a) >= y2(a)])
    plt.fill_between(x_before, y(x_before), y1(x_before), color="lightblue")
    plt.fill_between(x_after, y2(x_after), y1(x_after), color="lightblue")

在此处输入图像描述


推荐阅读