【问题标题】:R for loop and a series of plots: obtaining always the same plotR for循环和一系列图:始终获得相同的图
【发布时间】:2012-10-18 14:42:17
【问题描述】:

我正在尝试从以下数据集和 for 循环中获取一系列图:

> head(all5new[c(6,70,22:23)])#This is a snapshot of my dataset. There is more species, see below.
   setID         fishery blackdog smoothdog
11     1 TRAWL-PAND.BOR.        0         0
12     1 TRAWL-PAND.BOR.        0         0
13     1   TRAWL-REDFISH        0         0
14     1 TRAWL-PAND.BOR.        0         0
21    10 TRAWL-PAND.BOR.        0         0
22    10 TRAWL-PAND.BOR.        0         0

> elasmo #This is the list of the species for which I would like to have individual barplots
 [1] "blackdog"     "smoothdog"    "spinydog"     "mako"         "porbeagle"   
 [6] "blue"         "greenland"    "portuguese"   "greatwhite"   "mackerelNS"  
[11] "dogfish"      "basking"      "thresher"     "deepseacat"   "atlsharp"    
[16] "oceanicwt"    "roughsagre"   "dusky"        "sharkNS"      "sand"        
[21] "sandbar"      "smoothhammer" "tiger"        "wintersk"     "abyssalsk"   
[26] "arcticsk"     "barndoorsk"   "roundsk"      "jensensk"     "littlesk"    
[31] "richardsk"    "smoothsk"     "softsk"       "spinysk"      "thorny"      
[36] "whitesk"      "stingrays"    "skateNS"      "manta"        "briersk"     
[41] "pelsting"     "roughsting"   "raysNS"       "skateraysNS"  "allSHARK"    
[46] "allSKATE"     "PELAGIC"     

这是我的 for 循环。当我为一个物种运行它时,代码运行良好,但是当我为所有物种运行它时,我总是得到相同的条形图。我知道它必须只是在代码中某处添加例如 [[i]] 的快速修复,但我尝试了不同的东西但没有任何成功。

for (i in elasmo) {

  # CALUCLATE THE CATCH PER UNIT OF EFFORT (KG/SET) FOR ALL SPECIES FOR EACH FISHERY
  test<-ddply(all5new,.(fishery),summarize, sets=length(as.factor(setID)),LOGcpue=log((sum(i)/length(as.factor(setID)))))

  #TAKE THE FIRST 10 FISHERY WITH THE HIGHEST LOGcpue
  x<-test[order(-test$LOGcpue)[1:10],]

  #REORDER THE FISHERY FACTOR ACCORDINGLY (FOR GGPLOT2, TO HAVE EACH LEVEL IN ORDER)
  list<-x$fishery
  x$fishery <- factor(x$fishery, levels =list)

  #BAR PLOT
  graph<-ggplot(x, aes(fishery,LOGcpue)) + geom_bar() + coord_flip() +
  geom_text(aes(label=sets,hjust=0.5,vjust=-1),size=4,angle = 270)

  #SAVE GRAPH IN NEW DIR
  ggsave(graph,filename=paste("barplot",i,".png",sep=""))
}

这是融化后我的数据集的一个子集:mydata。

> data.melt<-melt(all5new, id.vars=c("tripID","setID","fishery"), measure.vars = c(22:23))
> head(data.melt);dim(data.melt)
  tripID setID         fishery variable value
1      1     1 TRAWL-PAND.BOR. blackdog     0
2      1     1 TRAWL-PAND.BOR. blackdog     0
3      1     1   TRAWL-REDFISH blackdog     0
4      1     1 TRAWL-PAND.BOR. blackdog     0
5      1    10 TRAWL-PAND.BOR. blackdog     0
6      1    10 TRAWL-PAND.BOR. blackdog     0
[1] 350100      5

【问题讨论】:

  • 我认为第一个 ddply 语句中的 i 可能没有按照您希望的方式进行评估...我可能会尝试创建一个 explicit 函数对于ddply 并拨打browser() 电话,看看那里发生了什么...
  • 在for 循环中使用ddply 效率极低。 @BenBolker 是对的,i 不会正确传递。给我们可重复的例子,也许我们可以提供帮助。我建议你 melt 数据集所以 species 是一个列,然后你可以通过 (fishery, species) ddply。情节也可以进入列表,因此您也可以llply该部分。

标签: r for-loop ggplot2


【解决方案1】:

这是我用于生成大量图表的工作流程,适用于您的数据集(或者,我对它的解释)。我认为这是plyr 力量的一个很好的例证。对于您的应用程序,我认为计算时间并不重要。对你来说更重要的是生成易于阅读的代码,我认为 plyr 对此有好处。

#Load packages
require(plyr)
require(reshape)
require(ggplot2)

#Recreate your data set, with only two species
setID <- rep(1:5, each=4, times=1)
fishery <- gl(10, 2)
blackdog <- sample(1:5, size=20, replace=TRUE)
smoothdog <- sample(1:5, size=20, replace=TRUE)
df <- data.frame(setID, fishery, blackdog, smoothdog)

#Melt the data frame
dfm <- melt(df, id.vars <- c("setID", "fishery"))

#Calculate LOGcpue for each fish at each fishery

cpueDF <- ddply(dfm, c("fishery", "variable"), summarise, LOGcpue = log(sum(value)/length(value)))

#Plot all the data in one (potentially huge) faceted plot.
#(I often use huge plots like this for onscreen analysis 
#  - obviouly it can't be printed in practice, but you can get a visual overview of the data)
ggplot(cpueDF, aes(x=fishery, y=LOGcpue)) + geom_bar() + coord_flip() + facet_wrap(~variable)
ggsave("giant plot.pdf", height=30, width=30, units="in")

#Print each plot individually to screen, and save it, and put it in a list
printGraph <- function(df) {
  p <-ggplot(df, aes(x=fishery, y=LOGcpue)) +
geom_bar() + coord_flip()
  print(p)
  fn <- paste(df$variable[1], ".png")
  ggsave(fn)
  printGraph <- p
}
plotList <- dlply(cpueDF, .(variable), printGraph)

#Now pick out the top n fisheries for each fish
cpueDFtopN <- ddply(cpueDF, .(variable), function(x) head(x[order(x$LOGcpue, decreasing=T),], n=5))
ggplot(cpueDFtopN, aes(x=fishery, y=LOGcpue)) + geom_bar() + 
  coord_flip() + facet_wrap(~variable, scales="free")

【讨论】:

  • 谢谢@DrewSteen,当我尝试使用 cpueDF 时,我得到了 LOGcpue 的 NA,有什么想法吗?我添加了我的数据的一个子集。我需要计算每个渔业的每个物种的公斤/组。然后我只想按降序绘制 LOGcpue 最高的前 10 个渔业。
  • 对此感到抱歉 - 这是因为 count() 并没有像我想象的那样工作。将在几个小时内修复。顺便说一句,请通过键入 dput(mydata) 并粘贴到代码窗口中来输入您的数据 - 这样我就可以直接粘贴到我的 R 控制台中。
  • 抱歉,以前从未执行过此 dput 命令,这是要粘贴的很多行,即 350100!这是人们通常做的事情吗?
  • 获取数据的一个子集;例如我的数据[1:20, 1:10]。但此时我不确定是否有必要,我即将发布完整的 sln。
猜你喜欢
  • 2016-07-12
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 2021-04-17
相关资源
最近更新 更多