Sei sulla pagina 1di 49

Computação II - Python

Aula 8 - Matplotlib e Scipy

João C. P. da Silva
Carla A. D. M. Delgado
Dept. Ciência da Computação - UFRJ

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 1 / 44


Matplotlib - Básico
Queremos plotar a função seno para 200 pontos no intervalo [0, 10)

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 2 / 44


Matplotlib - Básico
Queremos plotar a função seno para 200 pontos no intervalo [0, 10)
1 import m a t p l o t l i b . p y p l o t as p l t # bi bliot e ca matplotlib . pyplot
2
3 f i g , ax = p l t . s u b p l o t s ( )

fig, ax = plt.subplots(): retorna um par de elemento, onde:


fig é uma instância de figura (”quadro em branco”)
ax é um frame no qual você pode plotar algo

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 2 / 44


Matplotlib - Básico
Queremos plotar a função seno para 200 pontos no intervalo [0, 10)
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )

Criamos os arrays x e y usando o np.linspace.

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 3 / 44


Matplotlib - Básico
Queremos plotar a função seno para 200 pontos no intervalo [0, 10)
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )

Criamos os arrays x e y usando o np.linspace.


Agora, queremos plotar o gráfico:
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )
7
8 ax . p l o t ( x , y , ’ b−’ , l i n e w i d t h =5) # p l o t a n d o o g r a f i c o

x e y são as coordenadas dos pontos



b − ‘ define a cor azul (b) e o estilo da linha (-)
linewidth define a largura da linha
http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 3 / 44
Matplotlib - Básico
Queremos plotar a função seno para 200 pontos no intervalo [0, 10)
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )
7
8 ax . p l o t ( x , y , ’ b−’ , l i n e w i d t h =5) # p l o t a n d o o g r a f i c o

x e y são as coordenadas dos pontos



b − ‘ define a cor azul (b) e o estilo da linha (-)
linewidth define a largura da linha

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 4 / 44


Matplotlib - Básico
Podemos plotar mais de uma função em um mesmo gráfico:
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )
7 z = np . c o s ( x )
8
9 ax . p l o t ( x , y , ’ b−’ , l i n e w i d t h =5) # p l o t a n d o o s e n o
10 ax . p l o t ( x , z , ’ r−’ , l i n e w i d t h =3) # p l o t a n d o o c o s e n o

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 5 / 44


Matplotlib - Básico
Formatos - Linhas e Pontos

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 6 / 44


Matplotlib - Básico

Formatos - Cores

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 7 / 44


Matplotlib - Básico
Podemos querer mostrar uma figura ou salvá-la em um arquivo:
show(): mostra a figura plotada
savefig(...): salva a figura em um arquivo
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )
7
8 ax . p l o t ( x , y , ’ b−’ , l i n e w i d t h =5) # p l o t a n d o o g r a f i c o
9
10 p l t . show ( ) # m ostrando o g r a f i c o

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 8 / 44


Matplotlib - Básico
Podemos querer mostrar uma figura ou salvá-la em um arquivo:
show(): mostra a figura plotada
savefig(...): salva a figura em um arquivo
1 i m p o r t numpy a s np # b i b l i o t e c a Numpy
2 import m a t p l o t l i b . p y p l o t as p l t # b i b l i o t e c a m a t p l o t l i b . p y p l o t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 0 , 200) # 200 p o n t o s do i n t e r v a l o [ 0 , 1 0 )
6 y = np . s i n ( x )
7
8 ax . p l o t ( x , y , ’ b−’ , l i n e w i d t h =5) # p l o t a n d o o g r a f i c o
9
10 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / f i g u r a . png ’ ) # m ostrando o g r a f i c o

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 9 / 44


Matplotlib - Básico

Exercı́cio:
Teste outras cores e formatos para o exemplo da função seno. Altere
também o número de pontos.

Plote as funções seno e coseno no mesmo gráfico, em cores e


formatos diferentes.

Plote as funções trigonométricas coseno (cos) e tangente (tan) de


forma que as cores e formatos de cada plot sejam distintas. Varie
também o número de pontos usados na geração dos gráficos. Salve
seus gráficos em arquivo.

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 10 / 44


Matplotlib - Básico - Rótulos e Legendas

1 f i g , ax = p l t . s u b p l o t s ( f i g s i z e =(10 , 5) ) # podemos mudar o tamanho do g r a f i c o g e r a d o


