Visualización con ggplot2
## Objetivos de Aprendizaje
- Comprender la gramática de gráficos de ggplot2
- Crear gráficos básicos
- Personalizar estética
- Facetas y capas de gráficos
- Guardar gráficos
## Introducción a ggplot2
### ¿Qué es ggplot2?
ggplot2 es un sistema para crear gráficos basado en la gramática de gráficos:
- **En capas** - Gráficos construidos desde componentes
- **Declarativo** - Especificas qué, no cómo
- **Extensible** - Fácil de personalizar
### Instalación
```r
install.packages("ggplot2")
library(ggplot2)
```
## Conceptos Básicos
### Componentes de un Gráfico
1. **Datos** - El dataframe
2. **Estéticas** - Mapeo de variables a propiedades visuales
3. **Geoms** - Objetos geométricos (puntos, líneas, barras)
4. **Stats** - Transformaciones estadísticas
5. **Scales** - Cómo las estética mapean a valores
6. **Facets** - Dividir en subgráficos
7. **Theme** - Estilo visual
### Plantilla Básica
```r
ggplot(data = ) +
(mapping = aes())
```
## Empezando
### Gráfico de Dispersión Simple
```r
# Crear datos
df <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(2, 4, 3, 5, 4)
)
# Gráfico de dispersión básico
ggplot(data = df, aes(x = x, y = y)) +
geom_point()
```
### Con Pipe
```r
df %>%
ggplot(aes(x = x, y = y)) +
geom_point()
```
## Mapeos Estéticos
### ¿Qué son las Estéticas?
Las estéticas conectan variables de datos a propiedades visuales:
- x, y - posición
- color - color de punto/línea
- size - tamaño de punto
- shape - forma de punto
- alpha - transparencia
### Mapeando Variables
```r
df <- data.frame(
x = 1:10,
y = 1:10,
grupo = rep(c("A", "B"), 5)
)
# Color por grupo
ggplot(df, aes(x = x, y = y, color = grupo)) +
geom_point()
# Tamaño por valor
ggplot(df, aes(x = x, y = y, size = x)) +
geom_point()
# Forma por grupo
ggplot(df, aes(x = x, y = y, shape = grupo)) +
geom_point()
```
### Establecer vs Mapear
```r
# Mapear: variable mapeada a estética
ggplot(df, aes(x = x, y = y, color = grupo)) +
geom_point()
# Establecer: valor fijo
ggplot(df, aes(x = x, y = y)) +
geom_point(color = "azul")
```
## Geoms Comunes
### geom_point()
```r
# Gráfico de dispersión
ggplot(df, aes(x = x, y = y)) +
geom_point()
# Con todas las estéticas
ggplot(df, aes(x = x, y = y, size = x, color = grupo)) +
geom_point(alpha = 0.7) # transparencia
```
### geom_line()
```r
# Gráfico de líneas
ggplot(df, aes(x = x, y = y)) +
geom_line()
# Línea + puntos
ggplot(df, aes(x = x, y = y)) +
geom_line() +
geom_point()
```
### geom_smooth()
```r
# Agregar línea suavizada
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_smooth()
# Sin intervalo de confianza
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_smooth(se = FALSE)
# Modelo lineal
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm")
```
### geom_bar()
```r
# Conteo de variable categórica
df <- data.frame(
categoria = c("A", "B", "C", "A", "B", "A")
)
ggplot(df, aes(x = categoria)) +
geom_bar()
# Desde datos resumidos
df <- data.frame(
categoria = c("A", "B", "C"),
conteo = c(30, 45, 25)
)
ggplot(df, aes(x = categoria, y = conteo)) +
geom_bar(stat = "identity")
```
### geom_histogram()
```r
# Histograma de variable continua
df <- data.frame(x = rnorm(1000))
ggplot(df, aes(x = x)) +
geom_histogram()
# Ajustar bins
ggplot(df, aes(x = x)) +
geom_histogram(bins = 30)
# Diferente relleno
ggplot(df, aes(x = x)) +
geom_histogram(fill = "steelblue", color = "white")
```
### geom_boxplot()
```r
# Boxplot
df <- data.frame(
grupo = rep(c("A", "B"), each = 50),
valor = c(rnorm(50, 5, 1), rnorm(50, 7, 1))
)
ggplot(df, aes(x = grupo, y = valor)) +
geom_boxplot()
# Horizontal
ggplot(df, aes(x = grupo, y = valor)) +
geom_boxplot() +
coord_flip()
```
### geom_violin()
```r
# Gráfico violín (forma de distribución)
ggplot(df, aes(x = grupo, y = valor)) +
geom_violin()
```
### geom_density()
```r
# Gráfico de densidad
ggplot(df, aes(x = valor)) +
geom_density()
# Relleno
ggplot(df, aes(x = valor, fill = grupo)) +
geom_density(alpha = 0.5) # semi-transparente
```
### geom_text()
```r
# Agregar etiquetas
ggplot(df, aes(x = x, y = y, label = grupo)) +
geom_text()
```
### geom_label()
```r
# Etiquetas con fondo
ggplot(df, aes(x = x, y = y, label = grupo)) +
geom_label()
```
## Escalas
### Escalas de Color
```r
# Colores manuales
ggplot(df, aes(x = x, y = y, color = grupo)) +
geom_point() +
scale_color_manual(values = c("rojo", "azul"))
# Gradiente
ggplot(df, aes(x = x, y = y, color = valor)) +
geom_point() +
scale_color_gradient(low = "azul", high = "rojo")
# Gradiente2 para divergente
ggplot(df, aes(x = x, y = y, color = valor)) +
geom_point() +
scale_color_gradient2(low = "azul", mid = "blanco", high = "rojo")
```
### Escalas de Tamaño
```r
# Tamaño manual
ggplot(df, aes(x = x, y = y, size = valor)) +
geom_point() +
scale_size(range = c(1, 10))
```
### Escalas de Ejes
```r
# Escala logarítmica
ggplot(df, aes(x = x, y = y)) +
geom_point() +
scale_y_log10()
# Marcas manuales
ggplot(df, aes(x = x, y = y)) +
geom_point() +
scale_y_continuous(breaks = seq(0, 100, 10))
```
## Etiquetas y Títulos
### labs()
```r
ggplot(df, aes(x = x, y = y)) +
geom_point() +
labs(
title = "Mi Título",
subtitle = "Subtítulo aquí",
x = "Etiqueta Eje X",
y = "Etiqueta Eje Y",
color = "Título de Leyenda",
caption = "Fuente de datos: ..."
)
```
### ggtitle()
```r
ggplot(df, aes(x = x, y = y)) +
geom_point() +
ggtitle("Título") +
xlab("X") +
ylab("Y")
```
## Temas
### Temas Incorporados
```r
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_minimal()
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_bw()
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_classic()
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_dark()
```
### Personalización de Temas
```r
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme(
panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "gray90"),
panel.grid.minor = element_line(color = "gray95"),
text = element_text(family = "sans", size = 12),
plot.title = element_text(hjust = 0.5, face = "bold")
)
```
## Facetas
### facet_wrap()
```r
# Envolver por una variable
df <- data.frame(
x = 1:20,
y = 1:20,
grupo = rep(c("A", "B", "C", "D"), 5)
)
ggplot(df, aes(x = x, y = y)) +
geom_point() +
facet_wrap(~grupo)
# Múltiples filas
ggplot(df, aes(x = x, y = y)) +
geom_point() +
facet_wrap(~grupo, nrow = 2)
```
### facet_grid()
```r
# Grid por dos variables
df <- data.frame(
x = 1:10,
y = 1:10,
grupo1 = rep(c("A", "B"), each = 10),
grupo2 = rep(c("X", "Y"), 10)
)
ggplot(df, aes(x = x, y = y)) +
geom_point() +
facet_grid(grupo1 ~ grupo2)
```
## Transformaciones Estadísticas
### Stats Incorporadas
```r
# Resúmenes estadísticos
ggplot(df, aes(x = x, y = y)) +
stat_summary()
# Boxplot con muescas
ggplot(df, aes(x = grupo, y = valor)) +
geom_boxplot(notch = TRUE)
```
## Ajustes de Posición
### Dodge, Stack, Fill
```r
# Gráfico de barras
df <- data.frame(
grupo = c("A", "A", "B", "B"),
tipo = c("X", "Y", "X", "Y"),
valor = c(10, 20, 15, 25)
)
# Lado a lado
ggplot(df, aes(x = grupo, y = valor, fill = tipo)) +
geom_bar(position = "dodge", stat = "identity")
# Apilado
ggplot(df, aes(x = grupo, y = valor, fill = tipo)) +
geom_bar(position = "stack", stat = "identity")
# Proporciones
ggplot(df, aes(x = grupo, y = valor, fill = tipo)) +
geom_bar(position = "fill", stat = "identity")
```
## Coordenadas
### coord_flip()
```r
# Barras horizontales
ggplot(df, aes(x = categoria, y = valor)) +
geom_bar(stat = "identity") +
coord_flip()
```
### coord_cartesian()
```r
# Zoom sin afectar datos
ggplot(df, aes(x = x, y = y)) +
geom_point() +
coord_cartesian(xlim = c(0, 50), ylim = c(0, 50))
```
## Guardar Gráficos
### ggsave()
```r
# Guardar último gráfico
ggsave("mi_grafico.png")
ggsave("mi_grafico.pdf")
# Gráfico específico
p <- ggplot(df, aes(x = x, y = y)) + geom_point()
ggsave("mi_grafico.png", p)
# Especificar tamaño y resolución
ggsave("mi_grafico.png", width = 10, height = 8, dpi = 300)
```
### Funciones de Exportación
```r
# PNG
png("grafico.png", width = 800, height = 600)
print(ggplot(df, aes(x = x, y = y)) + geom_point())
dev.off()
# PDF
pdf("grafico.pdf", width = 10, height = 8)
print(ggplot(df, aes(x = x, y = y)) + geom_point())
dev.off()
```
## Extensiones
### Extensiones Comunes
```r
# patchwork - combinar gráficos
install.packages("patchwork")
library(patchwork)
p1 <- ggplot(df, aes(x = x, y = y)) + geom_point()
p2 <- ggplot(df, aes(x = x)) + geom_histogram()
p1 + p2
# gganimate - animaciones
install.packages("gganimate")
library(gganimate)
```
## Resumen
- ggplot2 usa gramática de gráficos en capas
- Mapear datos a estéticas con `aes()`
- Usar funciones `geom_*` para diferentes tipos de gráficos
- Personalizar con `scale_*`, `theme()`, `labs()`
- `facet_wrap()` y `facet_grid()` para subgráficos
- `ggsave()` para guardar gráficos
- Combinar gráficos con patchwork o gridExtra
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →