3

I have a dataframe "test" with column1 - dates (timelines), column2 - 1 OR 0 variable (specific periods of time - named binary) and column3 (GDP) - GDP growth rate. I would like to plot a ggplot with GDP growth rate over time and additionally, I would like to shade areas that have 1 in column 2. Lets say dates between 1972 - 1977 and 1990 - 1992 all have 1 in column2 and I would like this timespan to be shaded in grey on the chart. Formerly, I created a data table such as:

"Peak, Trough
1972-01-01, 1977-01-01
1990-01-01, 1992-01-01"), sep=',',
colClasses=c('Date', 'Date'), header=TRUE)

and used it

ggplot(data=filter(test),aes(x=test$timelines,y=test$GDP))+
  geom_rect(data=filter(period.df,year(Peak)>1959), inherit.aes=F, aes(xmin=Peak, xmax=Trough, ymin=-Inf, ymax=+Inf), fill='darkgray') 

but now the binary (column2) variable can change and I need to supply the ggplot an appropriate timespans so that it can shade areas marked with 1. Thank you!!

sample screenshot

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Michael
  • 57
  • 6
  • Could you please show a sample of the expected plot? – NelsonGon Aug 12 '19 at 15:10
  • 1
    definitely @NelsonGon, how can I add a picture here? – Michael Aug 12 '19 at 15:17
  • 2
    Possible duplicate of [Using geom\_rect for time series shading in R](https://stackoverflow.com/questions/29648907/using-geom-rect-for-time-series-shading-in-r) – Jindra Lacko Aug 12 '19 at 18:26
  • consider `ggplot::geom_rect()`, as discussed in https://stackoverflow.com/questions/29648907/using-geom-rect-for-time-series-shading-in-r – Jindra Lacko Aug 12 '19 at 18:27
  • 2
    [Don't use `$` inside `aes`](https://stackoverflow.com/questions/32543340/issue-when-passing-variable-with-dollar-sign-notation-to-aes-in-combinatio). What are you intending with `filter(test)`, since you don't actually have any filter conditions? – camille Aug 12 '19 at 18:49
  • @camille it might be a bit redundant there, thats true. – Michael Aug 13 '19 at 10:58
  • Calling `filter` without any filtering conditions I guess is redundant and might not cause problems beyond making it more difficult to read, but the `$` inside `aes` will very likely cause errors – camille Aug 13 '19 at 14:47

0 Answers0