library(ggplot2)
library(gcookbook)
library(MASS)
library(RColorBrewer)
library(scales)

Using Colors in Plots

Note: Some problems cannot be completed as written because the code has changed. You will need to find the updated code.

Section 12.1. Setting the Colors in Objects

# Figure 12-1
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(colour = "red")

ggplot(birthwt, aes(x = bwt)) + geom_histogram(fill = "red", color = "black")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Section 12.2. Mapping Variables to Colors

# Figure 12-2
ggplot(cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) +
 geom_bar(colour="black", position = "dodge", stat = "identity")

ggplot(mtcars, aes(x = wt, y = mpg, colour = cyl)) + geom_point()

# Figure 12-3
ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) + geom_point()

Section 12.3. Using a Different Palette for a Discrete Variable

# Figure 12-4
p <- ggplot(uspopage, aes(x = Year, y = Thousands, fill = AgeGroup)) + geom_area()
p

p + scale_fill_brewer()

# Figure 12-5
h <- ggplot(heightweight, aes(x = ageYear, y = heightIn, colour = sex)) +
 geom_point()
h

h + scale_color_hue(l = 45)

# Figure 12-6
display.brewer.all()

# Figure 12-7
p + scale_fill_brewer(palette = "Oranges")

# Figure 12-8
p + scale_fill_grey()

p + scale_fill_grey(start = 0.7, end = 0)

Section 12.4. Using a Manually Defined Palette for a Discrete Variable

# Figure 12-9
h + scale_colour_manual(values = c("red", "blue"))

h + scale_colour_manual(values = c("#CC6666", "#7777DD"))

Section 12.5. Using a Colorblind-Friendly Palette

# Figure 12-10
cb_palette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442",
 "#0072B2", "#D55E00", "#CC79A7")
p + scale_fill_manual(values = cb_palette)

Section 12.6. Using a Manually Defined Palette for a Continuous Variable

# Figure 12-12
p <- ggplot(heightweight, aes(x = ageYear, y = heightIn, colour = weightLb)) +
 geom_point(size = 3)
p

p + scale_colour_gradient(low = "black", high = "white")

p + scale_colour_gradient2(low = muted("red"), mid = "white", high = muted("blue"), midpoint = 110)

p + scale_colour_gradientn(colours = c("darkred", "orange", "yellow", "white"))

Section 12.7. Coloring a Shaded Region Based on Value

# Figure 12-13
cb <- subset(climate, Source=="Berkeley")
cb$valence[cb$Anomaly10y >= 0] <- "pos"
cb$valence[cb$Anomaly10y < 0] <- "neg"
ggplot(cb, aes(x = Year, y = Anomaly10y)) +
 geom_area(aes(fill = valence)) +
 geom_line() +
 geom_hline(yintercept = 0)

# Figure 12-14
interp <- approx(cb$Year, cb$Anomaly10y, n = 1000)
cbi <- data.frame(Year = interp$x, Anomaly10y = interp$y)
cbi$valence[cbi$Anomaly10y >= 0] <- "pos"
cbi$valence[cbi$Anomaly10y < 0] <- "neg"
ggplot(cbi, aes(x = Year, y = Anomaly10y)) +
 geom_area(aes(fill = valence), alpha = .4) +
 geom_line() +
 geom_hline(yintercept = 0) +
 scale_fill_manual(values = c("#CCEEFF", "#FFDDDD"), guide = FALSE) +
 scale_x_continuous(expand = c(0, 0))


END!