0

I draw a plot with this code:

require(zoo)
raw_df1_zoo <-zoo(raw_df1[raw_df1$ID == '300',]$`N`, order.by = raw_df1[raw_df1$ID == '300',]$Date)

plot(raw_df1_zoo, xlab = "Date", ylab = "N")

As you see, I draw a plot for data with ID equal 300. But I want to draw facets of 4 plots for data with ID's from this list:

c(300, 301, 302, 303)

How could i do that? Im new in R)

french_fries
  • 1,149
  • 6
  • 22
  • I should have asked before answering. Please include in your post the output of `dput(head(raw_df1))` Per `r` tag (hover to see): please provide [minimal and reproducible example(s)](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5965451) along with the desired output. Use `dput()` for data. – Parfait May 05 '20 at 16:53

2 Answers2

1

Not sure that I understood, but try :

par(mfrow=c(2,2))
for (i in c(300, 301, 302, 303)){
  raw_df1_zoo <-zoo(raw_df1[raw_df1$ID == i,]$`N`, order.by = raw_df1[raw_df1$ID == paste0(i,'T'),]$Date)
  plot(raw_df1_zoo, xlab = "Date", ylab = "N")
}

assuming 300T should be adapted to 301T,302T,...

Levon Ipdjian
  • 786
  • 7
  • 14
0

Consider by to slice your data by factor(s). Even paste ID into plot's main title:

# SET UP PLOTS BY 2 ROWS AND 2 COLUMNS
par(mfrow=c(2, 2))                                 

# RUN GROUPING ITERATION
output <- by(raw_df1, raw_df1$ID, function(sub) {
   sub_zoo <-zoo(sub$`N`, order.by = sub$date)
   plot(raw_df1_zoo, xlab = "Date", ylab = "N",
        main = paste(sub$ID[[1]], "of N Series"))
})

To demonstrate with random, seeded data:

set.seed(552020)

raw_df1 <- data.frame(
  group = sort(rep(c("sas", "stata", "spss", "python", "r", "julia"), 90)),
  date = rep(seq.Date(Sys.Date() - 89, Sys.Date(), by="day"), 6),
  N = rnorm(540)
)    

par(mfrow=c(2, 3))
output <- by(raw_df1, raw_df1$group, function(sub) {
   sub_zoo <- zoo(sub$`N`, order.by = sub$date)
   plot(raw_df1_zoo, xlab = "Date", ylab = "N",
        main = paste0(sub$group[[1]], " of N Series"))
})

enter image description here

Parfait
  • 104,375
  • 17
  • 94
  • 125
  • I don't understand what you mean by "Even paste ID into plot's main title" – french_fries May 05 '20 at 16:40
  • Its not quite that, cause in your data frame all groups are included in drawing plots, but in my its just a part – french_fries May 05 '20 at 16:43
  • Carefully read the solution. `by` creates the groups from the original, *single* dataset and then plots each. And in example demo, `group` (counterpart of your `ID`) is included in each plot's title with `paste0`. See last argument of `plot`. – Parfait May 05 '20 at 16:55
  • sub$ID[[c(300, 301, 302, 303)]] ? – french_fries May 05 '20 at 17:13
  • Please post `dput` of your data above or mock a reproducible version. If these 4 IDs are out of many IDs then use `%in%` filter prior to calling `by` or use `for` loop as suggested above. – Parfait May 05 '20 at 17:25