2 x = np . l i n s p a c e ( 0 , 1 0 , 200)
3 y = np . s i n ( x )
4 ax . p l o t ( x , y , ’ r−’ , l i n e w i d t h =2, l a b e l = ’ s i n e f u n c t i o n ’ , a l p h a =0. 6) # l a b e l da f i g u r a
5
6 p l t . x l a b e l ( ’ Eixo X ’ ) # r o t u l o do e i x o X
7 p l t . y l a b e l ( ’ Eixo Y ’ ) # r o t u l o do e i x o Y
8
9 ax . l e g e n d ( ) # i n c l u i a legenda
10 p l t . show ( )

figsize: permite definir o tamanho da figura


label: acrescenta um rótulo para a função
plt.xlabel e plt.ylabel: rótulo dos eixos x e y
alpha: grau de ”transparência” da linha
(quanto menor, mais transparente)
legend: inclui a legenda na figura

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 11 / 44


Matplotlib - Básico - Rótulos e Legendas
1 f i g , ax = p l t . s u b p l o t s ( f i g s i z e =(10 , 5) )
2
3 x = np . l i n s p a c e ( 0 , 1 0 , 200)
4 y = np . s i n ( x )
5
6 ax . p l o t ( x , y , ’ r−’ , l i n e w i d t h =2, l a b e l = ’ s i n e f u n c t i o n ’ , a l p h a =0. 6)
7
8 ax . l e g e n d ( l o c= ’ u p p e r c e n t e r ’ ) # mudamos a q u i
9 p l t . show ( )

Podemos mudar a posição da legenda na figura:

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 12 / 44


Matplotlib - Básico - Rótulos e Legendas
1 f i g , ax = p l t . s u b p l o t s ( f i g s i z e =(10 , 5) )
2
3 x = np . l i n s p a c e ( 0 , 1 0 , 200)
4 y = np . s i n ( x )
5
6 ax . p l o t ( x , y , ’ r−’ , l i n e w i d t h =2, l a b e l = ’ s i n e f u n c t i o n ’ , a l p h a =0. 6)
7
8 ax . l e g e n d ( l o c= ’ u p p e r c e n t e r ’ ) # mudamos a q u i
9 p l t . show ( )

String Código
‘best’ 0
‘upper right’ 1
‘upper left’ 2
‘lower left’ 3
‘lower,right’ 4
‘right’ 5
‘center left’ 6
‘center right’ 7
‘lower center’ 8
‘upper,center’ 9
‘center’ 10
http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 13 / 44
Matplotlib - Básico - Rótulos e Legendas
1 f i g , ax = p l t . s u b p l o t s ( f i g s i z e =(10 , 5) )
2
3 x = np . l i n s p a c e ( 0 , 1 0 , 200)
4 y = np . s i n ( x )
5
6 ax . p l o t ( x , y , ’ r−’ , l i n e w i d t h =2, l a b e l =r ’ $y=\ s i n ( x ) $ ’ , a l p h a =0. 6) # mudamos a q u i
7
8 ax . l e g e n d ( l o c= ’ u p p e r c e n t e r ’ )
9
10 p l t . show ( )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 14 / 44


Matplotlib - Básico - Rótulos e Legendas
1 f i g , ax = p l t . s u b p l o t s ( )
2 x = np . l i n s p a c e ( 0 , 1 0 , 200)
3 y = np . s i n ( x )
4
5 ax . p l o t ( x , y , ’ r−’ , l i n e w i d t h =2, l a b e l =r ’ $y=\ s i n ( x ) $ ’ , a l p h a =0. 6)
6 ax . l e g e n d ( l o c= ’ u p p e r c e n t e r ’ )
7
8 ax . s e t y t i c k s ([ −1 , 0 , 1 ] ) # acrescentamos esta li n h a
9 ax . s e t t i t l e ( ’ T e s t p l o t ’ ) # acrescentamos esta li n h a
10
11 p l t . show ( )

ax.set yticks(): elementos


que formam o eixo y

ax.set title(): tı́tulo da


figura

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 15 / 44


Matplotlib - Básico

Exercı́cios:
Crie um array com números do intervalo [0., 5.) (step = 0.2), e plote
as funções
f (x) = x (formato: traços vermelhos)
g (x) = x 2 (quadrados azuis)
h(x) = x 3 (triângulos verdes).

