Hello. How to create a program that draws graphs of functions in MatplotLib. I have sketched something here:

# -*- coding: utf-8 -*- from numpy import * import matplotlib.pyplot as plt import math import pylab from matplotlib import mlab print("Π‘Ρ‚Ρ€ΠΎΠΈΡ‚Π΅Π»ΡŒ Π³Ρ€Π°Ρ„ΠΈΠΊΠΎΠ²") f = input ('f(x)=') code = """ def func (x): return %s """ % f exec(code) xmin = -20.0 xmax = 20 dx = 0.01 xlist = mlab.frange (xmin, xmax, dx) ylist = [func (x) for x in xlist] plt.axis([-20, 20, -20, 20]) plt.xlabel('x') plt.ylabel('y') plt.title('Π“Ρ€Π°Ρ„ΠΈΠΊ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ(x)') plt.grid(True) pylab.plot (xlist, ylist) pylab.show() 

It's ok. But as I start to touch:

 code = """ def func (x): return %s """ % f 

writes that there is an extra indent, but the question is: where? I want to insert here also while, so that infinitely it was possible to build graphs of functions, but I can not because of this.

Tell me how to make it so that I can infinitely build graphs of functions? :)

Who has any options?

  • Delete the tab in the function and set it again. It worked for me ... - Pavel Durmanov

1 answer 1

UPDATE: build graphs of all functions at once. Functions that do not have the variable x (for example, f(x) = 5 + 20 ) will be converted to the form: f(x) = x/x * (5 + 20)

 # -*- coding: utf-8 -*- import numexpr as ne import matplotlib.pyplot as plt from matplotlib import mlab plt.style.use('ggplot') xmin = -20.0 xmax = 20 dx = 0.01 x = mlab.frange(xmin, xmax, dx) funcs = ["x**2 * sin(x)", "x**2", "15", "12 + 34"] # ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²ΡƒΠ΅ΠΌ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ, Π² ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… отсутствуСт пСрСмСнная `x` ΠΊ Π²ΠΈΠ΄Ρƒ: `x/x * (5)` new_funcs = [f if 'x' in f else 'x/x * ({})'.format(f) for f in funcs] [plt.plot(x, ne.evaluate(f), linewidth=1.5) for f in new_funcs] plt.title('Π“Ρ€Π°Ρ„ΠΈΠΊΠΈ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΉ') plt.xlabel('x') plt.ylabel('y') plt.legend(funcs) plt.show() 

enter image description here

Converted functions:

 In [25]: new_funcs Out[25]: ['x**2 * sin(x)', 'x**2', 'x/x * (15)', 'x/x * (12 + 34)'] 

PS I should add some exception handling, but I'm too lazy ...


Previous answer:

Use the numexpr module:

 # -*- coding: utf-8 -*- import numexpr as ne import matplotlib.pyplot as plt from matplotlib import mlab plt.style.use('ggplot') xmin = -20.0 xmax = 20 dx = 0.01 x = mlab.frange(xmin, xmax, dx) # f = input ('f(x)=') f = "x**2 * sin(x)" plt.plot(x, ne.evaluate(f), linewidth=1.5) plt.xlabel('x') plt.ylabel('y') plt.legend(['Π“Ρ€Π°Ρ„ΠΈΠΊ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ: f(x) = {}'.format(f)]) plt.show() 

enter image description here