【问题标题】:Making spaghetti plot with different variables as timepoints用不同的变量作为时间点制作意大利面条图
【发布时间】:2013-11-19 05:04:54
【问题描述】:

我已经被这个问题困扰了一段时间了。我正在尝试创建一个意大利面条图,其中不同的时间点实际上是不同的变量(或列),因此变量类似于:Test1Test2Test3Test4 其中每个测试都是不同的时间点(并且需要在 x 轴上表示)。我的 y 轴将是每个测试的测试分数,我需要通过 4 个时间点的学生 ID 绘制这些分数。

我尝试在R 中使用ggplotinteraction.plot 命令,但是当我使用ggplot 时,我收到以下错误消息:

美学长度必须为 1,或与数据长度相同。

interaction.plot 命令也是如此,它一直告诉我参数的长度相同。

数据格式为:

   ID Test1 Test2 Test3 Test4  
   1  83    84    67    44  
   2  67    55    58    59  
   3  99    98    98    95 

我需要 Test1-4 作为时间点和实际分数作为 y 轴。并且这些组将是 ID。

由于保密问题,我无法发布确切的数据。

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    ggplot 中,您的数据需要采用长格式。所以首先你需要重塑数据。

    library(reshape2)
    
    # melt data from wide to long format
    df2 <- melt(df, id.var = "ID")
    
    # plot
    ggplot(data = df2, aes(x = variable, y = value, group = ID, colour = factor(ID))) +
      geom_line()
    

    【讨论】:

      【解决方案2】:

      您也可以简单地使用matplot

      # Create some data
      df <- data.frame(ID=1:10, Test1=sample(50:100, 10), 
                       Test2=sample(50:100, 10), Test3=sample(50:100, 10))
      # Plot it! We remove the ID column, which we don't need to plot
      matplot(t(df)[-1,], t="l", lty=1, las=1, ylab="Score", 
              xlab="Test", xaxt="n")
      # Use the column labels as axis titles
      axis(1, at=1:(ncol(df)-1), labels=names(df)[-1])
      

      【讨论】:

        【解决方案3】:

        试试这个:

        #dummy data
        df <- read.csv(text="
        ID, Test1, Test2, Test3, Test4
        1, 83, 84, 67, 44
        2, 67, 55, 58, 59
        3, 99, 98, 98, 95
        ")
        #blank plot
        plot(0,0,ylim=c(0,100),xlim=c(1,4),bty="n")
        #add lines for each ID
        for(i in df$ID) lines(1:(ncol(df)-1),
                              df[df$ID==i,2:ncol(df)])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-04
          • 2022-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多