1

I have to plot the same graph a couple of times with different rectangles.

head(df)

DATA                      n
  <date>              <int>
1 2018-01-02            243
2 2018-01-03            243
3 2018-01-04            221
4 2018-01-05            211
5 2018-01-06             35
6 2018-01-07             30

head(rectangles)

channel                                    begin      end       
   <chr>                                      <date>     <date>    
 1 aaaaaaaaaaaaa                              2018-09-28 2018-12-28
 2 bbbb                                       2018-08-31 2018-10-31
 3 cccccccccccccc                             2018-08-31 2018-10-31
 4 aaaaaaaaaaaaaaaaaaaaaaa                    2018-08-31 2018-10-31
 5 ddddddddddddddddddddddddddddddd            2018-08-31 2018-10-31

What I have done so far to have many plots with the same data of df but with the unique rectangles$channels:

unique_rectangles <- unique(rectangles$channel)
for (rect in unique_rectangles) {
  plot <- ggplot(df, aes(x = DATA, y =n)) + 
    geom_rect(data = subset(rectangles, rectangles$channel==unique_rectangles[ret]), aes(xmin = begin, xmax = end, ymin = -Inf, ymax = +Inf), inherit.aes = FALSE, fill = 'red', alpha = 0.2) +
    geom_line() + 
    ggtitle(paste(unique_rectangles[ret])) 
  print(plot)}

But all I got is:

Error: Aesthetics must be either length 1 or the same as the data (1): xmin, xmax

What can I do to have the multiples plots?

Wash Muniz
  • 35
  • 5
  • 1
    Can you please share your data in a more [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) such as a `dput()`. It makes it easier to copy/paste the data in R for testing. What what is `ret` here? Since are already iterating over the unqiue values I think you want just `rect` where you have `unique_rectangles[ret]` (both in the subset and ggtitle) – MrFlick Mar 10 '20 at 19:10
  • 2
    Why not just use facet_wrap(~channel)? – William Gearty Mar 10 '20 at 19:30
  • Faceting worked. Thank you @WilliamGearty – Wash Muniz Mar 10 '20 at 19:40
  • I see a couple problems with your code. (a) Typo: you use `ret` instead of `rect`. (b) You use `for(rect in unique_rectangles)`, so `rect` will be `"aaaa"` then `"bbbb"`..., but then you use `rectangles$channel==unique_rectangles[ret]`, when you need `rectangles$channel==rect` (since `rect` already takes the value you need). That is, the code in your loop is written as if your loop was set up `for(i in 1:length(unique_rectangles))`. – Gregor Thomas Mar 10 '20 at 20:23

0 Answers0