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?

Postby ismaelvc » Mon Apr 07, 2014 4:31 am

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:

Image

My python code:

Code: Select all
import matplotlib.pyplot as plt
import numpy as np


def f(x):
    return 4*x**2-5*x+3


def g(x):
    return 8*x-5


x = np.linspace(0, 10, 1000)
y = f(x)
z = g(x)

plt.plot(x, y)
plt.plot(x, z)
plt.show()


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

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

Postby stranac » Mon Apr 07, 2014 9:53 am

Code: Select all
# give it the x values you're interested in
x = np.linspace(-4, 7, 1000)
y = f(x)
z = g(x)

plt.plot(x, y)
plt.plot(x, z)

# limit the y axis display
plt.ylim([0, 6])

plt.show()

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

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1143
Joined: Thu Feb 07, 2013 3:42 pm

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

Postby ismaelvc » Mon Apr 07, 2014 11:42 pm

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 inline

import matplotlib.pyplot as plt # módulo usado para plotear
import numpy as np # módulo para manipular arreglos


# despues se definen las funciones
def f(x):
    return 4*x**2 -5*x +3 # 4x²-5x+3


def 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áfica
plt.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 ejes
plt.title("$dy=f'(x)dx$\n")
plt.xlabel('$x$')
plt.ylabel('$y$', rotation=True)

# fijar los limites de los ejes
plt.ylim([0, 6])
plt.xlim([-2, 4])

plt.grid() # activar la cuadricula
plt.legend() # activar leyenda

# guardar la figura
figura = plt.gcf() # "get current figure" / 'obtener la figura actual'
figura.set_size_inches(10, 10) # fijar tamaño a 10x10 pulgadas
plt.savefig('figura_1', dpi=100) # nómbre y dpis

plt.show() # mostrar la figura


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

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

Postby Mekire » Tue Apr 08, 2014 1:54 am

Seems to do the trick:
Code: Select all
import numpy as np
import matplotlib.pyplot as plt


def f(x):
    return 4*x**2-5*x+3


def g(x):
    return 8*x-5


x = 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
User avatar
Mekire
 
Posts: 988
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

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

Postby ismaelvc » Tue Apr 08, 2014 6:18 am

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 plt
import numpy as np
import sympy as sp


def 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


Return to General Discussions

Who is online

Users browsing this forum: Crimson King and 2 guests