Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i annotate with arrows the maximum and the minimum of ggplot in R?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading