Link a html de clase 8.
library(dplyr) #
library(ggplot2) #
library(gganimate) #
library(gapminder) #
library(ggthemes) #
# library(plotly) #
head(gapminder)
head(gapminder)
dim(gapminder)
## [1] 1704 6
str(gapminder)
## tibble[,6] [1,704 × 6] (S3: tbl_df/tbl/data.frame)
## $ country : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...
## $ year : int [1:1704] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
## $ lifeExp : num [1:1704] 28.8 30.3 32 34 36.1 ...
## $ pop : int [1:1704] 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ...
## $ gdpPercap: num [1:1704] 779 821 853 836 740 ...
ggplot2?ggplot2 es un sistema para crear gráficos de forma declarativa, basado en The Grammar of Graphics. Nosotros le proporcionamos los datos, y le indicamos a ggplot2 cómo asignar variables a la estética, qué gráficas de base usar y ggplot2 se encarga de los detalles.
ggplot2 se refiere al nombre del paquete en sí. Cuando usamos el paquete, usamos la función ggplot() para generar los gráficos.
Los gráficos de ggplot se construyen capa por capa agregando nuevos elementos. Agregar capas de esta manera permite una gran flexibilidad y personalización de los gráficos.
Para construir un ggplot, usaremos la siguiente plantilla básica que se puede usar para diferentes tipos de gráficos:
ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()
## Error: <text>:1:15: unexpected '<'
## 1: ggplot(data = <
## ^
Usamos la función ggplot() como vase, y asi podemos vincular el gráfico a un data.frame específico usando la siguiente sintaxis:
ggplot(data = cars)
Definimps un mapa estético (usando la función estética (aes())), seleccionando las variables que se trazarán y especificando cómo presentarlas en el gráfico, por ejemplo, como posiciones x / y o características como tamaño, forma, color, etc.
ggplot(data = cars, mapping = aes(x = speed, y = dist))
Luego, agregamos “geoms”: representaciones gráficas de los datos en el gráfico (puntos, líneas, barras).
ggplot2 ofrece muchas geoms diferentes; usaremos algunos comunes hoy, que incluyen:
geom_histogram()para histogramas.geom_bar() para gráficos de barra.geom_point() para diagramas de dispersión, diagramas de puntos, etc.Existen muchos tipos de geom, algunos otros que se ocupan mucho en economía son: - geom_boxplot() para diagramas de caja! - geom_line() para líneas de tendencia, series de tiempo, etc.
Entre otros.
Para agregar una geom a la trama, use el operador +. Debido a que tenemos dos variables continuas, usemos primero geom_point ():
ggplot(data = cars, aes(x = speed, y = dist)) +
geom_point()
El + en el paquete ggplot2 es particularmente útil porque nos permitirá modificar los objetos ggplot existentes de forma fácil. Esto significa que puede configurar fácilmente “plantillas” de gráficos y explorar convenientemente diferentes tipos de gráficos. Como podrán imaginar, el gráfico anterior también se puede generar con un código como este:
# Guardamos la base del gráfico como un elemento
cars_plot <- ggplot(data = cars,
mapping = aes(x = speed, y = dist))
# Al cual podemos llamar para crear el gráfico final con sus distintas capas
cars_plot +
geom_point()
Histograma
ggplot(data = gapminder, aes(x = lifeExp))
ggplot(data = gapminder, aes(x = lifeExp)) +
geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Tarea: Hacer el histograma del gdpPercap per capita en vez de la esperanza de vida. (#gdpPercap)
Calculemos la experanza de vida promedio por continente
gapminder %>% group_by(continent) %>% summarise(promedio=mean(lifeExp))
Ahora, haremos un gráfico sobre la tabla que construimos en el paso anterior
gapminder %>% group_by(continent) %>% summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio)) + geom_bar(stat='identity')
Ahora le vamos agregar título y fondo blanco
gapminder %>% group_by(continent) %>% summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio)) + geom_bar(stat='identity') + ggtitle("Esperanza de vida por Continente" ) + theme_bw()
¿Qué tal si trabajaramos en the Economomist?
gapminder %>% group_by(continent) %>% summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio)) + geom_bar(stat='identity') + ggtitle("Esperanza de vida por Continente" ) +
theme_economist() + scale_colour_economist()
Probemos un recurso muy importante, agreguemos colores para hacer más fácil de entender el gráfico.
gapminder %>% group_by(continent) %>% summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio, fill=continent)) + geom_bar(stat='identity') + ggtitle("Esperanza de vida por Continente" ) + theme_clean()
Probemos con el siguiente codigo: ``jCountries <- c(“Canada”, “Rwanda”, “Cambodia”, “Mexico”)
ggplot(subset(gapminder, country %in% jCountries),
aes(x = year, y = lifeExp, color = country)) + geom_line() + geom_point()``
Podemos hacerlo con dplyr en un solo paso?
Tarea: Hacer un gráfico de líneas
gapminder %>% filter(country, ("Canada", "Rwanda", "Cambodia", "Mexico")) %>%
## Error: <text>:1:41: unexpected ','
## 1: gapminder %>% filter(country, ("Canada",
## ^
¿Cuál es la diferencia entre == y %in%?
%in% busca coincidencia de valores.
== es un operador lógico destinado a comparar si dos cosas son exactamente iguales.
Pongo las definiciones en inglés porque considero que es más claro
%in% is value matching and “returns a vector of the positions of (first) matches of its first argument in its second” (See help(‘%in%’)) This means you could compare vectors of different lengths to see if elements of one vector match at least one element in another. The length of output will be equal to the length of the vector being compared (the first one).
== is logical operator meant to compare if two things are exactly equal. If the vectors are of equal length, elements will be compared element-wise. If not, vectors will be recycled. The length of output will be equal to the length of the longer vector.
Podemos hacer tambien un gráfico de puntos, pero solo del año 2007
gapminder %>% filter(year==2007) %>% ggplot(aes(x=gdpPercap, y=lifeExp)) +
geom_point()
gapminder %>% filter(year==2007) %>% ggplot(aes(x=gdpPercap, y=lifeExp)) +
geom_point(aes(size=pop))
gapminder %>% filter(year==2007) %>% ggplot(aes(x=gdpPercap, y=lifeExp)) +
geom_point(aes(size=pop, color=continent))
gapminder %>% filter(year==2007) %>% ggplot(aes(x=gdpPercap, y=lifeExp)) +
geom_point(aes(size=pop, color=continent)) +
ggtitle('Relación entre esperanza de vida y GDP per capita') +
xlab('GDP per capita ($/año)') +
ylab('Esperanza de vida (años)')
library(plotly) #
head(gapminder)
ggplotly(gapminder %>% filter(year==2007) %>% ggplot(aes(x=gdpPercap, y=lifeExp)) +
geom_point(aes(size=pop, color=country)) +
ggtitle('Relación entre esperanza de vida y GDP per capita') +
xlab('GDP per capita ($/año)') +
ylab('Esperanza de vida (años)'))
ggplot(
gapminder,
aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)
) +
geom_point(show.legend = FALSE, alpha = 0.7) +
scale_color_viridis_d() +
scale_size(range = c(2, 12)) +
scale_x_log10() +
labs(x = "GDP per capita", y = "Life expectancy")
ggplot(
gapminder,
aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)
) +
geom_point(show.legend = FALSE, alpha = 0.7) +
scale_color_viridis_d() +
scale_size(range = c(2, 12)) +
scale_x_log10() +
labs(x = "GDP per capita", y = "Life expectancy") + transition_time(year) +
labs(title = "Year: {frame_time}")
ggplotly(ggplot(
gapminder,
aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)
) +
geom_point(show.legend = FALSE, alpha = 0.7) +
scale_color_viridis_d() +
scale_size(range = c(2, 12)) +
scale_x_log10() +
labs(x = "GDP per capita", y = "Life expectancy") )
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
geom_point(alpha = 0.7, show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
scale_x_log10() +
facet_wrap(~continent) +
# Here comes the gganimate specific bits
labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
transition_time(year) +
ease_aes('linear')