r - 使用非标准评估从 for 循环生成图
问题描述
我正在尝试使用ggplot
in从 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))
)
}
它提供以下错误:
错误:提供给连续刻度的离散值
出现错误是因为i
for 循环中的 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' 被解释为字符向量,以便我能够控制循环中的比例?还是有另一种方法可以方便地从数据框中的不同列生成图?
解决方案
我同意 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 创建
推荐阅读
- mongodb - 在 mac os 10.15 for php7 上安装 mongodb
- android - 如何从 viewpager 的片段中的 sqlite 检索一行?
- dotnetnuke - 没有堆栈跟踪的 DNN PageLoadException
- python - Python:你能动态获取函数要返回的变量数量吗?
- java - writeBytes 放入 CR
- java - 有没有办法在没有 RBAC 的情况下获取集群中的所有 pod?
- javascript - Vue Native 的全局样式
- json - Angular 8 - 比较对象内的数组(JSON)的更好方法是什么?
- tsql - 这是处理存储过程中可选参数的好方法吗?
- c - 使用修饰符时的 VT100 数字小键盘转义码(ctrl/shift/alt)