7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
Taller Matplotlib
Matplotlib (https://matplotlib.org) es una librería que permite la creación de figuras y gráficos de
calidad mediante el uso de Python.
Permite la creación de gráficos de manera sencilla y eficiente
Permite la integración de gráficos y figuras en un Jupyter Notebook
Import
In [2]: import matplotlib
import matplotlib.pyplot as plt
In [3]: # Muestrar los gráficos integrados dentro de jupyter notebook
%matplotlib inline
Representación gráfica de datos
Si a la función de trazado se le da una matriz de datos, la usará como coordenadas en el eje
vertical, y utilizará el índice de cada punto de datos en el array como la coordenada horizontal.
In [4]: plt.plot([1,2,5,7,8,3,1])
plt.show()
También se puede proporcionar dos matrices: una para el eje horizontal, y otra para el eje vertical.
localhost:8848/notebooks/Taller Matplotlib.ipynb# 1/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [5]: plt.plot([-3,-1,0,4,7],[1,4,6,7,8])
Out[5]: [<matplotlib.lines.Line2D at 0x287ffab4be0>]
Pueden modificarse las logitudes de los ejes para que la figura no se vea tan ajustada
In [6]: plt.plot([-3,-2,0,8,9],[1,4,5,10,12])
plt.axis([-4,8,0,10])
plt.show()
Se sigue el mismo procedimiento para pintar una función matemática
localhost:8848/notebooks/Taller Matplotlib.ipynb# 2/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [11]: import numpy as np
x=np.linspace(-2,2,500)
y=x**2
plt.plot(x,y)
plt.show()
También pude modificarse el estilo de la gráfica para que contenga más información.
In [12]: plt.plot(x,y)
plt.title("Función Cuadrática")
plt.xlabel("x")
plt.ylabel("y=x**2")
plt.grid(True)
plt.show()
localhost:8848/notebooks/Taller Matplotlib.ipynb# 3/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
Pueden superponerse gráficas y cambiar el estilo de las líneas
In [15]: import numpy as np
x=np.linspace(-2,2,500)
y=x**2
y2=x+1
plt.plot(x,y, 'b--',x,y2,'g')
plt.show()
In [20]: # Separando en diferentes lineas las funciones
import numpy as np
x=np.linspace(-2,2,500)
y=x**2
y2=x+1
plt.plot(x,y, 'b--')
plt.plot(x,y2,'c')
plt.show()
Para poder diferenciar entre ambas funciones siempre es recomendable añadir una leyenda
localhost:8848/notebooks/Taller Matplotlib.ipynb# 4/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [23]: import numpy as np
x=np.linspace(-2,2,500)
y=x**2
y2=x+1
plt.plot(x,y, 'b--', label ="x**2")
plt.plot(x,y2,'c', label ="x+1")
plt.legend(loc="best")
plt.show()
Tambien puede crearse dos graficas que no se superpongan. Estas graficas se organizan en un
grid y se denominan subplots.
localhost:8848/notebooks/Taller Matplotlib.ipynb# 5/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [26]: x=np.linspace(-2,2,500)
y=x**2
y2=x+1
plt.subplot(1, 2, 1)
plt.plot(x,y, 'b_-')
plt.subplot(1, 2, 2)
plt.plot(x,y2, 'g')
plt.show()
Para que las gráficas no queden tan ajustadas, podemos hacer la figura más grande.
localhost:8848/notebooks/Taller Matplotlib.ipynb# 6/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [28]: plt.figure(figsize=(14,6))
plt.subplot(1, 2, 1)
plt.plot(x,y, 'b_-')
plt.xlabel("x1", fontsize=16)
plt.ylabel("y1", fontsize=16)
plt.subplot(1, 2, 2)
plt.plot(x,y2, 'g')
plt.xlabel("x2", fontsize=16)
plt.ylabel("y2", fontsize=16)
plt.show()
In [31]: x=[1,2,3,4,5,6]
y=[2,4,6,8,10,12]
x1=[3,5,7,9,11]
y1=[2,3,6,8,10]
localhost:8848/notebooks/Taller Matplotlib.ipynb# 7/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [33]: plt.plot(x,y, color="blue", linewidth=5, label="Linea x-y")
plt.plot(x1,y1, color="green", linewidth=4, label="Linea x1-y1")
plt.title("Gráfico Lineas")
plt.xlabel("Eje X")
plt.ylabel("Eje Y")
plt.grid()
plt.legend()
plt.show()
Scatter plots
In [34]: from numpy.random import rand
x,y =rand (2,100)
plt.scatter(x,y)
plt.show()
localhost:8848/notebooks/Taller Matplotlib.ipynb# 8/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [35]: x,y =rand (2,100)
x2,y2 = rand(2,100)
plt.scatter(x,y, c='red')
plt.scatter(x2,y2, c='blue')
plt.show()
Histogramas
localhost:8848/notebooks/Taller Matplotlib.ipynb# 9/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [38]: data=[1,1.1,1.8,2,2.1,3.2,3,3,3,3.2]
plt.subplot(211)
plt.hist(data,bins=10, rwidth=0.8)
plt.xlabel("Valores")
plt.xlabel("Frecuencia")
plt.subplot(212)
plt.hist(data,bins=[1,1.5,2,2.5,3], rwidth=0.95)
plt.xlabel("Valores")
plt.xlabel("Frecuencia")
plt.show()
Tortas
localhost:8848/notebooks/Taller Matplotlib.ipynb# 10/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [39]: x=[1,2,3,4,5,6]
plt.pie(x, labels=x)
plt.title("Gráfico Torta")
plt.xlabel("Eje X")
plt.ylabel("Eje Y")
plt.grid()
plt.legend()
plt.show()
Barras
In [40]: # Creación de Gráficos
x=[1,2,3,4,5,6]
y=[2,3,6,8,9,10]
x1=[3,5,7,9,11]
y1=[2,4,6,8,19]
localhost:8848/notebooks/Taller Matplotlib.ipynb# 11/12
7/9/22, 19:53 Taller Matplotlib - Jupyter Notebook
In [45]: plt.bar(x,y, color="blue", linewidth=5, label="Linea x-y")
plt.bar(x1,y1, color="green", linewidth=4, label="Linea x1-y1")
plt.title("Gráfico Lineas")
plt.xlabel("Eje X")
plt.ylabel("Eje Y")
plt.grid()
plt.legend()
plt.savefig("Gráfico_barras_verticales.png", transparent=True)
plt.show()
Guardar las figuras
In [ ]:
In [ ]:
In [ ]:
localhost:8848/notebooks/Taller Matplotlib.ipynb# 12/12