3. Gráficos básicos: matplotlib & seaborn#

import matplotlib as mpl
mpl.get_backend()
'module://matplotlib_inline.backend_inline'
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
#plt.plot?

Dado que el estilo predeterminado es la línea ‘-’, no se mostrará nada si solo pasamos en un punto \((3,2)\)

plt.plot(3, 2)
[<matplotlib.lines.Line2D at 0x7f8f9ff90e20>]
_images/59082810f7c486ec954569c09bab8a55a514c0f788a546f3ee1eecb8a65dbf6b.png

Podemos pasarle ‘.’ a plt.plot para indicar que queremos el punto \((3,2)\) tal que sea puesto como un marker

plt.plot(3, 2, '.')
[<matplotlib.lines.Line2D at 0x7f8fa0283580>]
_images/f77a2e49512f4097d20d8d4c3a24609680c82d788616a0c8cb0eac9a099ce791.png

Veamos como hacer un plot usando la capa scripting.

# Primero configuremos el backend sin usar mpl.use() de la capa de scripting
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure

# crear una nueva figura
fig = Figure()

# asociamos "fig" con el backend
canvas = FigureCanvasAgg(fig)

# se agrega un subplot a la figura
ax = fig.add_subplot(111)

# graficamos el punto (3,2)
ax.plot(3, 2, '.')

# guardamos la figura en test.png
#canvas.print_png('test.png')
[<matplotlib.lines.Line2D at 0x7f8fa040f5b0>]
# creamos una nueva figura
plt.figure()

# graficamos el punto (3,2) usando el marker de circulo
plt.plot(3, 2, 'o')

# obtenemos el eje actual
ax = plt.gca()

# Fijamos las propiedades del eje [xmin, xmax, ymin, ymax]
ax.axis([0,6,0,10])
(0.0, 6.0, 0.0, 10.0)
_images/75166371689e95af89e9a2dd52816f0ef853a8ef49d0e89116b748f37880b975.png
# creamos una nueva figura
plt.figure()

# graficamos el punto (1.5, 1.5) usando un marker de circulo
plt.plot(1.5, 1.5, 'o')
# graficamos el punto (2, 2) usando un marker de circulo
plt.plot(2, 2, 'o')
# graficamos el punto (2.5, 2.5) usando un marker de circulo
plt.plot(2.5, 2.5, 'o')
[<matplotlib.lines.Line2D at 0x7f8fa04baf70>]
_images/374e732a1e66a570d1b188c520c459be9483c70e7d92e5c88c0cb6148e1fa3a4.png
# Accedemos al eje actual
ax = plt.gca()
# obtenemos todos los objetos hijo que contiene el eje
ax.get_children()
[<matplotlib.spines.Spine at 0x7f8fa0600550>,
 <matplotlib.spines.Spine at 0x7f8fa05ec070>,
 <matplotlib.spines.Spine at 0x7f8fa05d3cd0>,
 <matplotlib.spines.Spine at 0x7f8fa05d9ee0>,
 <matplotlib.axis.XAxis at 0x7f8fa05e57c0>,
 <matplotlib.axis.YAxis at 0x7f8fa0600880>,
 Text(0.5, 1.0, ''),
 Text(0.0, 1.0, ''),
 Text(1.0, 1.0, ''),
 <matplotlib.patches.Rectangle at 0x7f8fa06117c0>]
_images/e90d8f2c9f70eecb88a02eac39b631f0c6b659a1fe7234099703577c13a60cca.png

3.1. Scatterplots#

import numpy as np

x = np.array([1,2,3,4,5,6,7,8])
y = x

plt.figure()
plt.scatter(x, y) # similar a plt.plot(x, y, '.'), pero los objetos hijos en "axes" no son Line2D
<matplotlib.collections.PathCollection at 0x7f8fa0974880>
_images/53cc101df2db8b11b299333b077d0b3ef278bb1941d01d1952befd897c4e9482.png
import numpy as np

x = np.array([1,2,3,4,5,6,7,8])
y = x

# creamos una lista de colores para cada punto que tenemos
# ['green', 'green', 'green', 'green', 'green', 'green', 'green', 'red']
colors = ['green']*(len(x)-1)
colors.append('red')

plt.figure()

