Skip to content

Instantly share code, notes, and snippets.

@rudeboybert
Last active February 8, 2018 00:31
Show Gist options
  • Save rudeboybert/f8495a7911073df1f06ba399b810df45 to your computer and use it in GitHub Desktop.
Save rudeboybert/f8495a7911073df1f06ba399b810df45 to your computer and use it in GitHub Desktop.
One Simple, One Fancy, and One Interactive gapminder Bubbleplot
library(ggplot2)
library(dplyr)
library(gapminder)
# Only for 2007 data
gapminder2007 <- gapminder %>%
filter(year == 2007)
# Simple plot -------------------------------------------------------------
ggplot(gapminder2007, aes(x = gdpPercap, y = lifeExp, col = continent, size = pop)) +
geom_point() +
scale_x_log10() +
labs(
x = "GDP per capita (USD, log-scale)", y = "Life expectancy (years)",
color = "Continent", size = "Population",
title = "Relationship between Life Expectancy and GDP per Capita in 2007"
)
# Fancy plot --------------------------------------------------------------
library(ggrepel)
library(scales)
# Set which countries to explicitly label in plot
countries_to_label <- c("Afghanistan", "India", "China", "United States",
"Norway", "Japan", "Congo, Dem. Rep.", "Swaziland")
gapminder2007 <- gapminder2007 %>%
mutate(label = ifelse(country %in% countries_to_label, as.character(country), ""))
ggplot(gapminder2007, aes(x = gdpPercap, y = lifeExp, label = label)) +
geom_point(aes(col = continent, size = pop)) +
geom_label_repel() +
scale_x_log10(breaks = c(500, 5000, 50000)) +
scale_size(labels = scales::comma) +
labs(
x = "GDP per capita (USD, log-scale)", y = "Life expectancy (years)",
color = "Continent", size = "Population",
title = "Relationship between Life Expectancy and GDP per Capita in 2007"
)
# Interactive plot --------------------------------------------------------------
library(plotly)
gapminder2007_plot <-
ggplot(gapminder2007, aes(x = gdpPercap, y = lifeExp, label = country)) +
geom_point(aes(col = continent, size = pop)) +
scale_x_log10(breaks = c(500, 5000, 50000)) +
scale_size(labels = scales::comma) +
labs(
x = "GDP per capita (USD, log-scale)", y = "Life expectancy (years)",
color = "Continent", size = "Population",
title = "Relationship between Life Expectancy and GDP per Capita in 2007"
)
ggplotly(gapminder2007_plot, tooltip = c("label", "size", "x", "y"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment