How do make multiple plots in r, one for each vector that needs to create coordinates with another one?

Viewed 48

So, I have an ordered list, for example:

(1, 2, 3, 4, 5, 6, 7, 8)

Then I have multiple permutations, say:

(3, 2, 5, 4, 1, 6, 7, 8),

(7, 2, 4, 1, 3, 5, 8, 6),

...

Now, I need to plot each permutation separately (in a new plot), with the same ordered list, such that I form a scatterplot of coordinates.

  • So, for the first permutation I would need to plot (1,3), (2,2), (3,5), (4,4), ...

  • And for the second permutation I would need to plot (1,7), (2,2), (3,4), (4,1), ...

Something like this:

Example, where 'a' is the ordered list and 'b' is the first permutation

I created this for a single couple + permutation pair, but I don't know how to scale it with multiple permutations. I just manually replace the permutation each time, but this way it takes ages:

library(tidyverse)

ordered <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
permutation <- c(5, 7, 8, 6, 9, 4, 1, 3, 2)

coord.permutations <- data.frame(ordered,permutation)

ggplot(data=coord.permutations)+
  geom_point(aes(ordered,permutation,size=3))+
  scale_x_continuous(breaks = seq(0,(length(ordered)+1)), minor_breaks = seq(0,(length(ordered)+1)), expand = c(0,0), limits= c(0,(length(ordered)+1)))+
  scale_y_continuous(breaks = seq(0,(length(ordered)+1)), minor_breaks = seq(0,(length(ordered)+1)), expand = c(0,0), limits= c(0,(length(ordered)+1)))+
  coord_fixed()

Thanks in advance for any help!

1 Answers

Assuming you have saved the permutations in the list coord.permutations, then you can loop over this list using map and save each plot also in a list.

library(tidyverse)
coord.permutations <- list(c(5, 7, 8, 6, 9, 4, 1, 3, 2), c(2, 9, 1, 6, 5, 4, 7, 3, 8))
plots <- map(coord.permutations, ~ggplot(tibble(ordered, permutation=.))+
        geom_point(aes(ordered,permutation,size=3))+
        coord_fixed())
plots[[1]]

enter image description here

Using animation of 10 permutations

library(gganimate)
ggplot(data.frame(ordered = rep(ordered, 10), permutation = unlist(map(1:10, ~sample(1:10, 9))), n_per = rep(1:10, each=9))) + 
  geom_point(aes(ordered,permutation)) +
  transition_states(n_per, transition_length = 2, state_length = 1) +
  ggtitle('Permutation {closest_state}')

enter image description here

Related