JamCon
JamCon

Reputation: 2333

fill_between function using axline as input generates TypeError

I'm attempting to use an axline as one of the inputs to the matplotlib (version 3.4.3) fill_between() function. Simplified code example code below.

Code:

import numpy as np
import matplotlib.pyplot as plt

# Set my figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]

# Define a linear space between -5 and 5, with 100 points
x = np.linspace(-5, 5, 100)

# Define the Intercept and Slope
intercept0 = 2.2
slope0 = 0.75

# Set the x and y limits for the plot
plt.xlim(-5,5)
plt.ylim(-5,5)

# Create a diagonal line through [0,2.2] with a slope of 0.75
diagline = plt.axline((0,intercept0), slope=slope0, color='C0')

# Fill the area between the diagonal line and y=0
plt.fill_between(x,diagline,0)

plt.show()

When I run that code, I get the following numpy error.

Error:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Is there a way to use the axline as an input for the fill_between() function? I've seen vertical and horizontal lines used as inputs to fill_between(), as well as curved lines (sines), but I cannot find examples of diagonals created with axline.

Upvotes: 0

Views: 469

Answers (1)

JohanC
JohanC

Reputation: 80409

The equation of the line is just slope0 * x + intercept0, which numpy can use unchanged. So, you can do the fill with plt.fill_between(x, slope0 * x + intercept0).

import numpy as np
import matplotlib.pyplot as plt

# Set my figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]

# Define a linear space between -5 and 5, with 100 points
x = np.linspace(-5, 5, 100)

# Define the Intercept and Slope
intercept0 = 2.2
slope0 = 0.75

# Set the x and y limits for the plot
plt.xlim(-5, 5)
plt.ylim(-5, 5)

# Create a diagonal line through [0,2.2] with a slope of 0.75
diagline = plt.axline((0, intercept0), slope=slope0, color='C0')

# Fill the area between the diagonal line and y=0
plt.fill_between(x, slope0 * x + intercept0, 0, facecolor='gold', alpha=0.4, edgecolor='r', hatch='xx')
plt.show()

fill_between up till a diagonal line

PS: If you only want to show the positive part, you could use the where parameter:

y0 =  slope0 * x + intercept0
plt.fill_between(x, y0, 0, where=y0 >= 0, interpolate=True, color='yellow')
plt.axhline(0, color='black') # shows the x-axis at y=0

fill between, only showing positive part

Upvotes: 2

Related Questions