gpt4 book ai didi

python - 使用不同颜色绘制多个函数,包括导数

转载 作者:行者123 更新时间:2023-12-04 00:30:24 25 4
gpt4 key购买 nike

我的 Python 程序有一个非常简单的问题 - 根本没有完成。现在它正在做我想做的一切,但不是我想要的。

plot

我一直试图改变三件事:

  1. 所有函数都使用相同的颜色绘制,我希望程序在将新函数添加到绘图时自动切换到新颜色(它将超过 2 个,都在同一个绘图上) .
  2. f(x) 的范围是 140。我怎样才能减少它?也许到 20/40。
  3. (最重要)我的代码效率不高。 f1derivative 根本没有关联。我在 f1 中声明了函数的模型,但我必须在 derivative 中重新设置所有内容。每次我尝试这样做时,我最终都会遇到 main 函数的一些问题。我最终会添加更多的功能,比如集成和诸如此类的东西,如果我每次想用 f1 做某事时都从头开始声明,那么程序就会失去它的目的。

我应该使用 x = Symbol('x') inside f1吗?

import numpy as np
import matplotlib.pyplot as plt
from sympy import *

x = Symbol('x')

def f1(a, b, c, d):
y = a*x**3 + b*x**2 + x*c + d
return y
###yprime = y.diff(x)
###return yprime

def derivative(a, b, c, d):
y = a*x**3 + b*x**2 + x*c + d
yprime = y.diff(x)
return yprime

def factorail(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

###colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
###for y in ys:
###plt.scatter(x, y, color=next(colors))
def main():
###colors = itertools.cycle(["r", "b", "g"])
y = f1(0,1,2,1)
yp = derivative(0,1,2,1)
print(y)
plot(y, yp)
plot(yp)
plt.show()


if __name__ == '__main__':
main()

最佳答案

垂直窗口由 ylim 选项设置。我建议对 x 也使用一些明确的限制,默认的 -10 到 10 不一定最适合您。我推荐阅读 the page on SymPy plotting .

颜色由 line_color 选项设置。不同的颜色需要对 plot 的不同调用,但可以组合使用。示例:

p = plot(y, (x, -5, 5), ylim=(-20, 20), line_color='b', show=False)
p.extend(plot(yp, (x, -5, 5), ylim=(-20, 20), line_color='r', show=False))
p.show()

结果

combined

函数复用很容易:

def derivative(a, b, c, d):
y = f1(a, b, c, d)
yprime = y.diff(x)
return yprime

另外:如果我们尝试 line_color=['b', 'r'] 会发生什么,如 plot(y, yp, ylim=(-20, 20), line_color =['b', 'r'])?有趣的事情发生了:

funny

关于python - 使用不同颜色绘制多个函数,包括导数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com