# graficamos el punto con tamaño 100 y los colores elegidos
plt.scatter(x, y, s=100, c=colors)
<matplotlib.collections.PathCollection at 0x7f8fa02a9730>
_images/2e96eacafcea37daf26ed622bc63ca56434cdcd9a650c5dde3158143158a1ee8.png
# convertimos las dos listas en una lista de tuplas en parejas
zip_generator = zip([1,2,3,4,5], [6,7,8,9,10])

print(list(zip_generator))
# lo de arriba imprime:
# [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

zip_generator = zip([1,2,3,4,5], [6,7,8,9,10])
# La estrella * "desempaca" una colección en argumentos posicionales
print(*zip_generator)
# lo de arriba imprime:
# (1, 6) (2, 7) (3, 8) (4, 9) (5, 10)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
(1, 6) (2, 7) (3, 8) (4, 9) (5, 10)
# use zip para convertir 5 tuplas con 2 elementos cada una en 2 tuplas con 5 elementos cada una
print(list(zip((1, 6), (2, 7), (3, 8), (4, 9), (5, 10))))
# lo de arriba imprime:
# [(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)]


zip_generator = zip([1,2,3,4,5], [6,7,8,9,10])
# volvamos los datos a 2 listas
x, y = zip(*zip_generator) # Lo siguiente es equivalente zip((1, 6), (2, 7), (3, 8), (4, 9), (5, 10))
print(x)
print(y)
# lo de arriba imprime:
# (1, 2, 3, 4, 5)
# (6, 7, 8, 9, 10)
[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)]
(1, 2, 3, 4, 5)
(6, 7, 8, 9, 10)
plt.figure()
# graficar una serie de datos 'Estudiantes altos' en rojo usando los dos primeros elementos de x e y
plt.scatter(x[:2], y[:2], s=100, c='red', label='Estudiantes altos')
# graficamos una segunda serie de datos 'Estudiantes bajos' en azul usando los últimos tres elementos de x e y 
plt.scatter(x[2:], y[2:], s=100, c='blue', label='Estudiantes bajos')
<matplotlib.collections.PathCollection at 0x7f8fa042f670>
_images/53176aa2268f1af00a824bfa6713dae0fe808d42397e8d21659c4a19a9dcb70d.png
# agregamos una etiqueta en el eje x
plt.xlabel('Número de veces que el niño patea una pelota')
# agregamos una etiqueta en el eje y
plt.ylabel('La nota del estudiante')
# add a title
plt.title('Relación entre patear la pelota y notas')
Text(0.5, 1.0, 'Relación entre patear la pelota y notas')
_images/0da3ccf1040e328af2c27b02d378d49fa7235671ad35e7e21ca14dab39c74c88.png
# agregar una leyenda (usa las etiquetas de plt.scatter)
plt.legend()
No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
<matplotlib.legend.Legend at 0x7f8fa0bffc70>
_images/e01ff64d10ffc2275ed7b3831244b22a9222649122b67dd5c14325fa89245f16.png
# agregue la leyenda a loc = 4 (la esquina inferior derecha), también elimina el marco y agrega un título
plt.legend(loc=4, frameon=False, title='Legenda')
No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
<matplotlib.legend.Legend at 0x7f8fa0ea0f70>
_images/26b55d820f3dcb7eec5b9558a532b67bc7b4cba955563e1d33b690b284eda484.png
# obtener hijos de los ejes actuales (la leyenda es el penúltimo elemento de esta lista)
plt.gca().get_children()
[<matplotlib.spines.Spine at 0x7f8fa10042b0>,
 <matplotlib.spines.Spine at 0x7f8fa10043a0>,
 <matplotlib.spines.Spine at 0x7f8fa1004490>,
 <matplotlib.spines.Spine at 0x7f8fa1004580>,
 <matplotlib.axis.XAxis at 0x7f8fa10042e0>,
 <matplotlib.axis.YAxis at 0x7f8fa10049d0>,
 Text(0.5, 1.0, ''),
 Text(0.0, 1.0, ''),
 Text(1.0, 1.0, ''),
 <matplotlib.patches.Rectangle at 0x7f8fa1014be0>]
_images/e90d8f2c9f70eecb88a02eac39b631f0c6b659a1fe7234099703577c13a60cca.png

