0

I need to create a knight tour plot out of such an exemplary matrix:

Mat = matrix(c(1, 38, 55, 34, 3, 36, 19, 22,
               54, 47, 2, 37, 20, 23, 4, 17,
               39, 56, 33, 46, 35, 18, 21, 10,
               48, 53, 40, 57, 24, 11, 16, 5,
               59, 32, 45, 52, 41, 26, 9, 12,
               44, 49, 58, 25, 62, 15, 6, 27,
               31, 60, 51, 42, 29, 8, 13, 64,
               50, 43, 30, 61, 14, 63, 28, 7), nrow=8, ncol=8, byrow=T)

Numbers indicate the order in which knight moves to create a path. I have a lot of these kind of results with chessboard up to 75 in size, however I have no way of presenting them in a readable way, I found out that R, given the matrix, is capable of creating a plot like this: link (this one is 50x50 in size)

So for the matrix I presented the lines between two points occur between the numbers like: 1 - 2 - 3 - 4 - 5 - ... - 64, in the end creating a path presented in the link, but for the 8x8 chessboard, instead of 50x50

However, I have a very limited time to learn R good enough to accomplish it, I am desperate for any kind of direction. How hard does creating such code in R, that tranforms any matrix into such plot, is going to be ? Or is it something trivial ? Any code samples would be a blessing

false
  • 10,264
  • 13
  • 101
  • 209
mathew
  • 3
  • 3

1 Answers1

0

You can use geom_path as described here: ggplot2 line plot order

In order to do so you need to convert the matrix into a tibble.

coords <- tibble(col = rep(1:8, 8),
                 row = rep(1:8, each = 8))

coords %>%
  mutate(order = Mat[8 * (col - 1) + row]) %>%
  arrange(order) %>% 
  ggplot(aes(x = col, y = row)) + 
    geom_path() + 
    geom_text(aes(y = row + 0.25, label = order))  +
    coord_equal()   # Ensures a square board.

You can subtract .5 from the col and row positions to give a more natural chess board feel.

Ari Anisfeld
  • 736
  • 8
  • 14
  • Looks very promising, thanks ! Tho the numbers within the plot are upside down, the top row is at the bottom, any idea why ? https://imgur.com/a/CyLyb97 (it is with positions -0.5). Also, is there a way to hide the numbers ? – mathew Aug 17 '20 at 16:09
  • Yes, because `Mat[1,1]` is the top corner of the matrix, but `1,1` is the bottom corner of the graph. If that matters to you, you can transform the row and cols in the mutate with a transformation like `col = - col + 9,` – Ari Anisfeld Aug 17 '20 at 16:18
  • Got it, looks fine now ! Is there any way to hide the numbers ? With matrix of 50 x 50 the numbers themselves can blur the plot – mathew Aug 17 '20 at 16:31