forked from adamribaudo/storytelling-with-data-ggplot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFIG0203.R
46 lines (38 loc) · 1.9 KB
/
FIG0203.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
rm(list=ls())
library(tidyverse)
library(ggtext)
source("helper_functions.R")
source("theme/theme_swd.R")
theme_set(theme_swd() + theme(axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
axis.title = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.margin = unit(c(0,0,0,0),"cm")))
df <- read_csv(file.path("data","FIG0202-3.csv")) %>% mutate(Value_pct = scales::percent(Value/100))
# Function to format a string text as markdown/HTML
format_text <- function(text, color = "black", size = 20, bold = FALSE) {
opening_span = paste0("<span style='font-size:", size,"px; color:", color,"'>")
if(bold) text = paste0("**", text, "**")
closing_span = "</span>"
paste0(opening_span, text, closing_span)
}
# Gather the formatted label into a single tibble
text_data <- tibble(
label = paste0(format_text(df %>% filter(Year == 2012) %>% pull(Value_pct), color = GREEN3, size = 128, bold = TRUE), "<br/>",
format_text("of children had a", GRAY3),"<br/>",
format_text("traditional stay-at-home mom", color = GREEN3, bold = TRUE), "<br/>",
format_text(paste0("in 2012, compared to ", df %>% filter(Year == 1970) %>% pull(Value_pct)," in 1970"), color = GRAY3)))
# Use geom_richtext from the ggtext package to render the label
pt <- text_data %>%
ggplot(aes(x = 0, y = 0)) +
geom_richtext(aes(label = label),
hjust = 0,
label.color = NA,
lineheight = 1.5) +
xlim(0, 0.01)
pt %>%
save_and_show_plot(width = 3.5, height = 2.5, "FIG0203.png")