首页 > 解决方案 > 在 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()

标签: rggplot2shiny

解决方案


修复数据:

您的代码产生错误

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()

示例 ggplot 图像


推荐阅读