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)

 

Story time with papa Jamie

index

One cool R package I have been using lately, is ReporteRs. It essentially takes your plots etc and creates a PowerPoint of these. The quality of these are pretty good. This has been really useful for me, as I have been doing a lot of ‘data story boards’ for client presentations. Having a PowerPoint story board of all of my figures allows me to visualise what results I have, and what will be good for a client. If you’re a scientist writing a paper, this package will also come in handy as it will allow you to essentially create a PPT of your plots, diagnostics from these and even tables!

This is the final product here.

#Loading the package
require(ReporteRs)

#Create dummy variables
x=1:200
y=jitter(1:200,50)

#Setting up an lm model
m=lm(y~x)

#Set your working directory
setwd()

# Create a PowerPoint document. This is just an empty pptx doc at the moment
plots = pptx()

#Create your first slide. This will be a title slide
plots = addSlide(plots, "Section Header")
plots = addTitle(plots, "My storyline")

#Create a content slide
plots = addSlide(plots, "Title and Content")
plots = addTitle(plots, "Linear regression diagnostics")

#Wrap the plotting functions inside this wrapper.
#IMPORTANT. Anything you place in here such as functions,
#will not be avialable outside of it. So I suggest just placing
#the plotting stuff in here.
plotlm.diag= function(){
  #So we can have all of the plots on one page
  par(mfrow=c(2,2))

  #Plotting the diagnostics
  plot(m)
}

#This adds the plot to our empty plots Title and Content slide
plots = addPlot(plots, plotlm.diag,vector.graphic = T)
#Create a table output
plots = addSlide(plots, "Title and Content")
plots = addTitle(plots, "My lm output")

#The flextable output of the lm summary
plots = addFlexTable(plots, vanilla.table(data.frame("terms"=row.names(data.frame(summary(m)$coefficients)),
summary(m)$coefficients)))
#Create another content slide
plots = addSlide(plots, "Title and Content")
plots = addTitle(plots, "My plot")

plot1= function(){
  plot(x,y)
 }
plots = addPlot(plots, plot1,vector.graphic = T)

####Create PPT
writeDoc(plots, file = "mystoryline.pptx")

Creating pretty dials

1 d3w3uiLunDng-Cuj6rEO-A

R can do a lot of things really really well, but one thing it struggles to do (at least in base R anyway) is to create pretty visuals. I have recently been creating visuals for some clients and wrote some code to produce some pretty dials in R. I will start by building a simple dial, and then adding various bits to it.

1.Simple dial

 
###Create a sequence from your breaks
breaks.min=seq(from=0,to=100,by=2)

###Creating the dial shape
get.poly <- function(a,b,r1=0.5,r2=1.0) {
 th.start <- pi*(1-a/100)
 th.end <- pi*(1-b/100)
 th <- seq(th.start,th.end,length=100)
 x <- c(r1*cos(th),rev(r2*cos(th)))
 y <- c(r1*sin(th),rev(r2*sin(th)))
 return(data.frame(x,y))
}

###A nice big empty plotting area
par(mar=c(10,4,10,4))
plot(1,ylim=c(0,1),xlim=c(-1,1),type="n",axes=F,xlab="",ylab="")
###Dialling in the numbers
#Where you want the dial to finish
pos<-70

#The coloured section up to your position
p<-get.poly(breaks[1],pos,0.75) 
polygon(p,col="lightgreen",border=NA)

#From your position to the end of the dial
p<-get.poly(pos,breaks[11],0.75)
polygon(p,col="lightgrey",border=NA)

Ta da! Here we have the output for the most simple of simple dials

1 On-eNjk5ksLXrlm5Q6fHHQ

Locator arrows in R

location-pixabay-1200x800-100728584-large

When creating advanced visualisations in R, determining the coordinates of where to put your arrows or text can be a tricky thing. Luckily, there is an awesome function in R called ‘locator‘.

##Make a plot
plot(1:10,1:10)

##Place locations of two arrows
loc.arrow<-locator(4)

##Once this line is run, the console run line should be flashing.
#click on a start and stop point of the where the first arrow should go,
##then the start and stop point on the second arrow.
##The console run line should then stop flashing

##run the loc.arrow line
##in this case
loc.arrow
$x
[1] 2.828149 2.798691 5.332089 7.070118
$y
[1] 4.646730 8.367149 7.477484 4.201897

#Adding the arrows to the plot
with(loc.arrow, arrows(x0=x[seq(1,4,by=2)], x1=x[seq(2,4,by=2)],
y0=y[seq(1,4,by=2)], y1= y[seq(2,4,by=2)]))