Iterate through a list of functions and add to a plot

I’m new to R!

I have a data frame with dates and measurements:

mydata= Col1(date) Col2(diameter)

df<- mydata

I also have a list of functions(f), these functions check for patterns:

Function_list<- c(f1,f2,f3,f4,f5)

I’ve plotted mydata using ggplot2(geom_point), I’d now like to iterate through the list of functions f1 then f2… f5 and if any of the functions (can be more than 1) detect a pattern for the given data(mydata) highlight these diameter points on my geom_point plot.

How would I approach this problem, I’ve tried the annotate function, which allows me to label/annotate within ggplot2 but I’m not sure how to loop through the functions and add to my plot?

Can you paste a small part of your DF using this code? dput(head(YOURDF, 20)) and the code to generate the figures?

One approach would be to do all of your checks prior to plotting, creating a data set of outcomes you can join to your original data. Then, you can add the outcomes to the plot using geom_text(). Below is an example.


mydata = data.frame(
  date = seq.Date(from = as.Date('2022-10-01'),
                  to = as.Date('2022-10-14'),
                  by = 'days'), 
  diameter = sample(x= 1:25, size = 14, replace = T)

# check for small diameters
f1 = function() {
  mydata %>%
    filter(diameter <= 5) %>%
    mutate(description = 'small')

# check for large diameters
f2 = function() {
  mydata %>%
    filter(diameter >= 20) %>%
    mutate(description = 'large')

Function_list = c(f1, f2)

# run through all checks to create a data frame of outcomes
outcomes = lapply(Function_list, function(f) f()) %>%

# join to the original data
mydata = left_join(mydata, outcomes)
#> Joining, by = c("date", "diameter")

# create plot with text
ggplot(mydata, aes(x = date, y = diameter)) +
  geom_point() +
  geom_text(aes(label = description), hjust = -0.2)

Created on 2022-10-14 with reprex v2.0.2.9000

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.