2015-10-02 78 views
0

我有一个数据集(A2),看起来像这样;如何在r中循环ggplot图形

Year Gear  Region Landings.t 
1975 Creel  Clyde  3.456 
1976 Creel  Clyde  20.531 
1977 Creel  Clyde  56.241 
1978 Creel  Clyde  43.761 
1975 Creel  Shetland 3.456 
1976 Creel  Shetland 10.531 
1977 Creel  Shetland 46.241 
1978 Creel  Shetland 33.761 

我使用下面的代码来生成一个线图;

ggplot(subset(A2,Region=="Clyde"),aes(x=Year,y=Landings.t,colour=Gear,group=Gear))+ 
    geom_line()+ 
    facet_grid(Gear~.,scales='free_y')+ 
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES")+ 
    theme(panel.background=element_rect(fill='white',colour='black'))+ 
    geom_vline(xintercept=1984) 

此刻我正在复制每个不同区域的代码,这使得我的脚本非常长。我想知道是否有一种方法循环代码来遍历每个区域并为每个区域生成一个图表?

我已经尝试使用前面的问题Loop through a series of qplots可用的答案,但是当我使用此代码时,它返回'二进制运算符的非数字参数'错误。

for(Var in names(A2$Region)){ 
print(ggplot(A2,[,Var],aes(x=Year,y=Landings.t,colour=Gear,group=Gear))+ 
geom_line()+ 
facet_grid(Gear~.,scales='free_y')+ 
ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES")+ 
theme(panel.background=element_rect(fill='white',colour='black'))+ 
geom_vline(xintercept=1984) 
} 
+0

退房这里的http://www.r- bloggers.com/ggplot2-graphics-in-a-loop/ – Keniajin

+0

'names(A2 $ Region)'将返回NULL。你可能想在那里“独一无二”。在'A2'后面还有''',我认为你想要子集。 – LyzandeR

+0

而你又错过了'print'的支架 – LyzandeR

回答

1
for(Var in unique(A2$Region)){ 
    print(
    ggplot(
     subset(A2, Region == Var), 
     aes(x = Year, y = Landings.t, colour = Gear, group = Gear) 
    )+ 
    geom_line() + 
    facet_grid(Gear ~ ., scales = 'free_y') + 
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES") + 
    theme(panel.background = element_rect(fill = 'white', colour = 'black'))+ 
    geom_vline(xintercept = 1984) 
) 
} 

或使用plyr包

libary(plyr) 
dlply(A2, ~Region, function(x){ 
    ggplot(
     x, 
     aes(x = Year, y = Landings.t, colour = Gear, group = Gear) 
    )+ 
    geom_line() + 
    facet_grid(Gear ~ ., scales = 'free_y') + 
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES") + 
    theme(panel.background = element_rect(fill = 'white', colour = 'black'))+ 
    geom_vline(xintercept = 1984) 
}) 

plyr可以很容易地拆分沿多个变量的数据集

dlply(A2, ~Region + Species, function(x){ 
    ggplot(
     x, 
     aes(x = Year, y = Landings.t, colour = Gear, group = Gear) 
    )+ 
    geom_line() + 
    facet_grid(Gear ~ ., scales = 'free_y') + 
    ggtitle("CLYDE LANDINGS BY GEAR TIME-SERIES") + 
    theme(panel.background = element_rect(fill = 'white', colour = 'black'))+ 
    geom_vline(xintercept = 1984) 
}) 
+0

谢谢你的工作:) –

+0

有没有办法把这个循环放在另一个循环中。我想要为每个物种拥有相同的地块,但每个地区都有相同的地块。你可以有两个'背对'的'satements? –

+0

看到我在底部的编辑 – Thierry