matplotlib.plt adds an unwanted line when using fill_between

Question:

Question about using fill_between:

Using fill_between in the following snippet adds an unwanted vertical and horizontal line. Is it because of the parametric equation? How can I fix it?

import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 2 * np.pi, 100)
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2*np.cos(3*t) - np.cos(4*t)
plt.plot(x,y, 'red', linewidth=2)
plt.fill_between(x, y, color = 'red', alpha = 0.2)

Here is the outcome:

Please notice the horizontal and vertical lines

Asked By: NNsr

||

Answers:

You can use plt.fill to fill an area bounded by xy values. plt.fill_between fills between zero and a curve defined as y being a function of x.

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 2 * np.pi, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
plt.plot(x, y, 'deeppink', linewidth=2)
plt.fill(x, y, color='deeppink', alpha=0.2)
plt.axis('off')
plt.show()

plt.fill instead of plt.fill_between

Or in a loop:

t = np.linspace(0, 2 * np.pi, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
for r in np.linspace(1, 0.01, 50):
    plt.fill(r * x, r * y, color=plt.cm.Reds(r))
plt.axis('off')
plt.show()

plt.fill in a loop

Answered By: JohanC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.