【问题标题】:Generate plots from for loop with non-standard evaluation使用非标准评估从 for 循环生成图
【发布时间】:2020-03-24 23:05:56
【问题描述】:

我正在尝试使用ggplotR 中从for 循环生成图。

让我们创建一个数据集:

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

它提供以下错误:

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

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

在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' 被解释为字符向量,以便我能够控制循环中的比例?还是有另一种方法可以方便地从数据框中的不同列生成图?

【问题讨论】:

  • 我会 melt 并使用构面 - 这是更多 ggplot2 方式
  • 嘿 user213544,要扩展 @PoGibas 的 cmets,您可以熔化(或 pivot_longer() )df,然后只是 value_a、value_b 的子集 ...
  • 例如这样:df %>% pivot_longer(-time) %>% filter(name=="value_a") %>% ggplot()+geom_jitter(aes(x=time,y =值))
  • 我已修改标题以使其更易于搜索 - 希望这符合您的想法

标签: r for-loop ggplot2


【解决方案1】:

我同意 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 package (v0.3.0) 于 2019 年 11 月 29 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    相关资源
    最近更新 更多