3.2. Gráficos de linea#

import numpy as np

linear_data = np.array([1,2,3,4,5,6,7,8])
exponential_data = linear_data**2

plt.figure()
# graficar los datos lineales y los datos exponenciales
plt.plot(linear_data, '-o', exponential_data, '-o')
[<matplotlib.lines.Line2D at 0x7f8fa129cd00>,
 <matplotlib.lines.Line2D at 0x7f8fa129cd90>]
_images/280580b1b13fceac4c97acffff5d69e356b855d17595707294805a22a0d1bcaa.png
# graficar otra serie con una línea roja discontinua
plt.plot([22,44,55], '--r')
[<matplotlib.lines.Line2D at 0x7f8fa131eee0>]
_images/b40c3433588925abd143feed410b79661de1a42f88c16af4f0e4b48ebb3b92eb.png
plt.xlabel('Algún conjunto de datos')
plt.ylabel('Otro conjunto de datos')
plt.title('Un título')
# agregue una leyenda con entradas de leyenda (porque no teníamos etiquetas cuando graficamos la serie de datos)
plt.legend(['Línea base', 'Compentencia', 'Nosotros'])
<matplotlib.legend.Legend at 0x7f8fa137af70>
_images/8c3ae7019d8d5039278b3449c2d1b38d4d98a91d10a385bcafbd768306424806.png
# llenar el área entre los datos lineales y los datos exponenciales
plt.gca().fill_between(range(len(linear_data)), 
                       linear_data, exponential_data, 
                       facecolor='blue', 
                       alpha=0.25)
<matplotlib.collections.PolyCollection at 0x7f8fa137a9a0>
_images/a48fd36568fda5e4336094666d697af597634d7f4803c22494902a26f2b05cbe.png

¡Intentemos trabajar con fechas!

plt.figure()

observation_dates = np.arange('2017-01-01', '2017-01-09', dtype='datetime64[D]')

plt.plot(observation_dates, linear_data, '-o',  observation_dates, exponential_data, '-o')
[<matplotlib.lines.Line2D at 0x7f8fa1920ee0>,
 <matplotlib.lines.Line2D at 0x7f8fa17a3d90>]
_images/d4b320b2bd6d4b5ec9b6f34e681af4a74a7809dff3ba9abfeee89498b846f289.png

Intentemos usar pandas

import pandas as pd
plt.figure()
observation_dates = np.arange('2017-01-01', '2017-01-09', dtype='datetime64[D]')
observation_dates = list(map(pd.to_datetime, observation_dates)) #convertir el map en una lista
plt.plot(observation_dates, linear_data, '-o',  observation_dates, exponential_data, '-o')
[<matplotlib.lines.Line2D at 0x7f8fa28e6fd0>,
 <matplotlib.lines.Line2D at 0x7f8fa2922880>]
_images/d4b320b2bd6d4b5ec9b6f34e681af4a74a7809dff3ba9abfeee89498b846f289.png
x = plt.gca().xaxis

# rotar las etiquetas del eje x
for item in x.get_ticklabels():
    item.set_rotation(45)
_images/ec30f3d75eb8fccd2ed45957a8693d6e62a9271683e9dbf541bcedf4667ad680.png
# ajustar el subplot para que el texto no se salga de la imagen
plt.subplots_adjust(bottom=0.25)
<Figure size 640x480 with 0 Axes>
ax = plt.gca()
ax.set_xlabel('Fecha')
ax.set_ylabel('Unidades')
ax.set_title('Rendimiento Exponencial vs. Lineal')
Text(0.5, 1.0, 'Rendimiento Exponencial vs. Lineal')
_images/cfaa14e3b87dfd9245f37a110c54a86dee247dde9881c60c1d1fc34c9f9e51aa.png
# you can add mathematical expressions in any text element
ax.set_title("Rendimiento Exponential ($x^2$) vs. Linear ($x$)")
Text(0.5, 1.0, 'Rendimiento Exponential ($x^2$) vs. Linear ($x$)')

3.3. Gráficos de barras#

plt.figure()
xvals = range(len(linear_data))
plt.bar(xvals, linear_data, width = 0.3)
<BarContainer object of 8 artists>
_images/5e33109eec49bb24e39a33f2e55354edf1db85cc31facae8db60e6f78b73fa31.png
new_xvals = []

