Iteratively changing the y-axis label in a series of plots

154 views
Skip to first unread message

dha 2001

unread,
Apr 17, 2012, 11:13:34 PM4/17/12
to ggplot2
Hi,

This one is probably easy but I have not been able to sort it out
after a few weeks of trying on and off.

I'm having trouble figuring out how to update the y-axis label on a
series of plots generated in a loop. I've included a toy example
below which illustrates the issue. The actual code I'm working with
creates a moderately complex arrangement of plots on a pdf page. I
have a list of variables and want to create the same arrangement on a
series of pages, one for each of the variables in the list. I've
removed the pdf generating code here so it makes little sense on the
screen but illustrates the issue.

I can iterate the data and even the title of each plot just fine but
not the y-axis. The title of the y-axis ends up as "get(yVar)".

library(ggplot2)

variables=c("drat","qsec")
basePlot <- ggplot(mtcars, aes( x=wt, y=qsec)) +
geom_point()

for (yVar in variables) {
newPlot <- basePlot + aes(y=get(yVar)) + # axis label doesn't work
opts(title=yVar) + # works.
opts(axis.title.y=get(yVar))
print(newPlot)
}


I have tried adding the following to "newPlot" with no success:

+ opts(axis.title.y=yVar)
Error in grobName(grob, prefix) : Invalid 'grob' argument

+ opts(axis.title.y=deparse(yVar))
Error in grobName(grob, prefix) : Invalid 'grob' argument

+ opts(axis.title.y=get(yVar))
Error in get(yVar) : object 'drat' not found

Any help would be greatly appreciated!

Dennis Murphy

unread,
Apr 18, 2012, 1:29:59 AM4/18/12
to dha 2001, ggplot2
Hi:

Try this:

library('ggplot2')


variables=c("drat","qsec")

for (yVar in variables) {
print(ggplot(mtcars, aes_string(x = 'wt', y= yVar)) +
geom_point() +
opts(title=yVar)
)
}

aes_string() is used to pass a character string as values of the x and
y arguments. For the main title, the value of the title argument is a
character string, so you're covered there.

HTH,
Dennis

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

dha 2001

unread,
Apr 18, 2012, 10:04:58 AM4/18/12
to ggplot2
Thanks! That did it.
Reply all
Reply to author
Forward
0 new messages