January 2, 2016

Using attr labels for ggplot

The problem

In social sciences, variables often have long and informative labels. Mostly they are too long to put into variable names, and often you want to keep short, systematic variable names as well as long labels. I am always messing about with changing the labels for my ggplot plots.

The solution

Here is a simple function to wrap a ggplot so that it uses the labels stored in attr(var,“label”) rather than the variable names for the x and y axis labels.

ggplotl=function(...){
  plot=ggplot(...)
  dat=plot$data
  for(m in names(plot$mapping)){
    char=paste0(plot$mapping[m])
    ml=attr(dat[,char],"label")
    plot$labels[m]=ml
  }

  plot
}

Example:

attr(mtcars$cyl,"label")="my label";ggplotl(data=mtcars,aes(x=mpg,y=cyl,colour=cyl))+geom_point()

r code


Previous post
A PDF workflow which kills no kittens I have spent really decades trying to find a decent workflow for storing, annotating and referencing research documents, mostly but not always PDFs.
Next post
rbind.fill for 1-dimensional tables in r I have two one-dimensional frequency tables resulting from say the baseline and endline of a survey, recording say membership of 5 age groups. The


This blog by Steve Powell is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, syndicated on r-bloggers and powered by Blot.
Privacy Policy
.