Search code examples
rplotgraphvisualizationcorrelation

pairs() how to give different labels a different font style?


In a correlogram created by pairs(), I want the first, second, and fifth label in regular font (font.label=1); the third cursive (font.label=3); the forth and sixth label in bold font (font.label=4). I managed to give the different histograms a different color, yet I fail to do the same for the label fonts.

Changing font.label changes the font style of all labels and does not accept more than one number. When trying to create my own text.panel function I can't figure how to make the font style dynamic.

Reproducible code:

data("USJudgeRatings")
correlation <- USJudgeRatings[1:6]

clrs <- RColorBrewer::brewer.pal(n = 6, name = "RdBu")

panel.hist <- function(x, ...) {
  usr <- par("usr")
  on.exit(par(usr))
  par(usr = c(usr[1:2], 0, 1.5))
  his <- hist(x, plot = FALSE)
  breaks <- his$breaks
  nB <- length(breaks)
  y <- his$counts
  y <- y/max(y)
  c <<- c +1 
  rect(breaks[-nB], 0, breaks[-1], y, col = clrs[c] , ...) #different color per histogram
}


c <- 0
pairs(correlation,
      na.action = na.omit,
      diag.panel = panel.hist,# Adding the histograms
      #text.panel =   #Can we do something here? 
      #font.labels = c(1,1,3,2,1,2),   #Only takes one number
      cex.labels = 2,
      oma=c(1.4,1.4,1.4,1.4)) 

Solution

  • As you suggest, you can provide a custom function for text.panel:

    c <- 0
    pairs(correlation,
          na.action = na.omit,
          diag.panel = panel.hist,# Adding the histograms
          text.panel = function(x, y, labels, cex, font, ...) 
            text(x, y, labels, font=c(1, 1, 3, 2, 1, 2)[c]),
          cex.labels = 2,
          oma=c(1.4, 1.4, 1.4, 1.4)) 
    

    It uses the same global variable c as your panel.hist() function. I can't say I am too happy about such a solution (and naming a variable c is not a particularly good idea either) but it does get the job done.