Color area beneath sympy function plot

别说谁变了你拦得住时间么 提交于 2020-07-21 05:24:02

问题


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


回答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()



来源:https://stackoverflow.com/questions/62859264/color-area-beneath-sympy-function-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!