Vertically Align x-axis Labels in an R plot

When you are creating a plot in R, sometimes you have axis labels on the x axis. You can create custom ones with the axis function. If your labels are long, you can bring them apart using a newline character so they span multiple lines. But when you do this, it centers the text vertically at the bottom. But sometimes this doesn’t look right. In my case, I wanted these labels to be centered vertically at the top. I searched and couldn’t find any ideas on how to certain these vertically. If you know of something, please let me know.

Below is some code that is a workaround to certain labels vertically.

formatAxisNames = function(x, splitChar)
{
  maxSize = 0
 
  for (y in x)
  {
    z = strsplit(y, splitChar)[[1]]
    if (length(z) > maxSize)
      maxSize = length(z)
  }
 
  formatted = NULL
 
  for (y in x)
  {
    z = strsplit(y, splitChar)[[1]]
    while (length(z) < maxSize)
      z = c(z, "")
 
    formatted = c(formatted, paste(z, collapse="\n"))
  }
 
  formatted
}

The image below illustrates how this can be used:

Leave a Reply