2015-12-09 54 views
0

我想從下面的數據創建情節,以便每個標題是Site。我有以下數據框:ggplot功能因素水平爲標題

> 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 ... 

我寫一個函數來創建上述數據圖:

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() 

我然後使用該函數在一個by調用過的每個級別運行功能在Site因素:

by(sum_stats, sum_stats$Site, plot_func) 

我得到以下形式的27個圖:

enter image description here

但是,所有的標題都是一樣的。我怎樣才能讓每個標題反映它正在繪製的因子水平?這可以在繪圖功能內完成嗎?

感謝

+0

@MrFlick這似乎很好。謝謝你,它開始做我的頭! –

回答

2

現在你正在設置使用原始data.frame標題,並沒有通過數據的子集給你工作。如果所收到的子集中的所有網站都相同,則可以使用第一個作爲標題。使用

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