i have a data frame with dates and values :
n = 1000
date = seq(as.Date("2022/1/1"), by = "day", length.out = n)
value = rnorm(n,0,1)
df = tibble(date,value);df
how can i ggplot this data frame and to plot in the geom_line or geom_point two arrows pointing the maximum value and the minimum value of the value variable ?
ggplot(data =df, aes(x = date,y=value)) +
geom_point()
ggplot(data =df, aes(x = date,y=value)) +
geom_line()
Any help ?
>Solution :
It’s easiest to create a dataframe of the data for the annotations and then add it to the plot.
Here I make maxmin_df, which contains the details of the maximum and minimum values, and then add a geom_segment() to add them to the ggplot().
You’ll need to decide on the look of the line and arrows.
max_df <- tibble(y = max(df$value),
yend = y,
x = df$date[which(df$value == y)] + lubridate::days(5),
xend = x + lubridate::days(50))
minmax_df <- bind_rows(max_df,
c(tibble(y = min(df$value),
yend = y,
x = df$date[which(df$value == y)] + lubridate::days(5),
xend = x + lubridate::days(50))
)
)
ggplot(data = df, aes(x = date,y=value)) +
geom_point() +
geom_segment(data = minmax_df, aes(x = xend, xend = x, y = y, yend = yend), colour = "red", arrow = arrow())
