All about that base: some cool and useful functions for base plots and beyond

meghan_trainor_photos-770x470

You’re either in the ggplot gang or the base plot gang. Despite what I joke to people about, I like ggplot, I have just plide my trade in base plot. Along the way, I have found some pretty useful snippets of code that are handy for base and to a lesser extent ggplot. I will be updating this sporadically when I come across more useful functions.

##Text and sequence manipulation
#Round up nice. Round up a sequence to the nearest 10.
roundUpNice = function(x, nice=c(1:10)) {
  if(length(x) != 1) stop("'x' must be of length 1")
  10^floor(log10(x)) * nice[[which(x <= 10^floor(log10(x)) * nice)[[1]]]]
}

#Wrapping strings. For when you have lengthly text that you automatically want to spread across
#multiple lines. The width argument determines where to cut the string.
wrap_strings = function(vector_of_strings,width){sapply(vector_of_strings,FUN=function(x){paste(strwrap(x,width=width), collapse="\n")})}
#e.g. wrap_strings(mytxext,width=15)
#If you have one line of text and want to split it up, then use the \n argument
txt = "Hugh Jackman\nis my bae"

#Orientating the x-axis to a given angle (and not just those set via las). The srt number defines
#the angle. Remember to put xpd =TRUE, so you can plot outside of the plotting area.
text(x.range,1,
    srt = 50, adj= 1, xpd = TRUE,
    labels = names)

##Fine details
#Setting the transparency of colours. The second argument is the alpha level. 1 for non-transparent,
#0 for completely transparent
adjustcolor("blue",0.3)

#This changes the height between text thats on 2 lines
par(lheight=0.3)

#If all else fails and you want to make the graph in Excel,
#then this handy function should do the trick
write.excel <- function(x,row.names=FALSE,col.names=TRUE,...) {
 write.table(x,"clipboard",sep="\t",row.names=row.names,col.names=col.names,...)
}

 

Author: Jamie Samson

I am Head of Data Science and Insights at www.mindfolio.com. I am a lover of R and consider myself an Rtist in data visualisations.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s