View
213
Download
0
Category
Preview:
Citation preview
CURSOS DE VERANO 2014
TÍTULO DEL CURSO
TÍTULO PONENCIA
NOMBRE PROFESOR
APROXIMACIÓN PRÁCTICA A LA CIENCIA DE DATOS Y BIG
DATA: HERRAMIENTAS KNIME, R, HADOOP Y MAHOUT
Visualización de datos con R
Francisco Charte Ojeda
Epígrafe o tema Contenidos
Gráficos básicos
Histogramas
Agrupación de gráficos
Almacenamiento de gráficos
Introducción a ggplot2
Otras posibilidades gráficas
>> graficosBasicos.R <<
>> graficosAvanzados.R <<
Epígrafe o tema Gráficos básicos ► Nube de puntos
plot(iris$Petal.Length, iris$Petal.Width, col = iris$Species, pch = 19, xlab = 'Longitud del pétalo', ylab = 'Ancho del pétalo')
title(main = 'IRIS', sub = 'Pétalos según specie', col.main = 'blue', col.sub = 'blue')
legend("bottomright", legend = levels(iris$Species), col = unique(iris$Species), ncol = 3, pch = 19, bty = "n")
1 2 3 4 5 6 7
0.5
1.0
1.5
2.0
2.5
Longitud del pétalo
An
ch
o d
el p
éta
lo
setosa versicolor virginicasetosa versicolor virginica
IRIS
Exploración de los pétalos según especie
Epígrafe o tema Gráficos básicos ► Gráfico de cajas (bigotes)
plot(iris$Petal.Length ~ iris$Species)
setosa versicolor virginica
12
34
56
7
iris$Species
iris
$P
eta
l.L
en
gth
setosa versicolor virginica1
23
45
67
IRIS
Análisis de pétalo por familia
Lo
ng
itu
d p
éta
lo
boxplot(iris$Petal.Length ~ iris$Species)
title(main = 'IRIS', ylab = 'Longitud pétalo', sub = 'Análisis de pétalo por familia')
Epígrafe o tema Gráficos básicos ► Líneas
Fri Mon Sat Sun Tue
21
24
27
30
33
36
39
42
45
48
Precio de cierre según día
Día
Pre
cio
fin
al
$€
plot(meanPricesUS, type = "o", axes = F, ann = F, col = "blue")
lines(meanPricesEUR,type="o",col="red")
axis(1, at=1:length(meanPricesUS), lab = names(meanPricesUS))
axis(2, at = 3*0:rango[2], las = 1)
title(main='Precio de cierre según día', xlab = 'Día', ylab = 'Precio final')
legend("bottomright", c("$","€"), col = c("blue","red"), lty = c(1,1))
Epígrafe o tema Gráficos básicos ► Barras
barplot(sapply( endPricePerDay$EUR, length), col = rainbow(7))
title(main = 'Operaciones por día')
Fri Mon Sat Sun Thu Tue Wed
02
04
06
08
01
00
Número de operaciones por dia
Epígrafe o tema Gráficos básicos ► Barras
Accu
racy
Pre
cis
ion
RAkEL-BRLP-J48IBLR-MLHOMERCLRBR-J48
0.0 0.1 0.2 0.3 0.4 0.5 0.6
accuracy <- aggregate( Accuracy ~ Algorithm, results, mean) precision <- aggregate( Precision ~ Algorithm, results, mean) valMedios <- matrix(c( precision$Precision, accuracy$Accuracy), nrow=6, ncol=2) rownames(valMedios) <- accuracy$Algorithm
barplot(valMedios, beside=T, horiz=T, col = cm.colors(6), legend.text=T, names.arg = c('Accuracy', 'Precision'))
Epígrafe o tema Gráficos básicos ► Sectores (circular o tarta)
177
178
54
18
119
37239
36
Productos por categoría
Antique/Art/CraftAutomotive
BooksBusiness/Industrial
Clothing/AccessoriesCoins/Stamps
CollectiblesComputer
opPorCategoria <- aggregate( ClosePrice ~ Category, ebay,length)[1:8,]
colores <- topo.colors(length( opPorCategoria$Category))
pie(opPorCategoria$ClosePrice, labels=opPorCategoria$ClosePrice, col=colores, main='Productos por categoría')
legend("bottom", opPorCategoria$Category, cex=0.6, fill=colores, ncol=4)
Epígrafe o tema Histogramas ► Frecuencia
Elevación del terreno
Metros
Fre
qu
en
cy
2000 2500 3000 3500 4000
05
00
00
10
00
00
15
00
00 hist(covertype$elevation,
breaks = 12, col = rainbow(12), main = 'Elevación del terreno', xlab = 'Metros')
Epígrafe o tema Histogramas ► Frecuencia
Elevación del terreno
Metros
Fre
qu
en
cy
2000 2500 3000 3500
05
00
01
00
00
15
00
02
00
00 histograma <- hist(covertype$elevation,
breaks = 100)
plot(histograma, col = ifelse(histograma$breaks < 2500, 'green', ifelse(histograma$breaks > 3000, "red", "blue")), main = 'Elevación del terreno', xlab = 'Metros')
Epígrafe o tema Histogramas ► Densidad
plot(density(rnorm(1000), adjust = 3), col = 'blue', lwd = 4, main = 'Distribución normal', xlab = 'Valores')
-4 -2 0 2 4
0.0
00
.10
0.2
00
.30
Distribución normal
Valores
De
nsity
Epígrafe o tema Histogramas ► Histograma + Densidad
Elevación del terreno
Metros
De
nsity
2000 2500 3000 3500
0.0
00
00
.00
05
0.0
01
00
.00
15
hist(covertype$elevation, prob = T, col = "grey", main = 'Elevación del terreno', xlab = 'Metros')
lines(density(covertype$elevation, adjust = 5), col = 'black', lwd = 3)
Epígrafe o tema Histogramas ► Histogramas de objetos compuestos
hist(iris)
Sepal.Length
Fre
quency
4 5 6 7 8
05
10
20
30
n:150 m:0Sepal.Width
Fre
quency
2.0 3.0 4.0
020
40
60
n:150 m:0Petal.Length
Fre
quency
1 3 5 70
10
20
30
40
50
n:150 m:0
Petal.Width
Fre
quency
0.0 1.0 2.0
010
20
30
40
50
n:150 m:0
virginica
versicolor
setosa
30 70
Frequencies for Species
Epígrafe o tema Agrupación de gráficos ► Proyecciones 2D
Sepal.Length
2.0 3.0 4.0 0.5 1.5 2.5
4.5
6.0
7.5
2.0
3.0
4.0
Sepal.Width
Petal.Length1
35
7
4.5 6.0 7.5
0.5
1.5
2.5
1 3 5 7
Petal.Width
plot(iris[ ,1:4], col = iris$Species)
Epígrafe o tema Agrupación de gráficos ► mfrow/mfcol
4.5 5.5 6.5 7.5
2.0
3.0
4.0
iris$Sepal.Lengt
iris
$S
epal.W
idth
1 2 3 4 5 6 7
0.5
1.5
2.5
iris$Petal.Lengt
iris
$P
eta
l.W
idth
4.5 5.5 6.5 7.5
0.5
1.5
2.5
iris$Sepal.Lengt
iris
$P
eta
l.W
idth
1 2 3 4 5 6 7
2.0
3.0
4.0
iris$Petal.Lengt
iris
$S
epal.W
idth
prev <- par(mfrow=c(2,2)) plot(iris$Sepal.Length, iris$Sepal.Width, col=iris$Species) plot(iris$Petal.Length, iris$Petal.Width, col=iris$Species) plot(iris$Sepal.Length, iris$Petal.Width, col=iris$Species) plot(iris$Petal.Length, iris$Sepal.Width, col=iris$Species) par(prev)
Epígrafe o tema Agrupación de gráficos ► layout
# 2x2 con 3 gráficas layout(matrix(c(1,1,2,3), 2, 2, byrow = T)) # Gráfico 1 ocupa 1ª fila hist(ebay$Duration, main='Duración subasta', xlab='Días') # Gráfico 2 en 1ª col de 2ª fila barplot(sapply( endPricePerDay$EUR, length), col = rainbow(7), horiz=T,las=1) # Gráfico 3 en 2ª col de 2ª fila plot(meanPricesEUR, type="o")
Duración subasta
Días
Fre
quency
2 4 6 8 10
0400
800
FriMonSat
SunThuTue
Wed
0 20 40 60 80
Operaciones por día Precio cierre por día
Día
Euro
s
Fri
Mon
Sat
Sun
Thu
Tue
Wed
212427303336394245
Epígrafe o tema Almacenamiento de gráficos ► Funciones de R
Generan un archivo en el formato adecuado
Mapas de bits: png(), bmp(), jpeg(), tiff()
Vectoriales: win.metafile()
Otros: postscript(), pdf()
Parámetros generales
filename, width, height, pointsize, quality
Desactivación de la salida al archivo
dev.off()
Ejemplo
pdf('Subastas.pdf', width=8.3, height=11.7) # A4 hist(iris) # Una gráfica por página dev.off() # Cerrar PDF
Epígrafe o tema Almacenamiento de gráficos ► Animaciones
Funciones en paquete animations
saveGIF(), saveVideo(), saveHTML(), saveLatex()
Ejemplo de uso
saveGIF({
for(lim in seq(-3.14,3.14,by=0.1))
curve(sin, from=lim, to=lim + 9.42)
}, movie.name="animacion.gif", interval=0.2, ani.width=640, ani.height=640)
Epígrafe o tema Introducción a ggplot2
Ventajas sobre los gráficos básicos
Estética mejorada y altamente personalizable
Mayor flexibilidad y control
Más facilidad para generar gráficos con datos complejos
Recursos necesarios
Instalar paquete ggplot2
Documentación en http://docs.ggplot2.org/current
ggplot2: Elegant Graphics for Data Analysis
Ejemplos disponibles en http://ggplot2.org/book
Epígrafe o tema Introducción a ggplot2 ► Nube de puntos
2.0
2.5
3.0
3.5
4.0
4.5
5 6 7 8
Sepal.Length
Se
pa
l.W
idth
Species
setosa
versicolor
virginica
Petal.Width
0.5
1.0
1.5
2.0
2.5
qplot(Sepal.Length, Sepal.Width, data=iris, colour=Species, size=Petal.Width)
Epígrafe o tema Introducción a ggplot2 ► Líneas
5
6
7
8
2 4 6
Petal.Length
Se
pa
l.L
en
gth
Species
setosa
versicolor
virginica
qplot(Petal.Length, Sepal.Length, data=iris, color=Species) + geom_line()
Epígrafe o tema Introducción a ggplot2 ► Nube de puntos + Curvas de regresión
qplot(Petal.Length, Petal.Width, data=iris, color=Species) + geom_point() + geom_smooth()
Epígrafe o tema
0.000
0.001
0.002
0.003
2000 2500 3000 3500
elevation
de
nsity
wilderness_area
1
2
3
4
Introducción a ggplot2 ► Densidad
qplot(elevation, data=covertype, geom="density", fill=wilderness_area)
Epígrafe o tema Introducción a ggplot2 ► Facets
# Representar 5 variables qplot(ClosePrice, sellerRating, data=ebay[ebay$endDay %in% c('Wed','Thu','Fri') & ebay$currency != 'US',], facets=currency ~ endDay, color=Duration)
Epígrafe o tema Introducción a ggplot2 ► Facets
Fri Mon Sat
Sun Thu Tue
0
5000
10000
15000
0
5000
10000
15000
EUR GBP US EUR GBP US EUR GBP US
currency
Clo
seP
rice
currency
EUR
GBP
US
qplot(currency, ClosePrice, data=ebay[ebay$endDay != 'Wed',], fill=currency) + geom_bar(stat='identity') + facet_wrap(~endDay)
Epígrafe o tema Otras posibilidades gráficas
Medio centenar de paquetes gráficos sólo en CRAN
http://cran.r-project.org/web/views/Graphics.html
Interacción con los gráficos desde navegador web
Shiny: http://shiny.rstudio.com/
Multitud de tipos de gráficas alternativas
circos, radar, 3D, etc.
Gráficos no generados a partir de datos
TurtleGraphics
Epígrafe o tema Otras posibilidades gráficas ► radarchart (paquete fmsb)
1
1
1 1
1
emotions
corel
scene yeast
ebay
Epígrafe o tema Otras posibilidades gráficas ► scatterplot3d
Helix
-1.0 -0.5 0.0 0.5 1.0-10
-5
0
5
10
-1.0
-0.5
0.0
0.5
1.0
x
y
z
Epígrafe o tema Otras posibilidades gráficas ► TurtleGraphics
turtle_do({ for(j in 1:45) { for(i in 1:6) { turtle_forward(20) turtle_right(360/6) } turtle_right(360/45) }})
Recommended