# graficar otro conjunto de barras, ajustando los nuevos "xvals" para compensar el primer conjunto de barras graficados
for item in xvals:
    new_xvals.append(item+0.3)

plt.bar(new_xvals, exponential_data, width = 0.3 ,color='red')
<BarContainer object of 8 artists>
_images/13a931de7cc15a50cc9913c4c2da7d1bc0e586d9e63f804c0cbae9037a8a2d19.png
from random import randint
linear_err = [randint(0,15) for x in range(len(linear_data))] 

# Esto graficará un nuevo conjunto de barras con barras de error utilizando la lista de valores de error aleatorios.
plt.bar(xvals, linear_data, width = 0.3, yerr=linear_err)
<BarContainer object of 8 artists>
_images/bfde95b8423957082566bc4b339e2b0f51958cdd919aaec9775f1a76e4f9e3fe.png
# También son posibles gráficos de barras apiladas
plt.figure()
xvals = range(len(linear_data))
plt.bar(xvals, linear_data, width = 0.3, color='b')
plt.bar(xvals, exponential_data, width = 0.3, bottom=linear_data, color='r')
<BarContainer object of 8 artists>
_images/97164f59c15fa689b7db85818ca82f8bec4d55024318c7c492eb5af17d98aae8.png
# o usar "barh" para gráficos de barras horizontales
plt.figure()
xvals = range(len(linear_data))
plt.barh(xvals, linear_data, height = 0.3, color='b')
plt.barh(xvals, exponential_data, height = 0.3, left=linear_data, color='r')
<BarContainer object of 8 artists>
_images/fc68ba8858df83194a3ee67254586dc87c6f70958a984ae21c37927590dba58d.png

3.4. Subplots#

import matplotlib.pyplot as plt
import numpy as np

#plt.subplot?
plt.figure()
# el subplot con 1 fila, 2 columnas y el eje actual es el primer eje del subplot
plt.subplot(1, 2, 1)

linear_data = np.array([1,2,3,4,5,6,7,8])

plt.plot(linear_data, '-o')
[<matplotlib.lines.Line2D at 0x7f8fa35a5c10>]
_images/96dc2ac5c4fe0a9b76be977324f5c96c7ff19f351b7e2de5c62513e7b19a426b.png
exponential_data = linear_data**2 

# el subplot con 1 fila, 2 columnas, y el eje actual es el segundo eje del subplot
plt.subplot(1, 2, 2)
plt.plot(exponential_data, '-o')
[<matplotlib.lines.Line2D at 0x7f8fa3617d30>]
_images/88bca04c52ea0d7511b0e36deb36b4a4a6c9340ce0eaf1ce915cd225aefcd16b.png
# graficar datos exponenciales en el primer eje
plt.subplot(1, 2, 1)
plt.plot(exponential_data, '-x')
[<matplotlib.lines.Line2D at 0x7f8fa36de2e0>]
_images/9317f2edacc850bb42854d1c59ee9c3f06da9e29b3d2d646874564cfa7cb5032.png
plt.figure()
ax1 = plt.subplot(1, 2, 1)
plt.plot(linear_data, '-o')
# pasamos sharey = ax1 para asegurarse de que los dos subplots compartan el mismo eje y
ax2 = plt.subplot(1, 2, 2, sharey=ax1)
plt.plot(exponential_data, '-x')
[<matplotlib.lines.Line2D at 0x7f8fa3896250>]
_images/a47a9abe9882165835bbd8b0d7b75456053387535d25836afd8b504db18d7780.png
plt.figure()
# el lado derecho es una sintaxis abreviada equivalente
plt.subplot(1,2,1) == plt.subplot(121)
True
_images/e6dab32129f517c38eaabee126b782203ad35aa1e9c276101415aea8093e179a.png
# creamos un grid 3x3 de subplots
fig, ((ax1,ax2,ax3), (ax4,ax5,ax6), (ax7,ax8,ax9)) = plt.subplots(3, 3, sharex=True, sharey=True)
# graficamos linear_data en el quinto eje del subplot
ax5.plot(linear_data, '-')
[<matplotlib.lines.Line2D at 0x7f8fa363cc10>]
_images/bbbf752c28d5e615b79ec2dc267e0cc20b1edb960664ffa4dea0ee2d889cf01d.png

