首页 > 解决方案 > 为什么 ggplot 不能正确循环数据帧?

问题描述

这是可重现的数据框:

example_df <- data.frame(rnorm1 = rnorm(100), 
                       rnorm2 = rnorm(100), 
                       rnorm3 = rnorm(100), 
                       id = (1:100))

我想以这种方式绘制它:

plot(example_df[,1], type = 'l')
for(i in 2:3) {
  lines(example_df[,i], col = i)
}

基图

但是基础图不方便进一步添加,所以我想使用 ggplot。但是,为什么不能使用相同的循环方法?

g1 <- ggplot(example_df, aes(seq(length(example_df[,1]))))
for(i in 1:3) {
  g1 <- g1 + geom_line(aes(y=example_df[,i], colour=colnames(example_df)[i]))
}
g1

这只保存最后一行:

ggplot2 示例 1

现在,我显然可以在没有循环的情况下做同样的事情,而且对于超过 3 行显然会很不方便:

g2 <- ggplot(example_df, aes(seq(length(example_df[,1])))) 
g2 <- g2 + geom_line(aes(y=example_df[,1], colour=colnames(example_df)[1]))
g2 <- g2 + geom_line(aes(y=example_df[,2], colour=colnames(example_df)[2]))
g2 <- g2 + geom_line(aes(y=example_df[,3], colour=colnames(example_df)[3]))
g2

ggplot2 示例 1

我还可以融化 df 并获得所需的情节:

example_df_melt <- melt(example_df, id.vars = 'id', variable.name = 'variable')
g3 <- ggplot(example_df_melt, aes(id,value)) + geom_line(aes(colour = variable))
g3

在此处输入图像描述

但是有什么理由不会在循环中产生相同的结果吗?

所需软件包:

require(ggplot2)
require(reshape2)

标签: rggplot2

解决方案


ggplot不打算以这种方式使用。如果您稍微重组数据,则可以完全避免使用循环:

example_df <- data.frame(y = c(rnorm(100), rnorm(100), rnorm(100)),
                         group = rep(c("rnorm1", "rnorm2", "rnorm3"), each = 100),
                         id = rep((1:100), 3))

ggplot(example_df, aes(y=y, x=id, colour=group))+
  geom_line()

推荐阅读