Why i can not use for loop add new labels in geom_text

I want to use for loop to add some label in ggplot object , but i could not find a useful way.
so i want to ask some help.

suppose i have a ggplot object(list)

and i have a df for get some value and label.

i use following code

ggplot_add_text _function = function(gg_data,label_data){
 for(i in 1:length(gg_data){
gg_data[[i]] <- gg_data[[i]] + geom_text(aes(x = 1, y = pull(label_data[i,1]),label = pull(label_data[i,2]))
}
return(gg_data)
}


but after run it , it can not show label, why this happen

I am not sure I understand what you are trying to do. Does the code below do what you want? I found I could control the geom_text properly if I changed its data. If I tried to assign values within the aes(), only the last values were used.

library(ggplot2)
library(tibble)
DF <- tibble(X=1:4,Y=2:5)
DF2 <- tibble(X=1:4,Y=12:15)
DFP <- ggplot(DF,aes(X,Y))+geom_point()
DFP2 <- ggplot(DF2,aes(X,Y))+geom_point()
labels <- tibble(VY=c(3,13),VL=c("A","B"))
gg <- list(DFP,DFP2)


ggplot_add_text_function = function(gg_data,label_data){
  for(i in 1:length(gg_data)){
    gg_data[[i]] <- gg_data[[i]] + geom_text(aes(x = 1, y = VY,label = VL),
                                             data=labels[i,])
  }
  return(gg_data)
}
gg2 <- ggplot_add_text_function(gg,labels)
gg2[[1]]

gg2[[2]]

Created on 2022-10-30 with reprex v2.0.2

1 Like

Thank you for your help . I would learn it .

This topic was automatically closed 7 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.