Search code examples
rggplot2scatter-plot

How to plot scatter plot for a data in matrix form


I have data in a matrix form. I have two such matrices and want to plot it together for comparison purposes.

Type1:

  A B C D
A 1 2 3 4
B 2 1 7 8
C 3 7 1 9
D 4 8 9 1
Type2

  A  B  C  D
A 1  12 13 14
B 12 1  17 18
C 13 17 1  19
D 14 18 19 1

I want to keep type 1 as x-axis and type 2 as y-axis. How can I draw a scatter plot for this data using R?

Thanks a lot in advance!


Solution

  • You can first store your matrix values into a dataframe. You can use the function c(matrix1) to convert your matrix into a vector then storing this vector into a dataframe.

    Then you can plot each dataframe new variable against each other.

    ### Import library
    library(ggplot2)
    
    ### Simulating data
    df <- data.frame(
      coordinate=c("AA", "AB", "AC", "AD", 
                   "BA", "BB", "BC", "BD", 
                   "CA", "CB", "CC", "CD",
                   "DA", "DB", "DC", "DD"),
      matrix1=c(1, 2, 3, 4, 2, 1, 7, 8, 3, 7, 1, 9, 4, 8, 9, 1),
      matrix2=c(1, 12, 13, 14, 12, 1, 17, 18, 13, 17, 1, 19, 14, 18, 19, 1))
    
    ### Display plot
    ggplot(data=df, aes(x=matrix1, y=matrix2)) + 
      geom_point()  + 
      geom_line() + 
      scale_x_continuous(limits=c(0, 20), breaks=seq(0, 20, 1)) + 
      scale_y_continuous(limits=c(0, 20), breaks=seq(0, 20, 1))
    

    Sometimes it makes no sense to link the dots, if so, you can remove the geom_line() row.

    enter image description here

    Following your second question, if you want to add labels, you have many options. You can find two options with the following code, by either using geom_text_repel from ggrepel library or simply geom_text from ggplot2 library where you play with width and height arguments.

    ### Update group of labels with the same coordinates
    df$matrixboth <- paste(df$matrix1, df$matrix2)
    
    ### Display plot
    ggplot(data=df, aes(x=matrix1, y=matrix2, label=coordinate)) + 
      geom_point()  + 
      geom_line(color="#6aa6e7", size=1) + 
      scale_x_continuous(limits=c(0, 20), breaks=seq(0, 20, 1)) + 
      scale_y_continuous(limits=c(0, 20), breaks=seq(0, 20, 1)) + 
      # geom_text(position=position_jitter(width=0.6, height=0.6, aes(color=matrixboth)) + 
      ggrepel::geom_text_repel(aes(label=coordinate, color=matrixboth)) + 
      theme(legend.position="none")
    

    geom_text_repel

    enter image description here

    geom_text

    enter image description here