Search code examples
rplotknights-tour

R, creating a knights tour plot with a matrix indicating the path


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


Solution

  • 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.