Solution 2.2
The Setup
library(ggplot2)
library(scales)
library(formattable)
##
## Attaching package: 'formattable'
## The following objects are masked from 'package:scales':
##
## comma, percent, scientific
# Make sure the data set is including in the working directory.
data <- read.csv("data.csv", stringsAsFactors = FALSE)
# Format meals served with commas
data_with_commas <- data.frame(data$campaign_year,
meals_served = format(data$meals_served, big.mark=",",
scientific=FALSE))
Solution 2.2a
# Define a simple table
simple_table <- formattable(data_with_commas,
col.names = c("Campaign Year", "Meals Served"),
align = c("c", "c"))
# Adjust the simple tables' width
as.htmlwidget(simple_table, width=400)
Solution 2.2b
# Define a table with conditionally formatted cells
cond_table <- formattable(data_with_commas,
col.names = c("Campaign Year", "Meals Served"),
list(meals_served = color_tile("white", "#71AC4B")),
align = c("c", "c")
)
# Adjust the conditionally formatted tables' width
as.htmlwidget(cond_table, width=400)
Solution 2.2c
# Create bar chart theme
theme_swd_bar <- theme(
plot.title = element_text(size = rel(1.75), color = "#000000"),
text = element_text(family = "Roboto", color = "#979797"),
axis.title.x = element_text(hjust = 0, vjust = -0.5),
axis.title.y = element_text(hjust = 1),
line = element_blank(),
rect = element_blank()
)
# Properly format the commas while also removing the decimal places.
scaleFUN <- function(x) format(round(as.numeric(x), 0), nsmall=0, big.mark=",")
# Apply bar chart theme to the geom_bar
ggplot(data, aes(x = campaign_year, y = meals_served)) +
geom_bar(stat="identity",
fill = "#72AC4D",
width = .55) +
scale_x_continuous(name = "CAMPAIGN YEAR",
breaks=seq(2010, 2019,1)) +
scale_y_continuous(name = "# OF MEALS SERVED",
breaks=seq(0,300000,50000),
label = scaleFUN) +
labs(title = "Meals Served Over Time") +
theme_swd_bar

Solution 2.2d
# Create line chart theme
theme_swd_line <- theme(
plot.title = element_text(size = rel(1.75), color = "#000000"),
plot.margin = margin(20, 20, 20, 20),
text = element_text(family = "Roboto", color = "#979797"),
axis.title.x = element_text(hjust = 0, vjust = -0.5),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
line = element_blank(),
rect = element_blank()
)
# Apply line chart theme to geom_line
ggplot(data, aes(x = campaign_year, y = meals_served)) +
geom_line(size = 1, color = "#72AC4D") +
scale_x_continuous(name = "CAMPAIGN YEAR",
breaks=seq(2010, 2019,1),
expand = c(0, 0)) +
labs(title = "Meals Served Over Time",
subtitle = "# OF MEALS SERVED") +
theme_swd_line +
geom_text(data = data[data$campaign_year == 2010,],
aes(label = scaleFUN(meals_served)),
hjust = -0.2,
size = 3.25,
color = "#72AC4D",
fontface = "bold") +
geom_text(data = data[data$campaign_year == 2019,],
aes(label = scaleFUN(meals_served)),
hjust = 1,
vjust = -0.5,
size = 3.25,
color = "#72AC4D",
fontface = "bold")
