pythonmatplotlib

matplotlib.plt adds an unwanted line when using fill_between


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


Solution

  • 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