3
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()

enter image description here

How can I make use of the fill_between() to fill the area between the 2 lines? In other words, how can I fill the small flower petal between the green and blue lines?

user
  • 5,370
  • 8
  • 47
  • 75
AlvinL
  • 438
  • 5
  • 24

2 Answers2

6

@user 5061 was right on the code, inverse function was off there

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()

Not taking the positive component 1 + (1-x*x)**0.5 since it doesn't affect the intersection.

enter image description here

Zero
  • 74,117
  • 18
  • 147
  • 154
  • I understand you expressed y in terms of x in f2, however, you have 2 possible expressions, no? Based on what did you choose the expression with +? – AlvinL Apr 12 '15 at 10:09
  • `1 + (1-x*x)**0.5` is always `>1` for `0 – Zero Apr 12 '15 at 10:11
2

You can use fill_between() and fill between your two lines when a condition is met.

enter image description here

(I altered a bit your code, since the way you wrote it i had to find the inverse function of 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()
user
  • 5,370
  • 8
  • 47
  • 75