首页 > 解决方案 > 使用非标准评估从 for 循环生成图

问题描述

我正在尝试使用ggplotin从 for 循环生成图R

让我们创建一个数据集:

# Libraries
library(tidyverse)

# Set seed
set.seed(123)

# Create data frame
df <- data.frame(
  time = c( rep(1,20), rep(2, 20), rep(3, 20) ), 
  value_a =c(rnorm(n = 60, mean = 50, sd = 10)),
  value_b =c(rnorm(n = 60, mean = 50, sd = 10)),
  value_c =c(rnorm(n = 60, mean = 50, sd = 10))
)

我可以使用ggplot.

ggplot(data = df) +
  geom_jitter(aes(x = time, y = value_a), position = position_jitter(width = 0.1)) + 
  scale_y_continuous(limits = c(0, 100))

在此处输入图像描述

接下来,我想为数据框的每一列生成这些图(x 轴为时间,y 轴为 value_n)。我认为 for 循环可以解决问题:

for(i in colnames(df)[-1]){
  print(
    ggplot(df_a, aes(x= time, y = i)) +
      geom_jitter(position=position_jitter(width=0.1)) +
      scale_y_continuous(limits = c(0,100))
  )
}

它提供以下错误:

错误:提供给连续刻度的离散值

出现错误是因为ifor 循环中的 from 被视为字符向量,并且我(逻辑上)不能为离散值提供连续比例。

在for循环外重现错误:

ggplot(df_a, aes(x= time, y = "value_a")) + # value_a is provided as character vector
  geom_jitter(position=position_jitter(width=0.1)) +
  scale_y_continuous(limits = c(0,100))

问题

有没有办法防止 'value_a' 被解释为字符向量,以便我能够控制循环中的比例?还是有另一种方法可以方便地从数据框中的不同列生成图?

标签: rfor-loopggplot2

解决方案


我同意 PoGibas 的评论 - 重塑为长格式并使用facet可能是更好的方法。但是,如果您需要它来创建不同的绘图/图像等,请eval(sym(i))改用,如下所示:

library(tidyverse)

# Set seed
set.seed(123)

# Create data frame
df <- data.frame(
  time = c( rep(1,20), rep(2, 20), rep(3, 20) ), 
  value_a =c(rnorm(n = 60, mean = 50, sd = 10)),
  value_b =c(rnorm(n = 60, mean = 50, sd = 10)),
  value_c =c(rnorm(n = 60, mean = 50, sd = 10))
)

for(i in colnames(df)[-1]){
  print(
    ggplot(df, mapping = aes(x= time, y = eval(sym(i)))) +
      geom_jitter(position=position_jitter(width=0.1)) +
      scale_y_continuous(limits = c(0,100)) +
      labs(y = i) #added automatic y-label 

  )
}

reprex 包(v0.3.0)于 2019-11-29 创建


推荐阅读