Fill the common interior of two polar curves with matplotlib fill_between

Viewed 38

I'm trying to fill the common interior of circle and cardioid in polar coordinates (r1= sqrt(3)* sin(φ) and r2= 1 - cos(φ)). I've found a simple solution in this question — find the minimum of two functions and fill an area between 0 and minimum. Code:

import matplotlib.pyplot as plt
import numpy as np
import math

phi =  np.arange(0, (2 * np.pi), 0.01)
r1 = math.sqrt(3) * np.sin(phi)
r2 = 1 - np.cos(phi)
r3 = np.minimum(r1, r2)

plt.polar(phi, r1)
plt.polar(phi, r2)
plt.fill_between(phi, 0, r3, color='#D0D0FF')
plt.show()

But the end result is strange. The bottom part, where φ goes from 2π to 0, is 'inverted'.

Resulting plot

Perhaps I don't understand the 'where' argument of 'fill_between'. Any ideas?

1 Answers

Your polar plot's radial axis has a range that goes from approximately -1.7 to 2.

So with your call plt.fill_between(phi, 0, r3, color='#D0D0FF') you're missing the part between -1.7 and 0 when the cradiod dips below 0.

This modified code will work : I changed the 0 in fill_between to min(r1) and the r-axis limits to min(r1) and max(r2) to fit the plot.

import matplotlib.pyplot as plt
import numpy as np
import math

phi =  np.arange(0, (2 * np.pi), 0.01)
r1 = math.sqrt(3) * np.sin(phi)
r2 = 1 - np.cos(phi)
r3 = np.minimum(r1, abs(r2))

plt.polar(phi, r1)
plt.polar(phi, r2)
plt.ylim(min(r1),max(r2))
plt.fill_between(phi, min(r1), r3, color='#D0D0FF')
plt.show()

enter image description here

Hope this helps !

Related