Está en la página 1de 24

Gráficas en Python

Gráficas estadı́stica y minerı́a de datos con python

Miguel Cárdenas Montes

Centro de Investigaciones Energéticas Medioambientales y Tecnológicas,


Madrid, Spain
miguel.cardenas@ciemat.es

22-26 de Abril de 2013

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 1 / 24


Tabla de Contenidos

1 Objectivos

2 Introducción

3 Una Gráfica Básica

4 Histograma

5 Boxplot

6 Múltiples gráficas

7 Aumentando la Complejidad

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 2 / 24


Objectivos
Realización de gráficas y análisis simples.

Aspectos Técnicos
scipy
matplotlib
numpy

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 3 / 24


Introducción

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 4 / 24


Lo que los cientı́ficos necesitan

Manipular y procesar datos.


Visualizar resultados para entender qué se está haciendo.
Comunicar resultados: producir gráficas para publicaciones, informes,
presentaciones, etc.

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 5 / 24


Ladrillos

En Python existe una colección de herramientas que cubre la mayor


parte de las necesidades cientı́ficas.
Los tiempos de desarrollos disminuyen considerablemente.
Gran capacidad de reutilización y compartición de código existente.

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 6 / 24


Gráfica básica I

Grafica básica relacionando valores en coordenadas y abcisas.

25

import numpy as np
import pylab as pl 20

# Make an array of x values


x = [1, 2, 3, 4, 5] 15

# Make an array of y values for each x value


y = [1, 4, 9, 16, 25]
# use pylab to plot x and y 10

pl.plot(x, y)
# show the plot on the screen 5

pl.show()

0
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 7 / 24


Gráfica básica II: Puntos en vez de lı́nea.

25

import numpy as np
20
import pylab as pl
# Make an array of x values
x = [1, 2, 3, 4, 5] 15

# Make an array of y values for each x value


y = [1, 4, 9, 16, 25]
10
# use pylab to plot x and y as red circles
pl.plot(x, y, ’ro’)
# show the plot on the screen 5

pl.show()
0
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 8 / 24


Gráfica básica III: Colores

Indicador Color
b blue - azul
g green - verde
r reed - rojo
c cyan -
m magenta -
y yellow - amarillo
k black - negro
w white - blanco

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 9 / 24


Gráfica básica IV: Estilo de la lı́nea

Indicador Estilo
’-’ solid line style
’–’ dashed line style
’-.’ dash-dot line style
’:’ dotted line style
pl.plot(x, y, ’o’)
’.’ point marker
’s’ square marker
’p’ pentagon marker
’*’ star marker

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pl

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 10 / 24


Gráfica básica V: Enriqueciendo la gráfica

import numpy as np
import pylab as pl
# Make an array of x values 30
Plot of y vs. x

x = [1, 2, 3, 4, 5]
# Make an array of y values for each x value 25

y = [1, 4, 9, 16, 25]


# use pylab to plot x and y
20

pl.plot(x, y)
# give plot a title

y axis
15
pl.title(’Plot of y vs. x’)
# make axis labels
10
pl.xlabel(’x axis’)
pl.ylabel(’y axis’)
# set axis limits 5

pl.xlim(0.0, 7.0)
pl.ylim(0.0, 30.) 0
0 1 2 3 4 5 6 7
x axis
# show the plot on the screen
pl.show()

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 11 / 24


Gráfica básica VI: Más de un dibujo por gráfica

import numpy as np
import pylab as pl
# Make x, y arrays for each graph
x1 = [1, 2, 3, 4, 5] 30
Plot of y vs. x

y1 = [1, 4, 9, 16, 25]


x2 = [1, 2, 4, 6, 8] 25

y2 = [2, 4, 8, 12, 16]


# use pylab to plot x and y
20

pl.plot(x1, y1, ’r’)


pl.plot(x2, y2, ’g’)

y axis
15
# give plot a title
pl.title(’Plot of y vs. x’)
10
# make axis labels
pl.xlabel(’x axis’)
pl.ylabel(’y axis’) 5

# set axis limits


pl.xlim(0.0, 9.0) 0
0 1 2 3 4 5 6 7 8 9
x axis
pl.ylim(0.0, 30.)
# show the plot on the screen
pl.show()

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 12 / 24


Gráfica básica VII: Leyenda

import numpy as np
import pylab as pl
# Make x, y arrays for each graph
x1 = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25] 30
Plot of y vs. x

x2 = [1, 2, 4, 6, 8] red line

green circles
y2 = [2, 4, 8, 12, 16] 25

# use pylab to plot x and y : Give your plots names


plot1 = pl.plot(x1, y1, ’r’)
20

plot2 = pl.plot(x2, y2, ’go’)


# give plot a title

y axis
15
pl.title(’Plot of y vs. x’)
# make axis labels
10
pl.xlabel(’x axis’)
pl.ylabel(’y axis’)
# set axis limits 5

pl.xlim(0.0, 9.0)
pl.ylim(0.0, 30.) 0
0 1 2 3 4 5 6 7 8 9
x axis
# make legend
pl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)
# show the plot on the screen
pl.show()

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 13 / 24


