7.1 Gráficos básicos
7.1.1 Gráficas de puntos
plot(iris$Sepal.Length)

plot(iris$Sepal.Length, iris$Sepal.Width)

plot(iris$Sepal.Length, iris$Sepal.Width, col = iris$Species, pch = 19)

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 = 'Exploración de los pétalos según especie', col.main = 'blue', col.sub = 'blue')
legend("bottomright", legend = levels(iris$Species), col = unique(iris$Species), ncol = 3, pch = 19, bty = "n")

7.1.2 Gráficas de cajas
plot(iris$Petal.Length ~ iris$Species)

boxplot(Petal.Length ~ Species, data = iris, notch = T, range = 1.25, width = c(1.0, 2.0, 2.0))
title(main = 'IRIS', ylab = 'Longitud pétalo', sub = 'Análisis de pétalo por familia')

7.1.3 Gráficas de líneas
# Separar por moneda
# install.packages("XLConnect")
library('XLConnect')
ebay <- readWorksheetFromFile('eBayAuctions.xls',sheet=1)
ebayPerCurr <- split(ebay, ebay$currency)
# En cada moneda, separar por dias
endPricePerDay <- lapply(ebayPerCurr, function(curr) split(curr$ClosePrice, curr$endDay))
# Precio medio de cierre para moneda
meanPricesUS <- sapply(endPricePerDay$US, mean)
meanPricesEUR <- sapply(endPricePerDay$EUR, mean)
meanPricesUS[is.na(meanPricesUS)] <- mean(meanPricesUS, na.rm=T)
# Obtener el rango a representar
rango <- range(meanPricesUS, meanPricesEUR)
meanPricesEUR
## Fri Mon Sat Sun Thu Tue Wed
## 20.47578 43.07168 45.63229 40.85346 25.75291 23.29060 31.47493
meanPricesUS
## Fri Mon Sat Sun Tue
## 48.21471 36.83621 39.28396 42.27805 31.95483
rango
## [1] 20.47578 48.21471
# Inicializa gráfico con la primera línea y sin ejes
plot(meanPricesUS, type = "o", axes = F, ann = F,
col = "blue", ylim = rango)
# Añade la segunda línea
lines(meanPricesEUR, type = "o", col = "red")
# Colocamos los ejes
axis(1, at = 1:length(meanPricesUS), lab = names(meanPricesUS))
axis(2, at = 3*0:rango[2], las = 1)
# Y finalmente los títulos y leyendas
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))

7.1.4 Gráficas de barras
barplot(sapply(endPricePerDay$EUR, length), col = rainbow(7))
title(main='Número de operaciones por dı́a')

results <- read.csv('results.csv')
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'))

7.1.5 Gráficas de sectores (circular)
# Obtener número de operaciones por categorı́a
opPorCategoria <- aggregate(
ClosePrice ~ Category,
ebay, length)[1:8,] # Tomar solo las primeras 8 filas
colores <- topo.colors(length(opPorCategoria$Category))
pie(opPorCategoria$ClosePrice,
labels = opPorCategoria$ClosePrice,
col = colores, main='Productos por categorı́a')
legend("bottom", "Categorı́a", opPorCategoria$Category,
cex = 0.6, fill = colores, ncol = 4)

7.2 Histogramas
7.2.1 Histograma básico
# install.packages("RWeka")
library(RWeka)
covertype <- read.arff('covertype.arff')
hist(covertype$elevation, main = 'Elevación del terreno', xlab = 'Metros')

# El parámetro plot = FALSE desactiva la visualización
histograma <- hist(covertype$elevation, plot = F)
str(histograma, strict.width = 'wrap')
## List of 6
## $ breaks : int [1:22] 1800 1900 2000 2100 2200 2300 2400 2500 2600 2700 ...
## $ counts : int [1:21] 93 1180 3456 5255 7222 11161 12837 22350 30864 46331 ...
## $ density : num [1:21] 1.60e-06 2.03e-05 5.95e-05 9.04e-05 1.24e-04 ...
## $ mids : num [1:21] 1850 1950 2050 2150 2250 2350 2450 2550 2650 2750 ...
## $ xname : chr "covertype$elevation"
## $ equidist: logi TRUE
## - attr(*, "class")= chr "histogram"
7.2.2 Personalización de divisiones y colores
plot(histograma, col = ifelse(histograma$breaks < 2500, 'green', ifelse(histograma$breaks > 3000, "red", "blue")), main='Elevación del terreno', xlab='Metros')

7.2.3 Curva de densidad
plot(density(covertype$elevation, adjust = 5), col = 'black', lwd = 3)

hist(covertype$elevation, prob = T, col = "grey", main = 'Elevación del terreno', xlab = 'Metros')
lines(density(covertype$elevation, adjust = 5), col = 'black', lwd = 3)

7.2.4 Histogramas de objetos complejos
# install.packages("Hmisc")
library(Hmisc)
# hist(iris) necesita entrada numérica
hist.data.frame(iris) # acepta data frame como entrada

7.3 Cómo agrupar varios gráficos
7.3.1 Gráficas cruzadas por atributos
plot(iris[ ,1:4], col = iris$Species)

# install.packages("ellipse")
library(ellipse)
plotcorr(cor(iris[ ,1:4]), col = heat.colors(10))

7.3.2 Composiciones de múltiples gráficas
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)
# Establecemos la distribución de las gráficas
layout(matrix(c(1,1,2,3), 2, 2, byrow = T))
# Un histograma
hist(ebay$Duration, main = 'Duración subasta', xlab = 'Dı́as')
# Una gráfica de barras
barplot(sapply(endPricePerDay$EUR, length),
col = rainbow(7),horiz=T,las=1)
title(main='Operaciones por dı́a')
# Y una gráfica de lı́neas
plot(meanPricesEUR, type = "o", axes = F, ann = F)
title(main = 'Precio cierre por dı́a',ylab = 'Euros', xlab = 'Dı́a')
axis(1, at = 1:length(meanPricesEUR),
lab = names(meanPricesEUR), las = 2)
axis(2, at = 3*0:rango[2], las = 1)

# Restablecemos la configuración previa
par(prev)
7.4 Cómo guardar los graficos
# Abrimos el archivo PDF y establecemos las dimensiones
pdf('AnalisisSubastas.pdf', width = 8.3, height = 11.7)
# Introducimos un histograma
hist(ebay$Duration, main='Duración subasta',xlab = 'Dı́as')
# Una gráfica de barras
barplot(sapply(endPricePerDay$EUR, length),
col = rainbow(7), horiz = T, las = 1)
title(main='Operaciones por dı́a')
# Y una gráfica de lı́neas
plot(meanPricesEUR, type = "o", axes = F, ann = F)
title(main = 'Precio cierre por dı́a',
ylab = 'Euros', xlab = 'Dı́a')
axis(1, at = 1:length(meanPricesEUR),
lab = names(meanPricesEUR), las = 2)
axis(2, at = 3*0:rango[2], las = 1)
# Cerramos el archivo
dev.off()
## png
## 2
7.4.1 Animaciones
#install.packages("animation")
#library(animation)
#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.1, ani.width = 640, ani.height = 640)