我需要制作一个带有ggplot的图形,其中图形中包含的序列数是可变的。数据框在第一列中具有日期(x变量),然后在其他1至15列中包含要绘制的变量的任何列。我以前看到过一篇帖子,建议重塑包装中融化。但是,我无法使它正常工作。我希望在调暗测试矩阵时不管ncol =规范如何工作。非常感谢您的帮助!
模拟数据:
#rm(list = ls())
library(ggplot2)
library(reshape2)
test <- matrix(0, nrow = 10, ncol = 5)
test[,1] <- seq(from = 2000, by = 1, length = 10)
for(i in 2:5){
test[1, i] <- 100
for(j in 2:10){
test[j, i] <- test[j-1, i] + rnorm(1, 25, 5)
}
}
colnames(test)[1] <- "date"
melt_test <- melt(test, id = "date")
ggplot(melt_test, aes(x=date, y=value, colour = variable, group = variable)) +
geom_line()
答案 0 :(得分:0)
修复数据:
您的代码产生错误
Error in dimnames(x) <- dn :
length of 'dimnames' [2] not equal to array extent
所以我将更直接地将数据重新生成到data.frame
和matrix
中:
library(ggplot2)
library(reshape2)
test <- matrix(0, nrow = 10, ncol = 4)
set.seed(2) # for reproducibility, always include this in SO questions when using random funcs
for(i in 1:4){
test[1,i] <- 100
for(j in 2:10){
test[j, i] <- test[j-1, i] + rnorm(1, 25, 5)
}
}
test[1:3,]
# [,1] [,2] [,3] [,4]
# [1,] 100.0000 100.0000 100.0000 100.0000
# [2,] 120.5154 124.3061 130.0641 122.0172
# [3,] 146.4397 151.3943 157.2255 150.9782
dat <- cbind.data.frame(date = seq(2000, by=1, length=nrow(test)), test)
dat[1:3,]
# date 1 2 3 4
# 1 2000 100.0000 100.0000 100.0000 100.0000
# 2 2001 120.5154 124.3061 130.0641 122.0172
# 3 2002 146.4397 151.3943 157.2255 150.9782
现在,当我们重塑形状时,我们可以看到更好的东西:
melt_dat <- reshape2::melt(dat, id="date")
melt_dat[1:3,]
# date variable value
# 1 2000 1 100.0000
# 2 2001 1 120.5154
# 3 2002 1 146.4397
现在一切正常:
ggplot(melt_dat, aes(x=date, y=value, colour = variable, group = variable)) +
geom_line()