Gráfica básica VIII: Leyenda

El primer parámetro es la lista


de dibujos.
El segundo es la lista de
etiquetas.
pl.legend((plot1, plot2), (label1, label2), best, numpoints=1)
El tercero es la posicion de las
etiquetas: ’upper right’, ’upper
left, ’center, ’lower left, ’lower
right, ’best’

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 14 / 24


Histograma I: uno simple

250
import numpy as np
import pylab as pl
# make an array of random numbers with 200
#a gaussian distribution with
# mean = 5.0
150
# rms = 3.0
# number of points = 1000
data = np.random.normal(5.0, 3.0, 1000) 100
# make a histogram of the data array
pl.hist(data)
50
# make plot labels
pl.xlabel(’data’)
pl.show() 0
5 0 5 10 15 20
data

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 15 / 24


Histograma II: variar el tamaño del bin


import numpy as np
300
import pylab as pl
# make an array of random numbers with
250
#a gaussian distribution with
# mean = 5.0
200
# rms = 3.0
# number of points = 1000
data = np.random.normal(5.0, 3.0, 1000) 150

# make a histogram of the data array


pl.hist(data) 100

bins = np.arange(-5., 16., 1.)


pl.hist(data, bins, histtype=’stepfilled’) 50
# make plot labels
pl.xlabel(’data’) 0
5 0 5 10 15
pl.show() data

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 16 / 24


Histograma II: semitransparente

pl.hist(data)
pl.hist(data, alpha=0.3)

pl.hist(data, bins, histtype=’stepfilled’)


pl.hist(data, bins, histtype=’stepfilled’, alpha=0.3)

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 17 / 24



Histograma III: Añadir textos

import numpy as np Histogram of IQ


0.030
import matplotlib.pyplot as plt
mu, sigma = 100, 15 0.025 = 100, = 15

x = mu + sigma * np.random.randn(10000)
# the histogram of the data
0.020
n, bins, patches = plt.hist(x, 50, normed=1, \

Probability
facecolor=’g’, alpha=0.75)
0.015
plt.xlabel(’Smarts’)
plt.ylabel(’Probability’)
0.010
plt.title(’Histogram of IQ’)
plt.text(60, .025, r’$\mu=100,\ \sigma=15$’)
plt.axis([40, 160, 0, 0.03]) 0.005
plt.grid(True)
plt.show() 0.00040 60 80 100 120 140 160
Smarts

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 18 / 24


Boxplot I

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 19 / 24



Boxplot II

20
import numpy as np
from pylab import * 15

#gaussian distributions
dataset_1 = np.random.normal(5.0, 3.0, 1000) 10

dataset_2 = np.random.normal(5.0, 5.0, 1000)


dataset_3 = np.random.normal(4.0, 1.0, 1000) 5

0
datos=[dataset_1, dataset_2, dataset_3]
xticks( arange(3), (’Dataset 1’, ’Dataset 2’, \
5

’Dataset 3’) )
10

boxplot(datos)
show() 15
Dataset 1 Dataset 2 Dataset 3

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 20 / 24



Múltiples gráficas I

import numpy as np 1.0

import matplotlib.pyplot as plt 0.8

0.6

0.4

0.2
def f(t): 0.0

return np.exp(-t) * np.cos(2*np.pi*t) 0.2

0.4

0.6

t1 = np.arange(0.0, 5.0, 0.1) 0.8


0 1 2 3 4 5

t2 = np.arange(0.0, 5.0, 0.02) 1.0

plt.figure(1) 0.5

plt.subplot(211)
plt.plot(t1, f(t1), ’bo’, t2, f(t2), ’k’) 0.0

plt.subplot(212) 0.5

plt.plot(t2, np.cos(2*np.pi*t2), ’r--’)


1.0
plt.show() 0 1 2 3 4 5

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 21 / 24


Aumentando la Complejidad I

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter

# the random data


x = np.random.randn(1000)
y = np.random.randn(1000)

nullfmt = NullFormatter() # no labels

# definitions for the axes


left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left+width+0.02

rect_scatter = [left, bottom, width, height]


rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 22 / 24


Aumentando la Complejidad II

# start with a rectangular Figure


plt.figure(1, figsize=(8,8))

axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)

# no labels
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)

# the scatter plot:


axScatter.scatter(x, y)

# now determine nice limits by hand:


binwidth = 0.25
xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth

axScatter.set_xlim( (-lim, lim) )


axScatter.set_ylim( (-lim, lim) )

bins = np.arange(-lim, lim + binwidth, binwidth)


axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation=’horizontal’)

axHistx.set_xlim( axScatter.get_xlim() )
axHisty.set_ylim( axScatter.get_ylim() )

plt.show()

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 23 / 24


Gracias

Gracias

¿Preguntas?

¿Más preguntas?

M. Cárdenas (CIEMAT) Gráficas 22-26 de Abril de 2013 24 / 24

También podría gustarte