Home > Back-end >  Place text in R plot where there is empty space
Place text in R plot where there is empty space

Time:07-04

I need to add some text to several different plots in R. The best location for this text will depend on where each particular plot has no(t many) points, to minimize text/point overlap. Example:

par(mfrow = c(1, 2))
plot(cars)
text(5, 100, "some text here.", adj = 0, cex = 0.7)
plot(iris[ , 3:4])
text(3, 0.5, "some text here.", adj = 0, cex = 0.7)

enter image description here

Is there a way (preferably with base R) to automatically get a good placement for the text in each plot, instead of me having to first look at each plot and then set 5, 100 and 3, 0.5 manually?

CodePudding user response:

I do not know of any built-in function, but it is not hard to write a function to compute the emptiest quadrant. The comment by @jay.sf mentioned "topright" etc. Those keywords work for legend but do not seem to work in text so I will use legend to write the text. First, the function

emptyQuadrant = function(x) {
    mid1 = sum(range(x[,1]))/2
    mid2 = sum(range(x[,2]))/2
    Q1 = sum(x[,1]>=mid1 & x[,2]>=mid2)
    Q2 = sum(x[,1]<=mid1 & x[,2]>=mid2)
    Q3 = sum(x[,1]<=mid1 & x[,2]<=mid2)
    Q4 = sum(x[,1]>=mid1 & x[,2]<=mid2)
    BestQ = which.min(c(Q1, Q2, Q3, Q4))
    return(c("topright", "topleft", 
        "bottomleft", "bottomright")[BestQ])
}

Now you can just compute the best location for the legend.

par(mfrow = c(1, 2))
plot(iris[ , 1:2])
legend(emptyQuadrant(iris[,1:2]), "some text here.", cex = 0.7, bty='n')
plot(iris[ , 3:4])
legend(emptyQuadrant(iris[,3:4]), "some text here.", cex = 0.7, bty='n')

Plots with carefully placed text

  • Related