Maneki Autumn
Maneki Autumn

Reputation: 69

How can I plot derivatives with matplotlib?

I am having a problem of plotting my derivatives. For example of my equation:

The value of x = 3

f(x) = 6x^2 - 2

f'(x) = 12x

f (3) = 36

from scipy.misc import derivative 
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
x = sp.Symbol("x")
ex = int(input("What is the value of x in f(x)? "))
coef = int(input("What is the coefficient of the first value? "))
if coef == 1:
    a = int(input("\nWhat is the value of the first coefficient in the equation? ")) #6
    sign = input("What is the operator of the equation? [+] or [-] ") #-
    expo = int(input("What is the value of exponent for the variable x? ")) #2
    ask = input("Does the 2nd value for the equation has constant? [Y] / [N]: ").upper() #y
    if ask == 'Y': #this will be the accepted condition for my example equation
        b = int(input("What is the value of constant? "))
        if sign == '-':
            f = a * x ** expo - b
        elif sign == '+':
            f = a * x ** expo + b
        derivative = sp.diff(f,x) # derivative of the function
        print (derivative) #prints the derivative as a function of x
        print (derivative.subs(x,ex)) # prints the derivative evaluated at x=3

        plt.plot((derivative.subs(x,ex)))
        plt.plot(derivative)
        plt.show()

I am getting an error where derivative cannot accept float. I made a comment for every inputs so it will be understood on how my program worked.

Error: 
  Message=can't convert expression to float
  Source=D:\VB\Calculus\Calculus\Calculus.py
  StackTrace:
  File "D:\VB\Calculus\Calculus\Calculus.py", line 24, in <module> (Current frame)
    plt.plot(derivative)

Upvotes: 2

Views: 1024

Answers (1)

Zephyr
Zephyr

Reputation: 12524

matplotlib.pyplot.plot requires arrays in order to plot their points, but you are passing to it a sympy object.
In order to plot sympy object, you should use sympy.plotting.plot:
(I simplified your code in order to make the point clear)

import matplotlib.pyplot as plt
from sympy.plotting import plot
import sympy as sp

x = sp.Symbol("x")
ex = 3
a = 6
expo = 2
b = 2

f = a*x**expo - b
derivative = sp.diff(f, x)

plot(derivative, ylabel = "f'(x)")

enter image description here

Upvotes: 3

Related Questions