r:将变量名作为字符串传递

ohtdti5x  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(132)

我需要生成很多类似格式的直方图,所以我想把具体的图代码做成一个函数,我的函数是:

DistribGraph <- function(VectorToGraph, VarName = "var", title,
                         limit_lo = 50, limit_hi = 150, bin_width = 5, tik_width = 10) {
  
  data <- data.frame(VarName = VectorToGraph)
  
  graph <- ggplot(data) +
    aes(x = VarName) +
    ggtitle(title) + 
    scale_x_continuous(breaks = seq(limit_lo, limit_hi, tik_width), 
                       limits = c(limit_lo, limit_hi)) +
    geom_histogram(aes(y = after_stat(density)),
                   binwidth = bin_width, 
                   fill = "#69b3a2", 
                   boundary = limit_lo,
                   color = "#e9ecef",  
                   alpha = 0.9) +
    theme(plot.title = element_text(size = 10, face = "bold")) +  
    stat_function(fun = dnorm, args = list(mean = mean(VectorToGraph), 
                                           sd = sd(VectorToGraph)))
  
  return(graph)
}

打个比方,

DistribGraph(mtcars$mpg, "mpg", "mpg - Histogram", 10, 35, 1, 5)

唯一的问题是x轴名称是“VarName”,而不是“mpg”

我怀疑问题是在data.frame(VarName = VectorToGraph)aes(x = VarName)中,因为R采用变量的名称而不是变量的内容......
问题是:如何将变量名传递为字符串,而不是包含字符串的变量?

q3aa0525

q3aa05251#

到目前为止,您还没有传递标签名称。只需添加labs(x=VarName)+,您将获得所需的输出:

DistribGraph <- function(VectorToGraph, VarName = "var", title,
                         limit_lo = 50, limit_hi = 150, bin_width = 5, tik_width = 10) {
  
  data <- data.frame(VarName = VectorToGraph)
  
  graph <- ggplot(data) +
    aes(x = VarName) +
    ggtitle(title) + 
    scale_x_continuous(breaks = seq(limit_lo, limit_hi, tik_width), 
                       limits = c(limit_lo, limit_hi)) +
    geom_histogram(aes(y = after_stat(density), x = VarName),
                   binwidth = bin_width, 
                   fill = "#69b3a2", 
                   boundary = limit_lo,
                   color = "#e9ecef",  
                   alpha = 0.9) +
    labs(x=VarName)+
    theme(plot.title = element_text(size = 10, face = "bold")) +  
    stat_function(fun = dnorm, args = list(mean = mean(VectorToGraph), 
                                           sd = sd(VectorToGraph)))
  
  return(graph)
}

DistribGraph(mtcars$mpg, "mpg", "mpg - Histogram", 10, 35, 1, 5)

相关问题