3.5. Histogramas#

# creamos un grid 2x2 de subplots
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True)
axs = [ax1,ax2,ax3,ax4]
import random 
random.seed(30)
# obtenemos muestras de n = 10, 100, 1000, y 10000 de uns distribución normal y graficamos los histogramas
for n in range(0,len(axs)):
    sample_size = 10**(n+1)
    sample = np.random.normal(loc=0.0, scale=1.0, size=sample_size)
    axs[n].hist(sample)
    axs[n].set_title('n={}'.format(sample_size))
_images/27e5bf5c164ac25ba02c06365d6b3863c2bf3d9798c5d0bf9058d80fedf0fd30.png
# repetimos con el numero de bins en 100
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True)
axs = [ax1,ax2,ax3,ax4]

for n in range(0,len(axs)):
    sample_size = 10**(n+1)
    sample = np.random.normal(loc=0.0, scale=1.0, size=sample_size)
    axs[n].hist(sample, bins=100)
    axs[n].set_title('n={}'.format(sample_size))
_images/b97ab5755ab6777602112eafde8d34ea9c168c86e4437d874284ff7f87d3ac8c.png
plt.figure()
Y = np.random.normal(loc=0.0, scale=1.0, size=10000)
X = np.random.random(size=10000)
plt.scatter(X,Y)
<matplotlib.collections.PathCollection at 0x7f8fa529ff70>
_images/c2298e74483b0dca0d54f5aec8563e0db03535131ac74318b4aa69f923a452ed.png
# usamos gridspec para dividir la figura en subplots
import matplotlib.gridspec as gridspec

plt.figure()
gspec = gridspec.GridSpec(3, 3)

top_histogram = plt.subplot(gspec[0, 1:])
side_histogram = plt.subplot(gspec[1:, 0])
lower_right = plt.subplot(gspec[1:, 1:])
_images/f214e4f5fb6526ef9ad7d93c9a370f0b65de6582e83cf54445fb579aceaae09d.png
Y = np.random.normal(loc=0.0, scale=1.0, size=10000)
X = np.random.random(size=10000)
lower_right.scatter(X, Y)
top_histogram.hist(X, bins=100)
s = side_histogram.hist(Y, bins=100, orientation='horizontal')
# limpieamos los histogramas  y graficamos los plots normados
top_histogram.clear()
top_histogram.hist(X, bins=100, density=True)
side_histogram.clear()
side_histogram.hist(Y, bins=100, orientation='horizontal', density=True)
# flip the side histogram's x axis
side_histogram.invert_xaxis()

3.6. Boxplots#

import pandas as pd
normal_sample = np.random.normal(loc=0.0, scale=1.0, size=10000)
random_sample = np.random.random(size=10000)
gamma_sample = np.random.gamma(2, size=10000)

df = pd.DataFrame({'normal': normal_sample, 
                   'random': random_sample, 
                   'gamma': gamma_sample})
df.describe()
normal random gamma
count 10000.000000 10000.000000 10000.000000
mean -0.008903 0.502291 1.994247
std 0.989420 0.287763 1.413379
min -3.504499 0.000110 0.031634
25% -0.679220 0.255157 0.962466
50% -0.001904 0.500954 1.664964
75% 0.664013 0.752779 2.693740
max 3.751151 0.999946 16.731397
plt.figure()
# crear un diagrama de caja de los datos normales, note el ";" al final
plt.boxplot(df['normal']);
_images/3991583440ee0063cdbac13101fbbe1f3de5582e52937b528fffcd7d4ff22c3d.png
# limpiamos la figura
plt.clf()
# graficamos diagramas de caja para las tres columnas de df
plt.boxplot([ df['normal'], df['random'], df['gamma'] ]);
_images/7aa829f37c236e7d5900f4c4d81a06c33c79a917516d32f02e05800a36ac8481.png
plt.figure()
plt.hist(df['gamma'], bins=100);
_images/2a9d304a1b3c6c22d113a7df5df2b04583dddd98afaa3a7e9dbde787f5cbe817.png
import mpl_toolkits.axes_grid1.inset_locator as mpl_il