Fazer duas versões, uma com eles separados e outra em um só gráfico.
Inclua a legenda para as funções e salve as imagens em arquivos.

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 16 / 44


Matplotlib - Básico

Exercı́cio
Considerando que você está usando 100 pontos no intervalo [−10, 10],
plote as funções seno e coseno para gerar o seguinte gráfico:

O tamanho da figura é 10 x 5. Salve seu gráfico em arquivo.

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 17 / 44


Matplotlib - Básico

Exercı́cio
Plote o gráfico abaixo. Use 100 pontos e o tamanho da figura de 10 x 8. Salve seu gráfico em arquivo.

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 18 / 44


Matplotlib - Funções Descontı́nuas

Considere a seguinte função:


(
x if x < 0.5
y=
1+x if x ≥ 0.5

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 19 / 44


Matplotlib - Funções Descontı́nuas

Considere a seguinte função:


(
x if x < 0.5
y=
1+x if x ≥ 0.5

Podemos plotar a função usando o seguinte código:


1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3 f i g , ax = p l t . s u b p l o t s ( )
4 x=np . l i n s p a c e ( 0 , 1 , 1 0 0 ) # array x
5 y=np . z e r o s ( 1 0 0 ) # a r r a y y , i n i c i a l i z a d o com z e r o
6
7 for i i n range (100) : # d e f i n i n d o a funcao
8 i f x [ i ] <0.5:
9 y[ i ] = x[ i ]
10 else :
11 y [ i ]=1+x [ i ]
12 ax . p l o t ( x , y , ’−o ’ )
13 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / d e s c o n t 1 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 19 / 44


Matplotlib - Funções Descontı́nuas

Considere a seguinte função:


(
x if x < 0.5
y=
1+x if x ≥ 0.5

Podemos simplificar a geração da função usando o fato que estamos


trabalhando com arrays:
1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x=np . l i n s p a c e ( 0 , 1 , 1 0 0 ) # array x
6 y=np . z e r o s ( 1 0 0 ) # a r r a y y , i n i c i a l i z a d o com z e r o
7
8 y [ x < 0. 5] = x [ x < 0. 5] # form a a l t e r n a t i v a p a r a d e f i n i r a f u n c a o
9 y [ x >=0.5] = 1 + x [ x >=0.5]
10
11 ax . p l o t ( x , y , ’−o ’ )
12 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / d e s c o n t 2 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 20 / 44


Matplotlib - Funções Descontı́nuas

Nos dois programas obtemos o mesmo gráfico:

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 21 / 44


Matplotlib - Funções Descontı́nuas

Nos dois programas obtemos o mesmo gráfico:

Por que isto ocorreu?

Como resolver este problema?

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 21 / 44


Matplotlib - Funções Descontı́nuas
Vamos usar np.nan para quebrar a linha em múltiplos seguimentos
1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 , 1 0 0 )
6 y = np . z e r o s ( 1 0 0 )
7
8 y [ x < 0.5] = x [ x < 0.5]
9 y [ x >= 0 . 5 ] = 1 + x [ x >= 0 . 5 ]
10
11 pos = np . whe re ( np . a b s ( np . d i f f ( y ) ) >= 0 . 5 ) [ 0 ] # l i n h a nova
12
13 x [ pos ] = np . nan # l i n h a nova
14 y [ pos ] = np . nan # l i n h a nova
15
16 ax . p l o t ( x , y , ’−o ’ )
17 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / d e s c o n t 3 . png ’ )

np.diff(y) : diferença entre os elementos de um array (out[n] = y[n+1]-y[n])

np.abs : retorna o valor absoluto do seu argumento

np.where(condicao[,x,y]) : retorna elementos (de x ou y ) em um ndarray ou


tupla de ndarrays, dependendo de condicao
http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 22 / 44
Matplotlib - Funções Descontı́nuas

Vamos usar np.nan para quebrar a linha em múltiplos seguimentos

1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 , 1 0 0 )
6 y = np . z e r o s ( 1 0 0 )
7
8 y [ x < 0.5] = x [ x < 0.5]
9 y [ x >= 0 . 5 ] = 1 + x [ x >= 0 . 5 ]
10
11 pos = np . whe re ( np . a b s ( np . d i f f ( y ) ) >= 0 . 5 ) [ 0 ] # l i n h a nova
12
13 x [ pos ] = np . nan # l i n h a nova
14 y [ pos ] = np . nan # l i n h a nova
15
16 ax . p l o t ( x , y , ’−o ’ )
17 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / d e s c o n t 3 . png ’ )

