r - 为什么 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
这只保存最后一行:
现在,我显然可以在没有循环的情况下做同样的事情,而且对于超过 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
我还可以融化 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)
解决方案
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()
推荐阅读
- r - Cleaning legacy country records in R dataframe
- android - 接口始终为空
- r - Replace column in a list of lists of dataframes with columns in another list of lists of dataframes. R
- php - 在其他列中使用 Datediff 结果
- c++ - 如何在给定向量中找到第一个、第二个和第三个最大值而不在 C++ 中排序?
- python - How to plot a matplotlib line plot using colormap?
- umbraco - 仅在表格完成后在 Umbraco 中显示内容
- php - Share URL including URL parameter through Facebook
- reactjs - 在反应组件上使用 Laravel 项目 CSS
- c# - 运行总 C#