数据框
x <- data.frame(id = c("A","B","C"), x_predictor = c(5,6,7), x_depended = c(5.5, 6.5, 7.5), y_predictor=c(2,3,2), y_depended=c(3,3,2), z_predictor=c(12,10,12), z_depended=c(14,11,13))
> x
id x_predictor x_depended y_predictor y_depended z_predictor z_depended
1 A 5 5.5 2 3 12 14
2 B 6 6.5 3 3 10 11
3 C 7 7.5 2 2 12 13
我想为ID上的每个级别以及每个依赖的对象和预测器创建一个散点图。
我创建了一个for循环,我在ID中循环遍历唯一级别,但是如何循环使用依赖和预测变量对?
uni <- unique(x$id)
for (p in uni){
print(ggplot(x[x$id==p], aes(y = x_depended,x = x_predictor))+geom_point()
}
我想绘制依赖vs预测器。依赖将始终在其预测器的后续列中。
答案 0 :(得分:1)
此代码将绘制三个不同的散点图,其中每个绘图将包含数据框中的不同列。
require(ggplot2)
x_plots <- list()
uni <- unique(x$id)
uni_counter <- 0
i <- 0
for (colnum in seq(2, 6, 2)) {
x_col <- names(x)[colnum]
y_col <- names(x)[colnum + 1]
# Retrieve the current uni.
curr_uni <- uni[uni_counter]
# Increment our counters
uni_counter <- uni_counter + 1
i <- i + 1
# Create the ggplot command,
# the command is created dynamically so that we can iterate through
# different columns in our data frame.
ggplot_cmd <- paste0("x_plots[[i]] <- ggplot(x[x$id == curr_uni], aes(y = ", y_col, ", x = ", y_col, "))+geom_point()")
# Evaluate each plot.
eval(parse(text = ggplot_cmd))
}
您可以加载multiplot()
张贴here的功能,使用以下内容绘制所有生成的图:
multiplot(plotlist = x_plots)
希望这有帮助。