Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I wanted to plot y=(x+2)(x−1)(x−2) for x going from −3 to 3 using a dashed red line. When I wrote the following code, nothing shows up.

import numpy as np
import matplotlib.pyplot as plt


def graph(formula, x_range):

    x = np.array(x_range)
    y = eval(formula)
    plt.plot(x, y)
    plt.show()

    graph('((x-3) * (x-2))', range(-3,3))
share|improve this question

1 Answer 1

up vote 1 down vote accepted

Make sure graph(..) call is outside the graph function definition (IOW, indent correctly):

import numpy as np
import matplotlib.pyplot as plt

def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)
    plt.plot(x, y, 'r--')   # `r--` for dashed red line
    plt.show()

graph('((x-3) * (x-2))', range(-3,3))  # <----

UPDATE

It's not a good idea to use eval. Instead you can pass a function in this case.

def graph(formula, x_range):
    x = np.array(x_range)
    y = formula(x)  # <-----
    plt.plot(x, y, 'r--')
    plt.show()

graph(lambda x: (x-3) * (x-2), range(-3,3))  # <---
share|improve this answer
    
@karel, Thank you for pointing that. I updated the answer accordingly. BTW, I was in the middle of editing the answere to not to use eval. –  falsetru 2 hours ago
    
@karel thanks for pointing that out, really helped me :) –  ssr 1 hour ago
    
that was really helpful. I am new to numpy and matplotlib and this solve so many of my basic questions. Thanks! –  ssr 1 hour ago
    
@ssr, Please post a separate question. –  falsetru 40 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.