Reputation: 1
I am a newie here, sorry for not writing the question right :p
1, the aim is to plot a graph about the mean NDVI value during a time period (8 dates were chosen from 2019-05 to 2019-10) of my study site (named RB1). And plot vertical lines to show the date with a grass cutting event.
2, Now I had calculated the NDVI value for these 8 chosen dates and made a CSV file. (PS. the "cutting" means when the grassland on the study site has been cut, so the corresponding dates should be show as a vertical line, using geom_vline)
infor <- read_csv("plotting information.csv")
infor
# A tibble: 142 x 3
date NDVI cutting
<date> <dbl> <lgl>
1 2019-05-12 NA NA
2 2019-05-13 NA NA
3 2019-05-14 NA NA
4 2019-05-15 NA NA
5 2019-05-16 NA NA
6 2019-05-17 0.787 TRUE
# ... with 132 more rows
3, the problem is, when I do the ggplot, first I want to keep the x-axis as the whole time period (2019-05 to 2019-10) but of course not show all dates in between, otherwise there will be way too much dates show on the x-axis). So, I do the scale_x_discrte(breaks=, labels=)
to show the specific dates with NDVI values.
Second I also want to show the dates that the grasses were cut geom_vline
.
BUT, it seems like the precondition for scale_x_discrte
is to factor
my date, while the precondition for geom_vline
is to keep the date as nummeric
.
these two calls seems to be contradictory.
y1 <- ggplot(infor, aes(factor(date), NDVI, group = 1)) +
geom_point() +
geom_line(data=infor[!is.na(infor$NDVI),]) +
scale_x_discrete(breaks = c("2019-05-17", "2019-06-18", "2019-06-26", "2019-06-28","2019-07-23","2019-07-28", "2019-08-27","2019-08-30", "2019-09-21"),
labels = c("0517","0618","0626","0628","0723","0728", "0827","0830","0921")))
y2 <- ggplot(infor, aes(date, NDVI, group = 1)) +
geom_point() +
geom_line(data=infor[!is.na(infor$NDVI),]))
when I add the geom_vline in the y1, vertical lines do not show on my plot: y1 + geom_vline
when I add it in the y2, vertical lines were showed, but the dates (x axis) are weird (not show as the y1 because we donot run the scale_x_ here) y2 + geom_vline
y1 +
geom_vline(data=filter(infor,cutting == "TRUE"), aes(xintercept = as.numeric(date)), color = "red", linetype ="dashed")
Would be appreciated if you can help! thanks in advance! :D
Upvotes: 0
Views: 400
Reputation: 448
I agree with the comment about leaving dates as dates. In this case, you can specify the x-intercept of geom_vline
as a date.
Given basic data:
df <- tribble(
~Date, ~Volume, ~Cut,
'1-1-2010', 123456, 'FALSE',
'5-1-2010', 789012, 'TRUE',
'9-1-2010', 5858585, 'TRUE',
'12-31-2010', 2543425, 'FALSE'
)
I set the date and then pull the subset for Cut=='TRUE'
into a new object:
df <- mutate(df, Date = lubridate::mdy(Date))
d2 <- filter(df, Cut == 'TRUE') %>% pull(Date)
And finally use the object to specify intercepts:
df %>%
ggplot(aes(x = Date, y = Volume)) +
geom_vline(xintercept = d2) +
geom_line()
Upvotes: 0