## How to port this plot from geogebra to python?

A forum for general discussion of the Python programming language.

### How to port this plot from geogebra to python?

I'm trying to get my head around how does ploting in python works, I have this plot made in geogebra, very easy, but I'd like to do it in python, this is what I have tried:

Geogebra:

My python code:

Code: Select all
`import matplotlib.pyplot as pltimport numpy as npdef f(x):    return 4*x**2-5*x+3def g(x):    return 8*x-5x = np.linspace(0, 10, 1000)y = f(x)z = g(x)plt.plot(x, y)plt.plot(x, z)plt.show()`

ismaelvc

Posts: 7
Joined: Tue Apr 01, 2014 3:35 pm

### Re: How to port this plot from geogebra to python?

Code: Select all
`# give it the x values you're interested inx = np.linspace(-4, 7, 1000)y = f(x)z = g(x)plt.plot(x, y)plt.plot(x, z)# limit the y axis displayplt.ylim([0, 6])plt.show()`

You end up with something like this:
figure_1.png (8.64 KiB) Viewed 705 times
Friendship is magic!

R.I.P. Tracy M. You will be missed.

stranac

Posts: 1486
Joined: Thu Feb 07, 2013 3:42 pm

### Re: How to port this plot from geogebra to python?

Wow thank you very much Stranac!

Do you know if there is a way to show the x and y axes, of the cartesian plane, like in the original example, I just found grid(), which helps, but it's not exactly what I need, This is what I've got so far!

Code: Select all
`# nos permite mostrar las imagenes aquí mismo, # en vez de que se abra una ventana nueva%matplotlib inlineimport matplotlib.pyplot as plt # módulo usado para plotearimport numpy as np # módulo para manipular arreglos # despues se definen las funcionesdef f(x):    return 4*x**2 -5*x +3 # 4x²-5x+3def df(x):    return 8*x-5 # 8x-5# arreglos usados como (x, y)x = np.linspace(-2, 4, 50)y1 = f(x)y2 = df(x)# genera la gráficaplt.plot(x, y1, marker='o', linestyle='--', color='b', label=r'\$f(x)=4x^2-5x+3\$')plt.plot(x, y2, marker='.', linestyle='-', color='r', label=r"\$f'(x)'dx=8x-5\$")# titulo y etiquetas de los ejesplt.title("\$dy=f'(x)dx\$\n")plt.xlabel('\$x\$')plt.ylabel('\$y\$', rotation=True)# fijar los limites de los ejesplt.ylim([0, 6])plt.xlim([-2, 4])plt.grid() # activar la cuadriculaplt.legend() # activar leyenda# guardar la figurafigura = plt.gcf() # "get current figure" / 'obtener la figura actual'figura.set_size_inches(10, 10) # fijar tamaño a 10x10 pulgadasplt.savefig('figura_1', dpi=100) # nómbre y dpisplt.show() # mostrar la figura`

ismaelvc

Posts: 7
Joined: Tue Apr 01, 2014 3:35 pm

### Re: How to port this plot from geogebra to python?

Seems to do the trick:
Code: Select all
`import numpy as npimport matplotlib.pyplot as pltdef f(x):    return 4*x**2-5*x+3def g(x):    return 8*x-5x = np.linspace(-4, 7, 1000)y = f(x)z = g(x)plt.plot(x, y)plt.plot(x, z)plt.grid(True)plt.axhline(0, color="black", lw=1)plt.axvline(0, color="black", lw=1)plt.ylim([-3,6])plt.show()`

-Mek
• Use code tags when posting code.
• Include any errors with your post (in code tags).
• Make examples the minimum length to demonstrate your issue.

Mekire

Posts: 1501
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

### Re: How to port this plot from geogebra to python?

Thank you very much Mekire!

I'm trying to encapsulate the code into a function for generalization, but I don't know if it'll work with more examples, this is as far as I could do today, I have to sleep and have exams tomorrow, what do you guys think about it?

Code: Select all
`import matplotlib.pyplot as pltimport numpy as npimport sympy as spdef graf_dif(y, lnsp=(-10, 10, 1000), ylim=(-15, 15), xlim=(-15, 15), alto=10,             ancho=10, marcador_y=None, marcador_dy=None, estilo_y='-',             estilo_dy='-', color_y='blue', color_dy='red', color_ejes='green',             guardar=False, dpis=100, nombre='grafica_diferencial.png'):    '''    Graficadora de Ecuaciones Diferenciales.    Uso:    >>> from grafica import graf_dif as gf    >>> import sympy as sp    >>> x = sp.symbols('x')    >>> # 4x² -5x +3    >>> gf(4*x**2 -5*x +3, ylim=(-2, 6), xlim=(-2, 4))    '''    dy = sp.diff(y)    def f(x):        return eval(str(y))    def df(x):        return eval(str(dy))    x1 = np.linspace(*lnsp)    y1 = f(x1)    y2 = df(x1)    plt.plot(x1, y1, marker=marcador_y, linestyle=estilo_y,             color=color_y, label=r'\$f(x)={0}\$'.format(sp.latex(y)))    plt.plot(x1, y2, marker=marcador_dy, linestyle=estilo_dy,             color=color_dy, label=r"\$f'(x)dx={0}\$".format(sp.latex(dy)))    plt.title("\$dy=f'(x)dx\$\n")    plt.xlabel('\$x\$')    plt.ylabel('\$y\$', rotation=True)    plt.ylim(ylim)    plt.xlim(xlim)    plt.grid()    plt.legend()    plt.axhline(color=color_ejes)    plt.axvline(color=color_ejes)    figura = plt.gcf()    figura.set_size_inches(ancho, alto)    if guardar:        plt.savefig(nombre, dpi=dpis)    plt.show()`
ismaelvc

Posts: 7
Joined: Tue Apr 01, 2014 3:35 pm