我正在尝试根据两个因素DF
子集编写一个自动绘图生成器。
我一步一步地解释自己。这是我DF
的一部分:
YEAR RN DATE NOM SITE LONG SP SUMNB NB100 DIFF IA
2001 RNN066 2001-04-26 RAVIN DE VALBOIS RNN066-Valbois Pel Humbert 231 Aphantopus hyperantus (Linnaeus, 1758) 0.000000 0.0000000 NA NA
2001 RNN066 2001-07-04 RAVIN DE VALBOIS RNN066-Valbois Pel Humbert 231 Aphantopus hyperantus (Linnaeus, 1758) 4.000000 1.7316017 69 59.740260
2001 RNN066 2001-07-17 RAVIN DE VALBOIS RNN066-Valbois Pel Pogo 231 Aphantopus hyperantus (Linnaeus, 1758) 2.000000 0.8658009 13 5.627706
2001 RNN066 2001-08-01 RAVIN DE VALBOIS RNN066-Valbois Pel Pogo 231 Aphantopus hyperantus (Linnaeus, 1758) 2.000000 0.8658009 15 6.493506
2001 RNN066 2001-10-03 RAVIN DE VALBOIS RNN066-Valbois Pel Humbert 231 Aphantopus hyperantus (Linnaeus, 1758) 0.000000 0.0000000 63 0.000000
2001 RNN066 2001-04-26 RAVIN DE VALBOIS RNN066-Valbois Pel Humbert 231 Aporia crataegi (Linnaeus, 1758) 0.000000 0.0000000 NA NA
2001 RNN066 2001-06-04 RAVIN DE VALBOIS RNN066-Valbois Pel Humbert 231 Aporia crataegi (Linnaeus, 1758) 4.000000 1.7316017 39 33.766234
2001 RNN066 2001-06-21 RAVIN DE VALBOIS RNN066-Valbois Pel Pogo 231 Aporia crataegi (Linnaeus, 1758) 16.000000 6.9264069 17 58.874459
2001 RNN066 2001-06-28 RAVIN DE VALBOIS RNN066-Valbois Pel Humbert 231 Aporia crataegi (Linnaeus, 1758) 16.000000 6.9264069 7 24.242424
2001 RNN066 2001-07-04 RAVIN DE VALBOIS RNN066-Valbois Pel Pogo 231 Aporia crataegi (Linnaeus, 1758) 2.000000 0.8658009 6 2.597403
我想为每个SP+SITE组合画一个YEAR~IA的图。我尝试应用函数,但由于晦涩的原因,它没有将我的 ggplot() 视为函数,并且 ddply() 不适合。
我会得到大量的情节(数千个),所以我需要正确设置它们。这就是为什么我想在情节的标题上写下 SITE 名称和 SP 名称,并根据 SITE 和 SP 使用名称保存每个地块。我命名每个因子的当前值的所有尝试都失败了。
我正在考虑循环,但这可能是一个耗时的命令。
编辑:
这是我的尝试:
tapply(SUBTOT$SITE,SUBTOT$SP,function(x){
ggplot(SUBTOT, aes(YEAR, IA))+
geom_point(size=3) +
geom_line(size=1) +
ggtitle("IA Evolution")+
theme_bw()+
theme(legend.direction ="vertical",legend.position = "bottom")+
guides(color=guide_legend(ncol=2))
} )
它针对每个 SP 运行,但不针对每个 SITE 值运行,从而产生相同的绘图。
在你的函数function(x){ ... }
中,你从来没有真正调用过x
,而是使用原始数据SUBTOT
。这就是为什么你多次得到相同的情节的原因。我也不认为tapply
是合适的功能。我会改用plyr
包中的dlply
。这是我的解决方案:
require(plyr)
p <- dlply(SUBTOT, .(SITE, SP),function(x){
ggplot(x, aes(YEAR, IA))+
geom_point(size=3) +
geom_line(size=1) +
ggtitle("IA Evolution")+
theme_bw()+
theme(legend.direction ="vertical",legend.position = "bottom")+
guides(color=guide_legend(ncol=2))
})
# only run the following if you want to actually print all your (thousands) of plots.
# you may want to save them (ggsave) instead.
lapply(p, print)