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.