0

I'm relatively new to ggplot and R, and am trying to write a small function to make it easy to run the same code for multiple bird species, denoted by the species code in the function argument. I want to use a single argument as both the y-axis data for a scatterplot AND for the y-axis label.

I've read the answer to this question but I can't get the y axis and the x axis to both display correctly at the same time:

# set up
library(ggplot2)

df.eg <- data.frame(
  yr = sample(2005:2015,100,replace=TRUE),
  rt = sample(letters[1:4],100,replace=TRUE),
  SP1 = sample(0:10,100,replace=TRUE),
  SP2 = sample(0:20,100,replace=TRUE)
)
attach(df.eg)

# standalone ggplots to wrap in function, ylab automatically correct
p1<-ggplot(df.eg, aes(x=yr, y=SP1)) + geom_point() +
    stat_smooth(method="lm", se=TRUE)
p1

p2<-ggplot(df.eg, aes(x=yr, y=SP1)) + geom_point() +
    stat_smooth(method="lm", se=TRUE) + facet_wrap(~rt)
p2

# wrap the two plots in function
fx.eg <- function(SPX)
{
  p1<-ggplot(df.eg, aes(x=yr, y=SPX)) + geom_point() +
    stat_smooth(method="lm", se=TRUE) + ylab(SPX)

  p2<-ggplot(df.eg, aes(x=yr, y=SPX)) + geom_point() +
    stat_smooth(method="lm", se=TRUE) + facet_wrap(~rt) + ylab(SPX)

  return(list(p1,p2))
}

# run function on second species
fx.eg(SP2)

If I don't specify ylab() in the function, the plots show "SPX" (no quotes) as the y-axis label instead of the function argument.

If I use aes(x=yr, y=SPX), add + ylab(SPX) in the function, and call fx.eg(SP2), the y-axis label shows as a number (in this case 4, but every time I try something different, it's a different number).

If I use aes_string(x=yr, y=SPX), keep + ylab(SPX) in the function, and call fx.eg(SP2), the y-axis shows correctly (i.e. "SP1" or "SP2"), but the x-axis displays as a list of years (e.g. "c(2010L, 2009L, 2008L, etc...")

I feel like I'm pretty close, but just can't get it to all work together. Any hints would be much appreciated.

Community
  • 1
  • 1
JMDR
  • 121
  • 1
  • 8
  • 1
    You'll have to use `aes_string` instead of `aes` – talat Feb 22 '16 at 17:40
  • @docendo-discimus thanks for the tip on `aes_string`, I hadn't known about that and it _almost_ worked, but caused other issues—see edited question above – JMDR Feb 22 '16 at 19:43
  • 1. don't use `attach`; 2. in your function definition, use `aes_string(x="yr", y=SPX))`; 3. call the function using `fx.eg("SP2")`. Does that work? – talat Feb 22 '16 at 19:50
  • That worked, thanks @docendo-discimus. Could you point me at a good explanation of when to use `attach` and when (as in this case) it causes problems? (I've read the help files, but am obviously not 100% clear) – JMDR Feb 22 '16 at 20:07
  • 1
    It's simple: don't use `attach` at all. – talat Feb 22 '16 at 20:08
  • 10-4, thanks for your help – JMDR Feb 22 '16 at 20:51

0 Answers0