Rory Shaw
Rory Shaw

Reputation: 851

ggplot function factor level as title

I want to create plots from the following data, so that each plot Title is the Site. I have the following dataframe:

> head(sum_stats)
   Season         Site Isotope Time n      mean       sd        se
1 Summer Afon Cadnant   14CAA    0 3 100.00000 0.000000 0.0000000
2 Summer Afon Cadnant   14CAA    2 3  68.26976 4.375331 2.5260988
3 Summer Afon Cadnant   14CAA    5 3  69.95398 7.885443 4.5526627
4 Summer Afon Cadnant   14CAA   24 3  36.84054 2.421846 1.3982532
5 Summer Afon Cadnant   14CAA   48 3  27.96619 0.829134 0.4787008
6 Summer Afon Cadnant   14CAA   72 3  26.28713 1.454819 0.8399404

> str(sum_stats)
'data.frame':   648 obs. of  8 variables:
 $ Season : Factor w/ 1 level "Summer": 1 1 1 1 1 1 1 1 1 1 ...
 $ Site   : Factor w/ 27 levels "Afon Cadnant",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Isotope: Factor w/ 4 levels "14CAA","14CGlu",..: 1 1 1 1 1 1 2 2 2 2 ...
 $ Time   : num  0 2 5 24 48 72 0 2 5 24 ...
 $ n      : int  3 3 3 3 3 3 3 3 3 3 ...
 $ mean   : num  100 68.3 70 36.8 28 ...
 $ sd     : num  0 4.375 7.885 2.422 0.829 ...
 $ se     : num  0 2.526 4.553 1.398 0.479 ...

I have written a function to create plots of the above data:

plot_func <- function(T){ggplot(data = T) + geom_point(aes(Time, mean,   colour = Season)) + 
  geom_line(aes(Time, mean, colour = Season)) +
  geom_errorbar(aes(Time, mean, ymax = (mean + se), ymin = (mean - se)), width   = 0.1) +
  labs(title = unique(levels(sum_stats$Site)), y = "Percentage of isotope   remaining in solution", x = "Time (h)") +
  facet_wrap(~Isotope, ncol = 2)} + theme(axis.title.y = element_text(vjust = 1)) +
  theme(axis.title.x = element_text(vjust = -0.1)) + theme(plot.title =  element_text(vjust = 1)) +
  theme_bw()

I then use the function in a by call to run the function over each level of the Site factor:

by(sum_stats, sum_stats$Site, plot_func)

I get 27 graphs of the following form:

enter image description here

However, all the titles are the same. How can I make each title reflect the factor level that it is plotting? Can this be done inside the plotting function?

Thanks

Upvotes: 0

Views: 596

Answers (1)

MrFlick
MrFlick

Reputation: 206232

Right now you are setting the title using the original data.frame, and not the subset of data passed to you function. If all the sites are the same in the subset you receive, you can just use the first as the title. Use

...
labs(title = T$Site[1], ...)
...

Upvotes: 2

Related Questions