Wednesday 18 December 2019

Insert text labels outside the plotting panel - lattice plot

In lattice, you can insert text labels inside the plot. This is useful but sometimes the labels get in the way. By changing the clip parameter within par.settings, the text labels can be displayed outside the plotting panel.

Example:  
  
par.settings = list(clip = list(panel = FALSE)  
  
  
library(lattice)  
  
dat <- iris  
  
COLOR <- c("red", "blue", "green")  
  
#with the setting to allow text label outside plotting panel  
  
xyplot(Sepal.Length ~ Sepal.Width, dat, group = dat$Species, col = COLOR,  
par.settings = list(clip = list(panel = FALSE)),  
panel = function(x, y, ...){  
panel.xyplot(x, y, ...)  
panel.text(x = c(4.5, 1.8, 3), y = c(4.5, 5.3, 8.5), label = levels(factor(dat$Species)), col = COLOR)  
}  
)  
  
  


  
#Under the default setting, the labels are cut off as you can see below
   
xyplot(Sepal.Length ~ Sepal.Width, dat, group = dat$Species, col = COLOR,  
panel = function(x, y, ...){  
panel.xyplot(x, y, ...)  
panel.text(x = c(4.5, 1.8, 3), y = c(4.5, 5.3, 8.5), label = levels(factor(dat$Species)), col = COLOR)  
}  
)  
  
  
  
  

  
  

Assigning object names in R

Assigning different object names to the output of each loop of iterative process can be done using assign() function.
  
Example: 
  
#Create an object     
OldName <- c(1:10)  
   
 #Create new object for each loop but assign them into new object names 
for (i in 1:10) {  
   assign(paste0("NewName", i), OldName[i])  
}  
   
#Check  
> NewName1    
[1] 1  
    
> NewName2    
[1] 2  
   
> NewName3  
[1] 3  
  
> sapply(ls(pattern = "^NewName[0-9]+"), get)  
 NewName1    NewName10     NewName2     NewName3     NewName4     NewName5     NewName6     NewName7 
                  1                     10                      2                      3                      4                      5                      6                      7 
 NewName8     NewName9 
                  8                      9