2

I have a sympy function, I want to plot it and color the area beneath the curve, how can I do it?

Code

import sympy as sy

x = sy.symbols('x')
f = sy.sin(x)

sy.plot(f, (x, 0, sy.pi))

Plot
enter image description here

Zephyr
  • 11,891
  • 53
  • 45
  • 80

2 Answers2

2

i have created the same output without using matplotlib directly(sympy already uses sympy)

import sympy as sy
import numpy as np
from sympy.plotting import plot
x = sy.symbols('x')
f = sy.sin(x)
x_array = np.linspace(0, np.pi, 1000)
f_array = sy.lambdify(x, f)(x_array)
plot(f, (x, 0, sy.pi), fill={'x': x_array,'y1':f_array,'color':'green'})

i got the output enter image description here

1

You can use plt.fill_between (documentation) but you need to convert your sympy function in a numpy array with sy.lambdify (documentation) before, because plt.fill_between takes in arrays.
Check this code as a reference:

import sympy as sy
import numpy as np
import matplotlib.pyplot as plt

x = sy.symbols('x')
f = sy.sin(x)

x_array = np.linspace(0, np.pi, 1000)
f_array = sy.lambdify(x, f)(x_array)

fig, ax = plt.subplots()

ax.plot(x_array, f_array, color = 'red')
ax.fill_between(x_array, f_array, facecolor = 'red', alpha = 0.3)

plt.show()

enter image description here

Zephyr
  • 11,891
  • 53
  • 45
  • 80
  • I would have preferred to avoid converting the sympy analytic functions to arrays, but it is still fine –  Jul 12 '20 at 09:35