plt.figure()
plt.boxplot([ df['normal'], df['random'], df['gamma'] ])
# superponer el eje encima de otro
ax2 = mpl_il.inset_axes(plt.gca(), width='60%', height='40%', loc=2)
ax2.hist(df['gamma'], bins=100)
ax2.margins(x=0.5)
_images/3c2353798646fc6adf06b91af5c802ced2278de9b1ced264721adf5fa2fd2043.png
# cambiar las marcas del eje y para ax2 al lado derecho
ax2.yaxis.tick_right()
# si no se pasa el argumento `whis`, el boxplot tiene por default to mostrar 1.5*interquartile (IQR) con outliers
plt.figure()
plt.boxplot([ df['normal'], df['random'], df['gamma'] ] );
_images/7aa829f37c236e7d5900f4c4d81a06c33c79a917516d32f02e05800a36ac8481.png

3.7. Heatmaps#

plt.figure()

Y = np.random.normal(loc=0.0, scale=1.0, size=10000)
X = np.random.random(size=10000)
plt.hist2d(X, Y, bins=25);
_images/4e90e6c95785f4d60e5c786d4bb3d774286eae093ac29a2489d99d57fad9a741.png
plt.figure()
plt.hist2d(X, Y, bins=100);
_images/77f3b4d0cfd3d4397e982d3b2126ab5f898cf8b1b1e4a3a3ce53425cd2239f1b.png
# añadimos la leyenda de colores
#plt.colorbar()

3.8. Visualización con Pandas#

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# consulte los estilos predefinidos proporcionados.
plt.style.available
['Solarize_Light2',
 '_classic_test_patch',
 '_mpl-gallery',
 '_mpl-gallery-nogrid',
 'bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn-v0_8',
 'seaborn-v0_8-bright',
 'seaborn-v0_8-colorblind',
 'seaborn-v0_8-dark',
 'seaborn-v0_8-dark-palette',
 'seaborn-v0_8-darkgrid',
 'seaborn-v0_8-deep',
 'seaborn-v0_8-muted',
 'seaborn-v0_8-notebook',
 'seaborn-v0_8-paper',
 'seaborn-v0_8-pastel',
 'seaborn-v0_8-poster',
 'seaborn-v0_8-talk',
 'seaborn-v0_8-ticks',
 'seaborn-v0_8-white',
 'seaborn-v0_8-whitegrid',
 'tableau-colorblind10']
# usamos el estilo 'seaborn-colorblind'
plt.style.use('seaborn-colorblind')
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/style/core.py:137, in use(style)
    136 try:
--> 137     style = _rc_params_in_file(style)
    138 except OSError as err:

File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/__init__.py:866, in _rc_params_in_file(fname, transform, fail_on_error)
    865 rc_temp = {}
--> 866 with _open_file_or_url(fname) as fd:
    867     try:

File ~/opt/anaconda3/lib/python3.9/contextlib.py:119, in _GeneratorContextManager.__enter__(self)
    118 try:
--> 119     return next(self.gen)
    120 except StopIteration:

File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/__init__.py:843, in _open_file_or_url(fname)
    842 fname = os.path.expanduser(fname)
--> 843 with open(fname, encoding='utf-8') as f:
    844     yield f

FileNotFoundError: [Errno 2] No such file or directory: 'seaborn-colorblind'

The above exception was the direct cause of the following exception:

OSError                                   Traceback (most recent call last)
Cell In[59], line 2
      1 # usamos el estilo 'seaborn-colorblind'
----> 2 plt.style.use('seaborn-colorblind')

File ~/opt/anaconda3/lib/python3.9/site-packages/matplotlib/style/core.py:139, in use(style)
    137         style = _rc_params_in_file(style)
    138     except OSError as err:
--> 139         raise OSError(
    140             f"{style!r} is not a valid package style, path of style "
    141             f"file, URL of style file, or library style name (library "
    142             f"styles are listed in `style.available`)") from err
    143 filtered = {}
    144 for k in style:  # don't trigger RcParams.__getitem__('backend')

OSError: 'seaborn-colorblind' is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)

3.8.1. DataFrame.plot#

np.random.seed(123)

