Skip to content

Instantly share code, notes, and snippets.

@cromanpa94
Created August 1, 2020 15:54
Show Gist options
  • Save cromanpa94/160bcb884022b4f9b4ca75d5ba4662b0 to your computer and use it in GitHub Desktop.
Save cromanpa94/160bcb884022b4f9b4ca75d5ba4662b0 to your computer and use it in GitHub Desktop.
annotate_rainbow_letters<-function(ggbasePlot, string, initialx, y, letterDistance,
wordDistance,uppcaseadditionalDistance){
spup<-strsplit(string, split = "")[[1]]
uppLett<-grepl("^[[:upper:]]+$", spup)
dostanceVector<-ifelse(spup == " ", wordDistance, letterDistance)
if(any(uppLett)){
for(i in 1:length(which(uppLett))){
dostanceVector[which(uppLett)+1]<-dostanceVector[which(uppLett)+1]+uppcaseadditionalDistance
}
}
dostanceVector[1]<-0
posLetters<-cbind.data.frame(letter=spup, xPosition=cumsum(dostanceVector)+initialx)
posLetters<-posLetters[!posLetters$letter ==" ",]
posLetters<-cbind.data.frame(posLetters,col= rainbow(nrow(posLetters)))
ggbaseAdded <- ggbasePlot + lapply(seq_along(posLetters[,1]), function(i) {
annotate("text", x = posLetters[i,2], y = y, label = posLetters[i,1],
hjust = 0, family = "Pacifico", fontface = "bold",
size = annotation_base_size * 1.75, lineheight = .8, color = posLetters[i,3])
})
return(ggbaseAdded)
}
#Test based on https://github.com/heidiesteiner/mylifeinmonths
#One line first
life_in_months_leopard_life<-annotate_rainbow_letters(
ggbasePlot=life_in_months_leopard,
string=c("My life in"),
initialx=29.75,
y=6.5,
letterDistance=0.5,
wordDistance=1,
uppcaseadditionalDistance=1
)
##Then the other...
life_in_months_titled<-annotate_rainbow_letters(
ggbasePlot=life_in_months_leopard_life,
string=c("Months"),
initialx=31,
y=4,
letterDistance=0.5,
wordDistance=1,
uppcaseadditionalDistance=1
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment