-
Notifications
You must be signed in to change notification settings - Fork 133
/
gapminder-ggplot2-colors.r
60 lines (47 loc) · 1.71 KB
/
gapminder-ggplot2-colors.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#' ---
#' author: "Jenny Bryan"
#' output:
#' html_document:
#' keep_md: TRUE
#' ---
#+ setup, include = FALSE
library(knitr)
opts_chunk$set(fig.path = 'figure/colors-', error = TRUE)
#' Note: this HTML is made by applying `knitr::spin()` to an R script. So the
#' narrative is very minimal.
library(ggplot2)
library(RColorBrewer)
#' pick a way to load the data
#gdURL <- "http://tiny.cc/gapminder"
#gapminder <- read.delim(file = gdURL)
#gapminder <- read.delim("gapminderDataFiveYear.tsv")
library(gapminder)
str(gapminder)
#' let just look at four countries
jCountries <- c("Canada", "Rwanda", "Cambodia", "Mexico")
x <- droplevels(subset(gapminder, country %in% jCountries))
ggplot(x, aes(x = year, y = lifeExp, color = country)) +
geom_line() + geom_point()
#' reorder the country factor to reflect lifeExp in 2007
x <- transform(x, country = reorder(country, -1 * lifeExp, max))
ggplot(x, aes(x = year, y = lifeExp, color = country)) +
geom_line() + geom_point()
#' look at the RColorBrewer color palettes
display.brewer.all()
#' focus on the qualitative palettes
display.brewer.all(type = "qual")
#' pick some colors
jColors = brewer.pal(n = 8, "Dark2")[seq_len(nlevels(x$country))]
names(jColors) <- levels(x$country)
#' remake the plot with our new colors
ggplot(x, aes(x = year, y = lifeExp, color = country)) +
geom_line() + geom_point() +
scale_color_manual(values = jColors)
#' pick some super ugly colors for shock value
kColors = c("darkorange2", "deeppink3", "lawngreen", "peachpuff4")
names(kColors) <- levels(x$country)
#' remake the plot with our ugly colors
ggplot(x, aes(x = year, y = lifeExp, color = country)) +
geom_line() + geom_point() +
scale_color_manual(values = kColors)
sessionInfo()