您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

80 行
2.4KB

  1. proc_data <- function(x, .id = "x", color_fun = colorize_keys, color_when = c("after", "before"), ...) {
  2. color_when <- match.arg(color_when)
  3. n_colors <- max(x$id)
  4. if (color_when == "before") x <- color_fun(x, n_colors, ...)
  5. x <- x %>%
  6. mutate(.y = -row_number()) %>%
  7. tidyr::gather("label", "value", setdiff(colnames(x), c(".y", "color"))) %>%
  8. mutate(value = as.character(value)) %>%
  9. group_by(.y) %>%
  10. mutate(
  11. .x = 1:n(),
  12. .id = .id,
  13. .width = 1
  14. ) %>%
  15. ungroup(.y)
  16. if (color_when == "after") x <- color_fun(x, n_colors, ...)
  17. x
  18. }
  19. colorize_keys <- function(df, n_colors, key_col = "id", color_other = "#d0d0d0", color_missing = "#ffffff") {
  20. # Assumes that key_col is integer
  21. colors <- scales::brewer_pal(type = "qual", "Set1")(n_colors)
  22. mutate(
  23. df,
  24. color = ifelse(label == key_col, value, n_colors + 1),
  25. color = colors[as.integer(color)],
  26. color = ifelse(is.na(color), "#d0d0d0", color),
  27. color = ifelse(is.na(value), "#ffffff", color)
  28. )
  29. }
  30. colorize_row_id <- function(df, n_colors, key_col = "id") {
  31. # Assumes that key_col is integer
  32. colors <- scales::brewer_pal(type = "qual", "Set1")(n_colors)
  33. df$color <- colors[df[[key_col]]]
  34. df
  35. }
  36. plot_data <- function(x, title = "") {
  37. if (!"alpha" %in% colnames(x)) x$alpha <- 1
  38. if (!".width" %in% colnames(x)) x$`.width` <- 1
  39. ggplot(x) +
  40. aes(.x, .y, fill = color, label = value) +
  41. geom_tile(aes(width = .width, alpha = alpha), color = "white", size = 3) +
  42. geom_text(aes(x = .x), hjust = 0.5, size = 12, family = "Fira Sans", color = "white") +
  43. scale_fill_identity() +
  44. scale_alpha_identity() +
  45. coord_equal() +
  46. ggtitle(title) +
  47. theme_void() +
  48. theme(plot.title = element_text(family = "Fira Mono", hjust = 0.5, size = 24)) +
  49. guides(fill = FALSE)
  50. }
  51. animate_plot <- function(x, transition_length = 2, state_length = 1) {
  52. x +
  53. transition_states(frame, transition_length, state_length) +
  54. enter_fade() +
  55. exit_fade() +
  56. ease_aes("sine-in-out")
  57. }
  58. save_static_plot <- function(g, filename, formats = c("png", "svg")) {
  59. filenames <- formats %>%
  60. purrr::set_names() %>%
  61. purrr::map_chr(static_plot_filename, x = filename) %>%
  62. purrr::iwalk(
  63. ~ ggsave(filename = .x, plot = g, dev = .y)
  64. )
  65. }
  66. static_plot_filename <- function(x, ext) {
  67. here::here("images", "static", ext, paste0(x, ".", ext))
  68. }
  69. options(tidy_verb_anim.functions_loaded = TRUE)