我有一个数据集(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)
}
退房这里的http://www.r- bloggers.com/ggplot2-graphics-in-a-loop/ – Keniajin
'names(A2 $ Region)'将返回NULL。你可能想在那里“独一无二”。在'A2'后面还有''',我认为你想要子集。 – LyzandeR
而你又错过了'print'的支架 – LyzandeR