【问题标题】:Getting Variable Names for X-Axis when Looping in ggplot?在ggplot中循环时获取X轴的变量名称?
【发布时间】:2021-02-24 22:12:39
【问题描述】:

我想知道是否有任何方法可以在每个图形的 x 轴上插入实际对应的变量。在我的实际数据集中,我有 15 个预测变量。因为它不是,对于每个图表,在轴上,我只是犯罪 crime[,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) 
} 

【问题讨论】:

  • 谢谢,刚刚修好。

标签: r for-loop ggplot2


【解决方案1】:

一种选择是根据索引获取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) 
   }

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

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) 
      }

【讨论】:

  • 谢谢!我以前没用过rlang。将对此进行更多探索。
【解决方案2】:

您可以遍历for 循环中的列名,并将它们与.data 中的.data 一起使用。

library(ggplot2)

for (col in names(crime)){ 
  print(ggplot(crime, aes(x = .data[[col]], y = y)) +  geom_point()) 
  Sys.sleep(2) 
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多