Advertisement
Guest User

Untitled

a guest
Jan 30th, 2023
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. library(data.table)
  2. library(ggplot2)
  3.  
  4. DT <- `[`
  5.  
  6. jump_by <- function (x, by, start = 1, fill = NULL) {
  7. if (!is.null(fill)) {
  8. x[-seq.int(start, length(x), by = by)] <- fill
  9. }
  10. else {
  11. x <- x[seq.int(start, length(x), by = by)]
  12. }
  13. return(x)
  14. }
  15.  
  16.  
  17.  
  18. totals <- babynames::babynames |>
  19. as.data.table() |>
  20. DT(, .(total = sum(n)), by = .(year))
  21.  
  22.  
  23. babynames::babynames |>
  24. as.data.table() |>
  25. DT(, ending := substr(name, nchar(name), nchar(name))) |>
  26. DT(ending %in% c("a", "e", "i", "o", "u", "y")) |>
  27. DT(, .(n = sum(n)), by = .(sex, year, ending)) |>
  28. DT(totals, on = c("year")) |>
  29. DT(, prop := n/total) |>
  30. ggplot(aes(year, prop)) +
  31. geom_line(data = \(x) x[, .(total = sum(prop)), by = .(ending, year)],
  32. aes(y = total), color = "gray40",
  33. size = 1) +
  34. geom_line(aes(color = sex), size = 1.5) +
  35.  
  36. scale_color_manual("Sex", values = c("F" = "#F36F52",
  37. "M" = "#51C5DE"),
  38. labels = c("F" = "Female",
  39. "M" = "Male")) +
  40. scale_x_continuous(NULL, breaks = seq(1800, 2022, by = 10),
  41. labels = \(x) jump_by(x, 2, fill = "")) +
  42. scale_y_continuous(NULL, labels = scales::percent_format()) +
  43. expand_limits(y = 0) +
  44. theme_minimal(base_size = 20) +
  45. theme(panel.grid.minor = element_blank(),
  46. axis.ticks.x = element_line(color = "gray40")) +
  47. labs(title = "US Babies Receiving Names Ending in... ") +
  48. facet_wrap(~paste0("-", ending), scale = "free", ncol = 2)
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement