Skip to content

Instantly share code, notes, and snippets.

@trcook
Created June 11, 2015 20:52
Show Gist options
  • Save trcook/7ba0674e1183a061713a to your computer and use it in GitHub Desktop.
Save trcook/7ba0674e1183a061713a to your computer and use it in GitHub Desktop.
random notes on ggplot
# use aes_string when constructing a plot in a function.
# when needed, use deparse(substitute(x)) to get an argument as a string -- useful soemtimes for using in aes_string
# use paste in aes_string to construct a string itself
# reset data source in geom_text to avoid chunky text in labels.
# all of these little tricks are used in this function:
my_grid_plot_function<-function(dat=eugene_mod2_qi,byrange=seq(0,1,.1),by_iter='entry_recency',group="factor(ambiguitymA)",xax="betmB",print=F,outfile=file.path(dissertation_root,"Construction/Graphics/grid1.pdf")){
require(gridExtra)
eval(substitute(dat[,j_iter:=x],list(x=as.name(by_iter))))
aline1<-aes_string(x=xax,y="est",color=group,linetype=group)
aribbon<-aes_string(x=xax,ymax='esthi',ymin='estlo',fill=group)
labs<-c("center","paste('two')")
if(xax%in%c('betmB','entry_recency')){
switch(xax,betmB=assign('lxax','Observer Betrayal'),entry_recency=assign('lxax','Entry Recency'))
}else{lxax<-''}
if(by_iter%in%c('betmB','entry_recency')){
switch(by_iter,betmB=assign('lby_iter','Observer Betrayal'),entry_recency=assign('lby_iter','Entry Recency'))
}else{lby_iter<-''}
plist<-lapply(byrange,function(j){
# setup labels
center1<-dat[as.factor(j_iter)==j&ambiguitymA==1,mean(est,na.rm=T)]
#: when matching against decimals, match using a factor. this avoids problems in matching due to decimal precision
center2<-dat[as.factor(j_iter)==j&ambiguitymA==0,max(est,na.rm=T)]
atext1<-aes_string(x=.5,y=center1,label='paste("ambiguous")')
atext2<-aes_string(x=.25,y=center2,label='paste("unambiguous")')
# plot itself
ggplot(data=dat[as.factor(j_iter)==j,])+
geom_line(aline1)+
geom_ribbon(aribbon,alpha=.1)+
xlab(paste(lxax,'@',lby_iter,'=',j))+
theme(legend.position="none",axis.text=element_text(size=6),axis.title=element_text(size=7))+
ylab('Probability of Alliance Formation')+
scale_color_grey()+
scale_fill_grey()+
geom_text(atext1,size=3,face='plain',data = data.frame())+
geom_text(atext2,size=3,face='plain',data = data.frame())
})
if(print==T){
pdf(file=outfile,pointsize = 6)
do.call("grid.arrange",c(plist))
dev.off()}
do.call("grid.arrange",c(plist))
return()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment