Обновление заголовка на графиках в соответствии с переменной, переданной в функции?

#r #ggplot2

#r #ggplot2

Вопрос:

Когда я вызываю функцию индивидуально с фреймом данных и конкретным столбцом напрямую, функция ведет себя так, как ожидалось, и заголовок графика обновляется при каждой новой переменной, передаваемой функции, но когда вы пытаетесь вызвать функцию из другой функции, и заголовки графиков не обновляются вместо переменнойимя «NA».

Я не могу исправить эту проблему? Кто-нибудь может помочь мне понять и исправить эту проблему?

введите описание изображения здесь

     plot_2 = function(df, xin, ...){
 
 plot1 = ggplot(df , aes(xin, fill = DEATH_EVENT)) 
 geom_histogram(...) 
 labs(title = paste(strsplit(deparse(xin),"$", 1)[[1]][2]," during heart attack and consequences"),y = "Count", x = strsplit(deparse(xin),"$", 1)[[1]][2]) 
 theme(legend.position = "top") 
 scale_fill_discrete(name = "Deaths due to heart attack", labels = c("No", "Yes")) 
 theme_dark()

 plot2 = ggplot(df, aes(DEATH_EVENT, xin)) 
 geom_violin(alpha = 0.5, aes(color = DEATH_EVENT)) 
 geom_jitter(alpha = 0.3, aes(color = DEATH_EVENT)) 
 labs(title = paste(strsplit(deparse(xin),"$", 1)[[1]][2]," during heart attack and   consequences"), y = strsplit(deparse(xin),"$", 1)[[1]][2], x = "Deaths due to heart attack")  # To give labels to the plot
 scale_x_discrete(labels = c("No", "Yes"))  # Specified the names of the levels of x axis ticks.
 coord_flip()  # Flipped the axes
 theme_light()
  
return(ggarrange(plot1,plot2, nrow = 2)) # To get the plots in single window having 1 column and 2 rows

} #plot_num


summary_predictors3 = function(df, xin, group, ...){
  
  summary_expl_variable_and_plot = list()
  class(summary_expl_variable_and_plot) = "summary_stats"
  
   if(is.factor(xin) == FALSE){
  
   summary_expl_variable_and_plot$plot = plot_2(df, xin, ...)
   summary_expl_variable_and_plot$mean = tapply(xin, group, mean)
   summary_expl_variable_and_plot$median = tapply(xin, group, FUN=median)
   summary_expl_variable_and_plot$Q1 = tapply(xin, group, FUN=quantile, 0.25)
   summary_expl_variable_and_plot$Q3 = tapply(xin, group, FUN=quantile, 0.75)
   summary_expl_variable_and_plot$IQR = summary_expl_variable_and_plot$Q1 - 
   summary_expl_variable_and_plot$Q3
  
   
   invisible(summary_expl_variable_and_plot)

   else{
    
    summary_expl_variable_and_plot$plot = plot_categorical_response(df, xin)
    invisible(summary_expl_variable_and_plot)

  }
    
  }

print.summary_stats <- function(variable){

  if(length(variable) > 1){

    print(variable$plot)
     
  } #if
  
  else print(variable$plot)

s = summary_predictors3(df= heart,heart$age, heart$DEATH_EVENT) # This doenst update the plots title

plot_2(heart, heart$age) # But if I call the function directly, it works fine
 

Комментарии:

1. Я ответил и надеюсь, что это было то, что вам нужно, потому что ваш пример сложный, и мы не можем воспроизвести, поскольку у нас нет данных. Было бы лучше использовать reprex и уменьшить сложность. Лучшие

Ответ №1:

Я бы принял rlang и сделал что-то вроде этого: где голые имена сначала преобразуются в вопрос, который мы сначала оцениваем в контексте data.frame с !! помощью оператора. И во второй раз в качестве строки, чтобы использовать ее в заголовке. надеюсь, это heps

 library(ggplot2)

curly_title <- function(df, xin) {
  xin <- enquo(xin)
  ggplot(df, aes(x = !!xin))  
    geom_histogram()  
    labs(title = paste("hist of", rlang::as_name(xin)))
}
curly_title(mtcars, mpg)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
 

Создано 2020-12-08 пакетом reprex (версия 0.3.0)