R. create a plot with non overlapping labels

The X axis labels were a bit long and they were having trouble fitting into the plot correctly. I tried various solutions: R’s default and maptool’s pointLabel. The first did not really allow me to turn the labels 90 deg (I know I can do it with text, but that is not R’s default for creating the X axis). The second did not really work that well with my long labels.

The trick that I applied is contained in this commit. This is the steps that the algorithm follows explained in “human” terms:

  • I found the plot X axis increment. This means that the plot will increment INC amount of units for every point in the X axis.
INC = ( par("fin")[1]/abs(abs(par("usr")[1])-abs(par("usr")[2]))
  • I found the size of the resulting font. Notice that in the commit that I linked there is an additional CEX variable. I use it because text allows further font size control. Further notice that all the variables I’m using have the same units.
FS = (par("cin")[1]*CEX)
  • The relation between FS and INC is the minimum space in X axis units that needs to exist between two labels.
MagicNumber = FS/INC
  • Finally its a matter of constructing the “at” and “label” vectors being careful that adjacent elements don’t have a distance < MagicNumber
for ( i in 1:(length(AT)-1) )
{
  dist = abs(ATtmp[length(ATtmp)] - AT[i+1])
  if ( dist > MagicNumber )
  {
   ATtmp = c(ATtmp, AT[i+1])
   Ltmp = c(Ltmp, labls[i+1])
  }
}

I could have probably coded this more efficiently, but I am lazy by nature :)

Advertisement

About joelgranados

I'm fascinated with how technology and science impact our reality and am drawn to leverage them in order to increase the potential of human activity.
This entry was posted in commands, R and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s