首页 文章

同一图中的多变量

提问于
浏览
2

我有一个525 * 95维度的数据矩阵 . 数据包含我希望在同一图表中绘制的模拟值 . 这意味着我有95个不同的变量,它们在Y轴上都有相同的起点,但在X轴上采用不同的路径 .

我正在寻找一种方法来绘制所有模拟值(存储在列中),但是在同一图表中 . 命令plot()似乎假设我希望将模拟路径相互绘制,但我只想将它们与它们被模拟的周期数相对应,即525 .

有线索吗?

V1         V2         V3
1  0.01076000 0.01076000 0.01076000
2  0.01135591 0.01081002 0.01081920
3  0.01117306 0.01034507 0.01079422
4  0.01090997 0.01091913 0.01065135
5  0.01072611 0.01082653 0.01091554
6  0.01121228 0.01098110 0.01149064
7  0.01171061 0.01138791 0.01282230
8  0.01057508 0.01208230 0.01268310
9  0.01033449 0.01172448 0.01233295
10 0.01067395 0.01297883 0.01247032

2 回答

  • 1

    一个简单的方法是使用 ggplot2 . 您只需要将数据重新整形为长格式,您可以使用包 reshape 轻松完成 . 一些模拟数据的示例:

    ## Simulate some data
    set.seed(123)
    df <- data.frame( y = runif(10) + 2 , x = runif(10) + 4 , z = runif(10) + 5 )
    df
    #         y        x        z
    #1  2.287578 4.956833 5.889539
    #2  2.788305 4.453334 5.692803
    #3  2.408977 4.677571 5.640507
    #4  2.883017 4.572633 5.994270
    #5  2.940467 4.102925 5.655706
    #6  2.045556 4.899825 5.708530
    #7  2.528105 4.246088 5.544066
    #8  2.892419 4.042060 5.594142
    #9  2.551435 4.327921 5.289160
    #10 2.456615 4.954504 5.147114
    
    
    ## Make an ID variable to use as the x-axis
    df$ID <- 1:nrow(df)
    
    ## Melt data into long format 
    df.long <- melt( df , id.vars = "ID" )
    
    
    ## Plot using the column name as the grouping variable
    ## After melting the column names are stored in the 
    ## column called 'varaible'
    ggplot( df.long , aes( x = ID , y = value , group = variable ) ) + geom_line( aes( color = variable  ) , stat = "smooth" )
    

    enter image description here

  • 1

    你也可以使用 matplot .

    这里有一些示例数据(类似于SimonO101的数据,但维度为525 * 95):

    df <- as.data.frame(matrix(runif(525 * 95), ncol=95))
    for (i in 1:ncol(df))  
      df[,i]=df[,i]+i
    df[1,] = rep(0, 95)
    

    然后绘图:

    matplot(1:nrow(df), df, type="l")
    

    enter image description here

相关问题