这是我的 df 的一部分:
CWRES ID AGE BMI WGT
3 0.59034000 1 37.5 20.7 64.6
4 1.81300000 1 37.5 20.7 64.6
5 1.42920000 1 37.5 20.7 64.6
6 0.59194000 1 37.5 20.7 64.6
7 0.30886000 1 37.5 20.7 64.6
8 -0.14601000 1 37.5 20.7 64.6
9 -0.19776000 1 37.5 20.7 64.6
10 0.74208000 1 37.5 20.7 64.6
11 -0.69280000 1 37.5 20.7 64.6
38 -2.42900000 1 37.5 20.7 64.6
39 -0.25732000 1 37.5 20.7 64.6
40 -0.49689000 1 37.5 20.7 64.6
41 -0.11556000 1 37.5 20.7 64.6
42 0.91036000 1 37.5 20.7 64.6
43 -0.24766000 1 37.5 20.7 64.6
44 -0.14962000 1 37.5 20.7 64.6
45 -0.45651000 1 37.5 20.7 64.6
48 0.53237000 2 58.5 23.0 53.4
49 -0.53284000 2 58.5 23.0 53.4
50 -0.33086000 2 58.5 23.0 53.4
51 -0.56355000 2 58.5 23.0 53.4
52 0.00883120 2 58.5 23.0 53.4
53 -1.00650000 2 58.5 23.0 53.4
80 0.85810000 2 58.5 23.0 53.4
81 -0.71715000 2 58.5 23.0 53.4
82 0.44346000 2 58.5 23.0 53.4
83 1.09890000 2 58.5 23.0 53.4
84 0.98726000 2 58.5 23.0 53.4
85 0.19667000 2 58.5 23.0 53.4
86 -1.32570000 2 58.5 23.0 53.4
89 -4.56920000 3 43.5 26.7 66.2
90 0.75174000 3 43.5 26.7 66.2
...
我想绘制这个:
for(i in names(tab3)[2:5]) {
df2 <- tab3[, c(i, "CWRES")]
p99 = ggplot(tab3) + geom_point(aes_string(x = i, y = "CWRES"))
print(p99)
}
问题是,如果我想更改 xlab,它不起作用,因为我正在使用 aes_string()
。
这不起作用:
names(tab3) = c("ID","age [years]","BMI (kg/m2)","body weight ,kg")
for(i in names(tab3)[2:5]) {
df2 <- tab3[, c(i, "CWRES")]
p99 = ggplot(tab3) + geom_point(aes_string(x = i, y = "CWRES"))
print(p99)
}
我还尝试了另一种方法:
namecol = c("ID","age [kgg]","BMI","bodyweight")
for(i in names(tab3)[2:5]) {
df2 <- tab3[, c(i, "CWRES")]
p99 = ggplot(tab3) + geom_point(aes_string(x = i, y = "CWRES")) +
ylab("CWRES") +
for(a in namecol[1:4]) {
xlab(namecol[a])
}
print(p99)
}
但它也不起作用。
我怎样才能让它发挥作用?
最佳答案
我认为关键是您需要在 aes_string
中语法上无效的名称周围加上反引号。将反引号放在引号内是我不知道的技巧。
在aes_string
存在之前,有this trick能够在函数中使用ggplot
。这将使您能够绕过(而不是解决)您遇到的问题。
这将涉及根据您的数据集 tab3
创建一个绘图函数,然后使用 lapply
遍历解释变量的名称。这里我将绘图函数命名为 plot1
。
names(tab3) = c("CWRES", "ID","age [years]","BMI (kg/m2)","body weight ,kg")
plot1 = function(variable) {
tab3$variable = tab3[,variable]
ggplot(tab3, aes(x = variable, y = CWRES)) +
geom_point() +
xlab(variable)
}
# Make a single plot
plot1(names(tab3)[3])
# Make all the plots; name object if want to save list
lapply(names(tab3)[2:5], function(x) plot1(x))
关于r - 使用 aes_string 在变量名称中添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26061184/