Search code examples
rannotations

How to add a custom text to a fourfoldplot graph in R?


I am trying to add additional information to a figure which is the output of the function fourfoldplot in R. This function plots the contingency table. The issue is that I need to add information to each sector of the plot. I have tried using text and mtext but no luck.

They both need the position of text in x and y (or defining the position by clicking on the plot). But this plot has no x and y since it is a pie (or I cannot find them). Another thing that adds to complexity is that I need to make make multiple graphs on one page .

Here is a sample of my data data1

#dput(data1)
list(structure(c(159076L, 5858L, 7285L, 23571L), .Dim = c(2L, 
2L), .Dimnames = list(Prediction = c("O3<80", "O3>80"), Reference = c("O3<80", 
"O3>80")), class = "table"), structure(c(159385L, 5549L, 6679L, 
24177L), .Dim = c(2L, 2L), .Dimnames = list(Prediction = c("O3<80", 
"O3>80"), Reference = c("O3<80", "O3>80")), class = "table"), 
   structure(c(159273L, 5661L, 8985L, 21871L), .Dim = c(2L, 
   2L), .Dimnames = list(Prediction = c("O3<80", "O3>80"), Reference = c("O3<80", 
   "O3>80")), class = "table"), structure(c(159250L, 5684L, 
    8486L, 22370L), .Dim = c(2L, 2L), .Dimnames = list(Prediction = c("O3<80", 
   "O3>80"), Reference = c("O3<80", "O3>80")), class = "table"))

I used the following script to plot:

par(mfrow=c(2,2))
for(pltnum in 1:length(data)) {
    fourfoldplot(data1[[pltnum]],
                 color = c("#B22222", "#2E8B57"),
                 main = "")
    }

The output of the above script is: output_mine

The output I want is: output_desired

Any help would be highly appreciated.


Solution

  • This can give you what you want. You might play with different values of (x,y) values to position the text annotation exactly where you want.

    for(pltnum in 1:length(data)) {
      fourfoldplot(data1[[pltnum]],
                   color = c("#B22222", "#2E8B57"),
                   main = "") + 
        text(-0.4,0.4, "TN", cex=1) + 
        text(0.4, -0.4, "TP", cex=1) + 
        text(0.4,0.4, "FN", cex=1) + 
        text(-0.4, -0.4, "FP", cex=1)
    }
    

    Output

    annotate_text