Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot several functions using different colors, including a derivative

I have a really simple issue with my Python program -- which isn't finished at all. Right now it's doing everything I want, but not how I want.

plot

There are three things I've been trying to change:

  1. all functions are being plotted using the same color, and I'd like the program to automatically switch to a new color when a new function is added to the plot (it will be more than 2, all on the same plot).
  2. f(x)'s range is 140. How can I decrease that? Maybe to 20/40.
  3. (most important) My code isn't very efficient. f1 and derivative are not associated at all. I declare the function's model in f1, but I have to set up everything again in derivative. Every time I try to do otherwise I end up having some problem with the main function. I'll eventually add more features like integration and whatnot, and if I'm declaring everything from scratch everytime I want to do something with f1 the program will kinda lose its purpose.

Should I use 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()
like image 841
Richie P. Avatar asked Dec 28 '25 23:12

Richie P.


1 Answers

Vertical window is set by ylim option. I recommend to also use some explicit limits for x, the default -10 to 10 is not necessarily best for you. And I do recommend reading the page on SymPy plotting.

Color is set by line_color option. Different colors require different calls to plot, but those can be combined. Example:

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

results in

combined

The function reuse is easy:

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

Aside: what happens if we try line_color=['b', 'r'], as in plot(y, yp, ylim=(-20, 20), line_color=['b', 'r'])? Funny stuff happens:

funny


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!