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 
  
  
  
  




Monday, 19 March 2018

Working with R Objects


When you create R objects and wants to retrieve the contents of the R object by iterating through the names recorded in the environment, get() is a useful function to use which avoids having to type out each of the object individually.

Example:

VECTOR1 <- sample(LETTERS, 10)
VECTOR1  

[1] "Y" "V" "T" "D" "K" "R" "W" "L" "Q" "J"  
 
VECTOR2 <- sample(letters, 30, replace = T)
VECTOR2  

 [1] "q" "i" "m" "u" "p" "e" "u" "t" "l" "t" "z" "k" "h" "u" "h" "o" "d" "t" "z" "n" "q" "a" "k" "b" "s" "e" "j"   
[28] "l" "k" "i"  
 
VECTOR3 <- runif(13)
VECTOR3  

[1] 0.73954457 0.19358300 0.04297713 0.99239641 0.28687096 0.47457809 0.10748857 0.83374202 0.66029667 0.74115429  
[11] 0.23601701 0.11957657 0.81442439  
   
LS <- ls(pattern = "^VECTOR")
LS  

[1] "VECTOR1" "VECTOR2" "VECTOR3"  
 
get(LS[1])  
 [1] "Y" "V" "T" "D" "K" "R" "W" "L" "Q" "J"  
 
get(LS[2])  
 [1] "q" "i" "m" "u" "p" "e" "u" "t" "l" "t" "z" "k" "h" "u" "h" "o" "d" "t" "z" "n" "q" "a" "k" "b" "s" "e" "j"  
[28] "l" "k" "i"  
 

Friday, 8 December 2017

3D Animated Graph - Rotation

For scatter plot:


library(car) library(rgl)


dat <- iris

KM <- kmeans(dat[, 1:4], centers = 3)

scatter3d(
x = dat$Sepal.Length, 
y = dat$Sepal.Width, 
z = dat$Petal.Length, 
bg.col = c("white"), 
ellipsoid.alpha = 0.2, 
xlab = "Sepal.Length", 
ylab = "Sepal.Width", 
zlab = "Petal.Length", 
surface.col = colorRampPalette(c("blue", "yellow", "red"))(length(levels(factor(KM$cluster)))), 
groups = factor(KM$cluster),
grid FALSE,
surface = FALSE,
ellipsoid = TRUE
)

aspect3d(1,1,1)
          
movie3d(
spin3d(axis = c(0, 1, 0)), 
duration = 25, 
convert = FALSE,
fps = 7, 
movie = "Iris_Cluster", 
dir = getwd()

)


To save the output into a file, ImageMagick needs to be installed first. 

'rgl' package looks for convert.exe file in ImageMagick, so ensure to click the option to install legacy utilities when installing ImageMagick. (Note: the later updates to the packages might have fixed this issue, but older version of Windows could present issues along this line).

Note2: If you are on 32bit Windows, install 32bit ImageMagick.

movie3d(
spin3d(axis = c(0, 1, 0)), 
duration = 25, 
convert = TRUE,
fps = 7, 
movie = "Iris_Cluster", 
dir = getwd()
)




For bar/column chart:

library(lattice)
library(latticeExtra)
library(animation)

Dat <- aggregate(Sepal.Length~Species+Petal.Length, iris, mean)

RotPlot<-function(A){
   for(i in A){
      print(
         cloud(Sepal.Length ~ Species + Petal.Length, Dat, panel.3d.cloud = panel.3dbars,
                screen = list(z = i, x = -60), 
                col.facet=colorRampPalette(c("dodgerblue", "salmon"))(nrow(Dat)),
                xbase = 0.4, ybase = 0.4, scales = list(arrows = FALSE, col = 1),
                col = "white", par.settings = list(axis.line = list(col = "transparent"))
         )
      )
   }
}

ROT<-seq(0,360,by=10)

saveGIF(RotPlot(ROT), interval = 0.5, movie.name = "Iris.gif",
          ani.height = 640, ani.width = 640)















Connect to Google Map API from R

The below enables geocoding from R using Google Map API.

The relevant website is:

https://developers.google.com/maps/

There is a restriction on how many requests can be made per day for free usage etc, and the above website provides the necessary information and guidelines.

While it is not necessary, you can download your own key for additional benefits including tracking of the usage. Please see below link:

https://developers.google.com/maps/documentation/javascript/get-api-key


EXAMPLE:


library(RJSONIO)

#if you are using a key
KEY<-as.character(read.table("//[path to your Google Key]/[name of file containing the key (e.g. '.GoogleApiKey.txt']", header=FALSE, sep = ""))

search_url <- paste("https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=[insert address or location searched]&key=", KEY, sep = "")


#if you are NOT using a key
search_url <- "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=[insert address or location searched]"
  
  
con <- url(search_url, open="r")
  
geo_info <- fromJSON(paste(readLines(con), collapse=""))

close(con)

#Flatten the received JSON
geo_info  <- unlist(geo_info )

latitude <- geo_info["results.geometry.location.lat"]
longitude <- geo_info["results.geometry.location.lng"]