df = pd.DataFrame({'A': np.random.randn(365).cumsum(0), 
                   'B': np.random.randn(365).cumsum(0) + 20,
                   'C': np.random.randn(365).cumsum(0) - 20}, 
                  index=pd.date_range('1/1/2017', periods=365))
df.head()
A B C
2017-01-01 -1.085631 20.059291 -20.230904
2017-01-02 -0.088285 21.803332 -16.659325
2017-01-03 0.194693 20.835588 -17.055481
2017-01-04 -1.311601 21.255156 -17.093802
2017-01-05 -1.890202 21.462083 -19.518638

Podemos seleccionar qué gráfico queremos usar pasándolo al parámetro ‘kind’.

df.plot('A','B', kind = 'scatter');

También puede elegir el tipo de figura utilizando los métodos DataFrame.plot.kind en lugar de proporcionar el argumento kind.

kind :

  • 'line' : line plot (default)

  • 'bar' : vertical bar plot

  • 'barh' : horizontal bar plot

  • 'hist' : histogram

  • 'box' : boxplot

  • 'kde' : Kernel Density Estimation plot

  • 'density' : same as ‘kde’

  • 'area' : area plot

  • 'pie' : pie plot

  • 'scatter' : scatter plot

  • 'hexbin' : hexbin plot

# crear un diagrama de dispersión de las columnas 'A' y 'C', cambiando el color (c) y el tamaño (s) según la columna 'B'
df.plot.scatter('A', 'C', c='B', s=df['B'], colormap='viridis');
ax = df.plot.scatter('A', 'C', c='B', s=df['B'], colormap='viridis')
ax.set_aspect('equal')
df.plot.box();
df.plot.hist(alpha=0.7);

Los gráficos de estimación de densidad con kernel son útiles para derivar una función continua suave a partir de una muestra determinada.

df.plot.kde();

3.8.2. pandas.tools.plotting#

#import os as os
#os.chdir("C:/Users/VICTOR/Documents/AnalyticsPython/Data")
iris = pd.read_csv('Data/iris.csv')
iris.head()
SepalLength SepalWidth PetalLength PetalWidth Name
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
pd.plotting.scatter_matrix(iris);
plt.figure()
#pd.tools.plotting.parallel_coordinates(iris, 'Name');
pd.plotting.parallel_coordinates(iris, 'Name');

3.9. Seaborn#

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(1234)

v1 = pd.Series(np.random.normal(0,10,1000), name='v1')
v2 = pd.Series(2*v1 + np.random.normal(60,15,1000), name='v2')
plt.figure()
plt.hist(v1, alpha=0.7, bins=np.arange(-50,150,5), label='v1');
plt.hist(v2, alpha=0.7, bins=np.arange(-50,150,5), label='v2');
plt.legend();
# graficar la estimación de la densidad del kernel sobre un gráfico de barras apilado
plt.figure()
plt.hist([v1, v2], histtype='barstacked', density=True);
v3 = np.concatenate((v1,v2))
sns.kdeplot(v3);
v3.shape
(2000,)
plt.figure()
# podemos pasar argumentos  para cada componente individual del gráfico
df_aux = pd.DataFrame({'V3':v3})
sns.displot(df_aux,kde = True,stat = 'density')
<seaborn.axisgrid.FacetGrid at 0x7fc721c59820>
sns.jointplot(x=v1,y=v2, alpha=0.4);
grid = sns.jointplot(x=v1,y=v2, alpha=0.4);
grid.ax_joint.set_aspect('equal')
sns.jointplot(x=v1,y=v2, kind='hex');
# establecer el estilo seaborn para todas las siguientes figuras
sns.set_style('white')

sns.jointplot(x=v1,y=v2, kind='kde', space=0);
iris = pd.read_csv('Data/iris.csv')
iris.head()
SepalLength SepalWidth PetalLength PetalWidth Name
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
sns.pairplot(iris, hue='Name', diag_kind='kde', height=2);
plt.figure(figsize=(8,6))
plt.subplot(121)
kk = 4
sns.swarmplot(x='Name', y='PetalLength', data=iris,s = kk);
plt.subplot(122)
sns.violinplot(x='Name', y='PetalLength', data=iris,s = kk);

3.10. Tips#

3.10.1. Creando gráficos#

