Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

68 lines
2.0KB

  1. set_text_color <- function(a) ifelse(apply(col2rgb(a), 2, mean) > 127, "black", "white")
  2. #' Animates a plot
  3. #'
  4. #' @param d a preprocessed dataset
  5. #' @param title the plot title
  6. #' @param transition_length see transition_states
  7. #' @param state_length see transition_states
  8. #' @param ... further arguments passed to static_plot
  9. #'
  10. #' @return a gif
  11. #'
  12. #' @examples
  13. #' NULL
  14. animate_plot <- function(d, title = "", transition_length = 2, state_length = 1, ...) {
  15. static_plot(d, title, ...) +
  16. transition_states(.frame, transition_length, state_length) +
  17. enter_fade() +
  18. exit_fade() +
  19. ease_aes("sine-in-out")
  20. }
  21. #' Prints the tiles for a processed dataset statically
  22. #'
  23. #' @param d a processed dataset
  24. #' @param title the title of the plot
  25. #' @param text_family the font for the text
  26. #' @param title_family the font for the title
  27. #' @param text_size the size of the text
  28. #' @param title_size the size of the title
  29. #' @param ... further arguments
  30. #'
  31. #' @return a ggplot
  32. #'
  33. #' @examples
  34. #' NULL
  35. static_plot <- function(d, title = "",
  36. text_family = "Fira Sans", title_family = "Fira Mono",
  37. text_size = 7, title_size = 25, ...) {
  38. if (!".alpha" %in% names(d)) d <- d %>% mutate(.alpha = 1)
  39. if (!".textcolor" %in% names(d))
  40. d <- d %>% mutate(.textcolor = set_text_color(.color))
  41. if (".id_long" %in% names(d)) {
  42. d <- d %>% mutate(.item_id = paste(.id_long, .col, sep = "-"))
  43. } else {
  44. # tidyr
  45. d <- d %>% mutate(.item_id = .id)
  46. }
  47. ggplot(d, aes(x = .x, group = .item_id, y = .y, fill = .color, alpha = .alpha)) +
  48. geom_tile(width = 0.9, height = 0.9) +
  49. coord_equal() +
  50. geom_text(data = d %>% filter(!is.na(.val)), aes(label = .val, color = .textcolor),
  51. family = text_family, size = text_size) +
  52. scale_fill_identity() +
  53. scale_color_identity() +
  54. scale_alpha_identity() +
  55. labs(title = title) +
  56. theme_void() +
  57. theme(plot.title = element_text(family = title_family, hjust = 0.5, size = title_size))
  58. }