r - 在 ggplot 中绘制可变数量的系列以用于 Shiny 应用程序
问题描述
我需要用 ggplot 制作一个图表,其中包含在图中的系列数是可变的。数据框在第一列中有日期(x 变量),然后是 1 到 15 个附加列,其中包含要绘制的变量。我看到以前的帖子建议从 reshape 包中融化;但是,我无法让它发挥作用。无论 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()
解决方案
修复数据:
您的代码产生错误
Error in dimnames(x) <- dn :
length of 'dimnames' [2] not equal to array extent
所以我将更直接地将数据重新生成为data.frame
副 a 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()
推荐阅读
- javascript - 如何折叠所有表格行
- reactjs - 当ant.d的Select下将一个不存在的Option设置为defaultValue时,会显示key
- yocto - 如何在 Yocto 中使用最新的 oe-depends-dot
- django - Django:将模型保存到数据库时得到确认
- midi - MIDI 文件部 SMTPE
- specifications - 非确定性下推自动机可以识别任何上下文无关语法吗?
- java - 如果不调用父构造函数(与 Java 不同),多态性如何在 Python 中工作?
- angularjs - 如何在 Angularjs 中将数据作为 ¶meter=value 对发布到 servlet
- excel - 活动单元格的单元格相等值,这是一个下拉列表
- javascript - 将图像拖放到另一个图像上的任何位置