x[pos] = np.nan e y[pos] = np.nan : substitui o ponto onde ocorre a


descontinuidade por np.nan

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 23 / 44


Matplotlib - Funções Descontı́nuas

Vamos usar np.nan para quebrar a linha em múltiplos seguimentos

1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3
4 f i g , ax = p l t . s u b p l o t s ( )
5 x = np . l i n s p a c e ( 0 , 1 , 1 0 0 )
6 y = np . z e r o s ( 1 0 0 )
7
8 y [ x < 0.5] = x [ x < 0.5]
9 y [ x >= 0 . 5 ] = 1 + x [ x >= 0 . 5 ]
10
11 pos = np . whe re ( np . a b s ( np . d i f f ( y ) ) >= 0 . 5 ) [ 0 ] # l i n h a nova
12
13 x [ pos ] = np . nan # l i n h a nova
14 y [ pos ] = np . nan # l i n h a nova
15
16 ax . p l o t ( x , y , ’−o ’ )
17 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / d e s c o n t 3 . png ’ )

x[pos] = np.nan e y[pos] = np.nan : substitui o ponto onde ocorre a


descontinuidade por np.nan

Note que o ponto foi perdido!

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 23 / 44


Matplotlib - Funções Descontı́nuas
Vamos usar np.nan para quebrar a linha em múltiplos seguimentos
1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3 f i g , ax = p l t . s u b p l o t s ( )
4 x=np . l i n s p a c e ( 0 , 1 , 1 0 0 )
5 y=np . z e r o s ( 1 0 0 )
6 y [ x < 0. 5] = x [ x < 0. 5]
7 y [ x >=0.5] = 1 + x [ x >=0.5]
8
9 pos = np . whe re ( np . a b s ( np . d i f f ( y ) ) >= 0 . 5 ) [ 0 ] + 1 # acrescentamos + 1 a posicao
10 x = np . i n s e r t ( x , pos , np . nan ) # a c r e s c e n t a m o s ponto de q u e b r a
11 y = np . i n s e r t ( y , pos , np . nan ) # a c r e s c e n t a m o s ponto de q u e b r a
12 ax . p l o t ( x , y , ’−o ’ )
13 p l t . s a v e f i g ( ’ /home/ j o a o / De sk top / d e s c o n t 3 . png ’ )

x = np.insert(x, pos, np.nan) e y = np.insert(y, pos, np.nan): acrescentamos um novo


ponto no array ao invés de substituı́-lo.

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 24 / 44


Matplotlib - Funções Descontı́nuas

Exercı́cio: Faça uma função que gere o seguinte gráfico (use 200 pontos e
valores de x ∈ [−10, 10]):

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 25 / 44


Scipy

SciPy é uma biblioteca construı́da sobre NumPy, aumentando o poder de manipulação e


visualização de dados, tornando este ambiente competitivo com outros sistemas como
MATLAB, Octave e SciLab.
Ela fornece uma série de ferramentas de programação cientı́fica:

álgebra linear (scipy.linalg)

integração numérica (scipy.integrate)

interpolação (scipy.interpolate)

otimização (scipy.optimize)

estatı́stica (scipy.stats)

outras

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 26 / 44


Scipy - Estatı́stica - scipy.stats

Este pacote oferece:


Variáveis aleatórias: densidade, distribuições, amostragem aleatória, etc.

procedimentos de estimativa

testes estatı́sticos

outros

Veja a lista completa de funções deste módulo utilizando o comando help no


