首页 > 解决方案 > 在ggplot中循环时获取X轴的变量名称?

问题描述

我想知道是否有任何方法可以在每个图形的 x 轴上插入实际对应的变量。在我的实际数据集中,我有 15 个预测变量。因为它不是,对于每个图表,在轴上,我只是犯罪犯罪[,i]。

谢谢!

这是一个最小的可重现示例:

y<- c(1,5,6,2,5,10) # response 
x1<- c(2,12,8,1,16,17) # predictor 
x2<- c(2,14,5,1,17,17)

crime <- data.frame(x1,x2,y)

for (i in 1:ncol(crime)){ 
  print(ggplot(crime, aes(x = crime[, i], y = y))+
    geom_point()) 
  Sys.sleep(2) 
} 

标签: rfor-loopggplot2

解决方案


一种选择是names根据索引获取 ,然后转换为symbol 并评估 ( !!)

for (i in 1:2){ # the first two columns are the 'x' columns
   print(ggplot(crime, aes(x = !! rlang::sym(names(crime)[i]), y = y))+
     geom_point()) 
     Sys.sleep(2) 
   }

或者另一种选择是在添加层的同时保留 OP 的代码xlab

for (i in 1:2){ # the first two columns are the 'x' columns
   print(ggplot(crime, aes(x = crime[,i], y = y))+
          geom_point() +
          xlab(names(crime)[i])) 
    Sys.sleep(2) 
      }

推荐阅读