Figure

Operador

Descripción

fig = plt.figures()

un contenedor que contiene todos los elementos del gráfico

Axes

Operador

Descripción

fig.add_axes()

Inicia un subplot

a = fig.add_subplot(222)

Un subplot es un AXES en un grid que tiene sistema fila-columna

fig, b = plt.subplots(nrows=3, nclos=2)

Agrega un subplot

ax = plt.subplots(2, 2)

Crea el subplot

3.10.2. Graficando#

Datos 1D

Operador

Descripción

lines = plt.plot(x,y)

Grafica datos conectados por líneas

plt.scatter(x,y)

Crea un gráfico de dispersión

plt.bar(xvalue, data , width, color…)

Gráfico de barras simple vertical

plt.barh(yvalue, data, width, color…)

Gráfico de barras simple horizontal

plt.hist(x, y)

Grafica un hisrograma

plt.boxplot(x,y)

Gráfico de caja y bigotes

plt.violinplot(x, y)

Gráfico de violín

ax.fill(x, y, color=’lightblue’)

Llena el área debajo de la curva

ax.fill_between(x,y,color=’yellow’)

Llena el área entre de la curva

Datos 2D

Operador

Descripción

fig, ax = plt.subplots()

im = ax.imshow(img, cmap, vmin…)

Mapa de colores con arrays RGB

Guardando gráficos

Operador

Descripción

plt.savefig(‘pic.png’)

Se guarda el gráfico

plt.savefig(‘transparentback.png’)

Se guarda el gráfico con fondo transparente

3.10.3. Personalización#

Color

Operador

Descripción

plt.plot(x, y, color=’lightblue’)

plt.plot(x, y, alpha = 0.4)

Se fija un color

plt.colorbar(mappable,

orientation=’horizontal’)

mappable: la Image, Contourset etc a los que aplica la barra de colores

Markers

Operador

Descripción

plt.plot(x, y, marker=’o’)

Se agrega el tipo de punto

plt.scatter(x, y, marker=’.’)

Se agrega un ‘.’ en cada punto

Líneas

Operador

Descripción

plt.plot(x, y, linewidth=2)

Se fija el ancho de la línea

plt.plot(x, y, ls=’solid’)

Se fija el estilo de la línea

plt.plot(x, y, ls=’–‘)

Se fija el estilo de la línea

plt.plot(x,y,'--', x**2, y**2, '-.')

Las lineas son '--' y '_.'

plt.setp(lines,color=’red’,linewidth=2)

Fija las propiedades de las lineas

Texto

Operador

Descripción

plt.text(1, 1,’Example

Text’,style=’italic’)

Ubica el texto en las coordenadas 1/1

ax.annotate(‘some annotation’, xy=(10, 10))

Ubica el texto s con coordenadas xy

plt.title(r'$delta_i=20$', fontsize=10)

Expresiones matemáticas

Límites

Operador

Descripción

plt.xlim(0, 7)

Fija el eje-x para mostrar 0-7

other = array.copy()

Crea una copia del array

plt.ylim(-0.5, 9)

Fija el eje-y para mostrar -0.5-9

ax.set(xlim=[0, 7], ylim=[-0.5, 9])

ax.set_xlim(0, 7)

Fija los límites

plt.margins(x=1.0, y=1.0)

Fija los márgenes

plt.axis(‘equal’)

Fija el ratio del gráfico a 1

Leyendas/etiquetas

Operador

Descripción

plt.title(‘just a title’)

Fija el título del gráfico

plt.xlabel(‘x-axis’)

Fija la etiqueta del eje x

plt.ylabel(‘y-axis’)

Fija la etiqueta del eje y

ax.set(title=’axis’, ylabel=’Y-Axis’, xlabel=’X-Axis’)

Fija el título y las etiquetas de los ejes

ax.legend(loc=’best’)

No traslapa los elementos del gráfico

Ticks

Operador

Descripción

plt.xticks(x, labels, rotation=’vertical’)

Fija los ticks

ax.xaxis.set(ticks=range(1,5), ticklabels=[3,100,-12,”foo”])

Fija los ticks de x

ax.tick_params(axis=’y’, direction=’inout’, length=10)

Hace que los ticks sean más largos dentro y fuera