我的数据框(tab3)如下所示:
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
91 0.40935000 3 43.5 26.7 66.2
92 0.18340000 3 43.5 26.7 66.2
93 0.27399000 3 43.5 26.7 66.2
94 -0.23596000 3 43.5 26.7 66.2
95 -1.59460000 3 43.5 26.7 66.2
96 -0.03708900 3 43.5 26.7 66.2
97 0.68750000 3 43.5 26.7 66.2
98 -0.47979000 3 43.5 26.7 66.2
125 2.23200000 3 43.5 26.7 66.2
126 0.90470000 3 43.5 26.7 66.2
127 -0.34493000 3 43.5 26.7 66.2
128 -0.02114400 3 43.5 26.7 66.2
129 -1.08830000 3 43.5 26.7 66.2
130 -0.33937000 3 43.5 26.7 66.2
131 1.19820000 3 43.5 26.7 66.2
132 0.81653000 3 43.5 26.7 66.2
133 1.61810000 3 43.5 26.7 66.2
134 0.42914000 3 43.5 26.7 66.2
135 -1.03150000 3 43.5 26.7 66.2
...
我想绘制变量CWRES与ID,AGE,BMI和WGT。为此,我使用以下代码:
library(ggplot2)
plotloop <- function(x, na.rm = TRUE, ...) {
nm <- names(x)
for (i in seq_along(nm)) {
print(ggplot(x,aes_string(x = nm[i], y = nm[1])) +
geom_point()) }
}
plotloop(tab3)
然而,它还绘制了CWRES与CWRES,我不想绘制CWRES与CWRES。
我该怎么办?
提前致谢,
马里奥
答案 0 :(得分:0)
循环可能不是用ggplot绘制多个图的最佳方法。因此,我不会尝试修改您的代码,而是建议另一条路线。
您应首先融合data.frame,将其转换为长格式,只保留CWRES变量:
require(reshape2)
mDf <- melt(x, c("CWRES"))
现在您可以按如下方式创建绘图:
g <- ggplot(mDF,aes(x=CWRES,y=value))
g <- g + geom_point()
g <- g + facet_grid(.~variable)
g
这会创建一个刻面图,其中四个散点图彼此相邻。
如果你真的想绘制多个,我会按照以下步骤进行(基于上面的格式):
variables <- unique(mDF$variable)
for (v in variables)
{
print(ggplot(mDF[mDF$variable==v,],aes(x=CWRES,y=value)) + geom_point() )
}
答案 1 :(得分:-1)
最后我找到了解决方案:
此代码效果很好!
for(i in names(tab3)[2:5]) {
df2 <- tab3[, c(i, "CWRES")]
print(ggplot(tab3) + geom_point(aes_string(x = i, y = "CWRES")) + theme_bw())
}