/R/path-andrews.r

http://github.com/ggobi/tourr · R · 79 lines · 22 code · 4 blank · 53 comment · 0 complexity · c27726a51fe064c5515d058315d05ff0 MD5 · raw file

  1. #' Draw the path that the geodesics took.
  2. #'
  3. #' This computes the projected values of each observation at each step, and
  4. #' allows you to recreate static views of the animated plots.
  5. #'
  6. #' @param history list of bases produced by \code{\link{save_history}}
  7. #' (or otherwise)
  8. #' @param data dataset to be projected on to bases
  9. #' @export
  10. #' @examples
  11. #' path1d <- save_history(flea[, 1:6], grand_tour(1), 10)
  12. #' path2d <- save_history(flea[, 1:6], grand_tour(2), 10)
  13. #'
  14. #' if (require("ggplot2")) {
  15. #' plot(path_curves(path1d))
  16. #' plot(path_curves(interpolate(path1d)))
  17. #'
  18. #' plot(path_curves(path2d))
  19. #' plot(path_curves(interpolate(path2d)))
  20. #'
  21. #' # Instead of relying on the built in plot method, you might want to
  22. #' # generate your own. Here are few examples of alternative displays:
  23. #'
  24. #' df <- path_curves(path2d)
  25. #' ggplot(data = df, aes(x = step, y = value, group = obs:var, colour = var)) +
  26. #' geom_line() +
  27. #' facet_wrap(~obs)
  28. #'
  29. #' library(tidyr)
  30. #' ggplot(
  31. #' data = pivot_wider(df,
  32. #' id_cols = c(obs, step),
  33. #' names_from = var, names_prefix = "Var",
  34. #' values_from = value
  35. #' ),
  36. #' aes(x = Var1, y = Var2)
  37. #' ) +
  38. #' geom_point() +
  39. #' facet_wrap(~step) +
  40. #' coord_equal()
  41. #' }
  42. path_curves <- function(history, data = attr(history, "data")) {
  43. history <- as.list(history)
  44. n <- length(history)
  45. project <- function(basis) {
  46. proj <- data %*% basis
  47. data.frame(
  48. obs = factor(row(proj)),
  49. var = factor(col(proj)),
  50. value = as.vector(proj)
  51. )
  52. }
  53. projections <- do.call("rbind", lapply(history, project))
  54. projections$step <- rep(seq_len(n), each = nrow(data) * ncol(history[[1]]))
  55. class(projections) <- c("path_curve", class(projections))
  56. projections
  57. }
  58. #' Plot history curves.
  59. #'
  60. #' The default plot method is a line plot with step on the x axis and
  61. #' value on the y axis. Each observation is drawn with a different line
  62. #' line and the plot is facetted by variable. This is rather similar in
  63. #' spirit to a parallel coordinates plot or Andrews curves.
  64. #'
  65. #' For alternative ways of plotting this data, see
  66. #' \code{\link{path_curves}}
  67. #' @keywords internal
  68. #' @export
  69. plot.path_curve <- function(x, ...) {
  70. step <- NULL # quiet R CMD check warning
  71. ggplot2::ggplot(data = x, ggplot2::aes(x = step, y = value, group = obs)) +
  72. ggplot2::geom_line() +
  73. ggplot2::facet_grid(var ~ .)
  74. }
  75. # globalVariables(c("value", "obs"))