Spider ou consultando a documentação na internet
(https://docs.scipy.org/doc/scipy/reference/stats.html).

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 27 / 44


Scipy - Estatı́stica - scipy.stats
Considere que queremos usar a função Beta. Podemos usar a função do Numpy:

https://docs.scipy.org/doc/numpy-
1.13.0/reference/generated/numpy.random.beta.html
http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 28 / 44
Scipy - Estatı́stica - scipy.stats
Ou a função do Scipy.

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#scipy.stats.beta

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 29 / 44


Scipy - Estatı́stica - scipy.stats
O Scipy nos oferece muito mais recursos:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#scipy.stats.beta
http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 30 / 44
Scipy - Estatı́stica - scipy.stats
norm: variável aleatória contı́nua normal
Função de Densidade da Distribuição Normal
1 x−µ )2
e− 2 ( σ
f (x) = √
σ 2π
onde µ é a média e σ o desvio padrão.
No scipy, ela é definida para a µ = 1 (parâmetro loc) e σ = 0 (parâmetro scale) por
default:
x2
e− 2
f (x) = √

1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3 from s c i p y . s t a t s i m p o r t norm # v a r i a v e l a l e a t o r i a c onti nua normal
4
5
6 f i g , ax = p l t . s u b p l o t s ( )
7
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 y = norm . p d f ( x )
10
11 ax . p l o t ( x , y , l i n e w i d t h =2)
12
13 p l t . s a v e f i g ( ’ norm al 1 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 31 / 44


Scipy - Estatı́stica - scipy.stats
1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3 from s c i p y . s t a t s i m p o r t norm # v a r i a v e l a l e a t o r i a c onti nua normal
4
5
6 f i g , ax = p l t . s u b p l o t s ( )
7
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 y = norm . p d f ( x )
10
11 ax . p l o t ( x , y , l i n e w i d t h =2)
12
13 p l t . s a v e f i g ( ’ norm al 1 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 32 / 44


Scipy - Estatı́stica - scipy.stats
1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3 from s c i p y . s t a t s i m p o r t norm # v a r i a v e l a l e a t o r i a c onti nua normal
4
5
6 f i g , ax = p l t . s u b p l o t s ( )
7
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 y = norm . p d f ( x , l o c =1, s c a l e =2) # m e di a = 1 e d e s v i o = 2
10
11 ax . p l o t ( x , y , l i n e w i d t h =2)
12
13 p l t . s a v e f i g ( ’ norm al 2 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 33 / 44


Scipy - Estatı́stica - scipy.stats

uniform: variável aleatória contı́nua uniforme

Função de Densidade da Distribuição Uniforme


(
1
b−a
para a ≤ x ≤ b
f (n) =
0 caso contrário

No scipy, o intervalo [a, b] é definido por [loc, loc + scale], onde por default loc = 0 e
scale = 1:

1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3 from s c i p y . s t a t s i m p o r t u n i f o r m # v a r i a v e l a l e a t o r i a continua uniforme
4
5
6 f i g , ax = p l t . s u b p l o t s ( )
7
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 y = uniform . pdf ( x ) # de nsidade uniforme
10
11 ax . p l o t ( x , y , l i n e w i d t h =2)
12
13 p l t . s a v e f i g ( ’ u n i f o r m e 1 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 34 / 44


Scipy - Estatı́stica - scipy.stats
1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3 from s c i p y . s t a t s i m p o r t u n i f o r m # v a r i a v e l a l e a t o r i a continua uniforme
4
5
6 f i g , ax = p l t . s u b p l o t s ( )
7
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 y = uniform . pdf ( x ) # de nsidade uniforme
10
11 ax . p l o t ( x , y , l i n e w i d t h =2)
12
13 p l t . s a v e f i g ( ’ u n i f o r m e 1 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 35 / 44


Scipy - Estatı́stica - scipy.stats
1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3 from s c i p y . s t a t s i m p o r t u n i f o r m # v a r i a v e l a l e a t o r i a continua uniforme
4
5
6 f i g , ax = p l t . s u b p l o t s ( )
7
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 y = u n i f o r m . p d f ( x , l o c =−1, s c a l e =2) # mudando o i n t e r v a l o
10
11 ax . p l o t ( x , y , l i n e w i d t h =2)
12
13 p l t . s a v e f i g ( ’ u n i f o r m e 2 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 36 / 44


Scipy - Estatı́stica - scipy.stats
1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3
4 from s c i p y . s t a t s i m p o r t norm # 1
5 from random i m p o r t u n i f o r m # 2
6
7 f i g , ax = p l t . s u b p l o t s ( )
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 f o r i i n range ( 3) : # 3
10 m, s = u n i f o r m ( −1, 1) , u n i f o r m ( 1 , 2)
11 y = norm . p d f ( x , l o c=m, s c a l e=s ) # 4
12 c u r r e n t l a b e l = r ’ $\mu = { 0 : . 2 f }$ ’ . f o r m a t (m)
13 ax . p l o t ( x , y , l i n e w i d t h =2, a l p h a =0. 6 , l a b e l =c u r r e n t l a b e l )
14 ax . l e g e n d ( )
15 p l t . show ( )

1 norm: Variável aleatória contı́nua normal


2 uniform: sorteia um número float dentro de um dado intervalo. CUIDADO: não
é do scipy, é do random!
3 Em cada passada do loop, um gráfico é construı́do:
Sorteia uma média m ∈ [−1., 1.] e desvio padrão s ∈ [1., 2.]
norm.pdf: função densidade de probabilidade com média m (loc=m) e
desvio padrão s (scale=s)
http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 37 / 44
Scipy - Estatı́stica - scipy.stats
1 import m a t p l o t l i b . p y p l o t as p l t
2 i m p o r t numpy a s np
3
4 from s c i p y . s t a t s i m p o r t norm # 1
5 from random i m p o r t u n i f o r m # 2
6
7 f i g , ax = p l t . s u b p l o t s ( )
8 x = np . l i n s p a c e ( −4, 4 , 150)
9 f o r i i n range ( 3) : # 3
10 m, s = u n i f o r m ( −1, 1) , u n i f o r m ( 1 , 2)
11 y = norm . p d f ( x , l o c=m, s c a l e=s ) # 4
12 c u r r e n t l a b e l = r ’ $\mu = { 0 : . 2 f }$ ’ . f o r m a t (m)
13 ax . p l o t ( x , y , l i n e w i d t h =2, a l p h a =0. 6 , l a b e l =c u r r e n t l a b e l )
14 ax . l e g e n d ( )
15 p l t . show ( )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 38 / 44


Matplotlib - Histogramas
1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3
4 num e roP ontos = 100000 # numero de p o n t o s
5 num e roBi ns = 20 # numero de c o l u n a s
6
7 x = np . random . r a n d n ( num e roP ontos ) # eixo X
8 y = . 4 ∗ x + np . random . r a n d n ( num e roP ontos ) + 5 # eixo Y
9
10 f i g , a x s = p l t . s u b p l o t s ( f i g s i z e =( 10 , 5) )
11
12 a x s . h i s t ( x , b i n s=num e roBi ns ) # histograma
13
14 p l t . s a v e f i g ( ’ t e s t e 0 . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 39 / 44


Matplotlib - Histogramas
1 i m p o r t numpy a s np
2 import m a t p l o t l i b . p y p l o t as p l t
3
4 num e roP ontos = 100000
5 num e roBi ns = 20
6
7 x = np . random . r a n d n ( num e roP ontos ) # eixo X
8 y = . 4 ∗ x + np . random . r a n d n ( num e roP ontos ) + 5 # eixo Y
9
10 f i g , a x s = p l t . s u b p l o t s ( 1 , 2 , f i g s i z e =( 20 , 10) , s h a r e y =True ) # d o i s h i s t o g . l a d o a l a d o com
mesmo e i x o Y ( s h a r e y )
11
12 a x s [ 0 ] . h i s t ( x , b i n s=num e roBi ns ) # primeiro histograma
13 a x s [ 1 ] . h i s t ( y , b i n s =20 , f a c e c o l o r= ’ r ’ ) # se gundo h i s t o g r a m a , de c o r v e r m e l h a
14
15 p l t . s a v e f i g ( ’ t e s t e . png ’ )

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 40 / 44


Matplotlib - Galeria
A Matplotlib é uma biblioteca bastante poderosa. Existem inúmeros
modelos de gráficos que podem ser usados.
Veja em : https://matplotlib.org/gallery/index.html

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 41 / 44


Matplotlib - Referências

Quantecon: https://lectures.quantecon.org/py/matplotlib.html#the-
matlab-style-api

Matplotlib: https://matplotlib.org/users/pyplot tutorial.html

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 42 / 44


Autores
João C. P. da Silva Lattes

Carla Delgado Lattes

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 43 / 44


Computação II - Python
Aula 8 - Matplotlib e Scipy

João C. P. da Silva
Carla A. D. M. Delgado
Dept. Ciência da Computação - UFRJ

http://www.dcc.ufrj.br/˜pythonUFRJ/ Computação II - Python Aula 8 44 / 44

Potrebbero piacerti anche