【问题标题】:Time Series Plot in R - Line Graph [closed]R中的时间序列图 - 折线图[关闭]
【发布时间】:2023-11-30 09:44:01
【问题描述】:

我有一个包含 5 个类别的 excel 文件,我想在 Y 轴上绘制类别,在 X 轴上绘制一年中的月份,矩阵的值是值。

excel表格是这样设置的

类别 |一月 |三月 |四月

猫。 1 |瓦尔。 |值 |验证
猫。 2 |。值 |值 |值

我该怎么做?

【问题讨论】:

    标签: r plot graph


    【解决方案1】:

    试试这个方法。您必须将数据重塑为长格式,然后绘制它。这里使用ggplot2tidyverse 函数的方法。我使用了与您类似的虚拟数据。代码如下:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    #Data
    df <- data.frame(Category=paste0('Cat.',1:5),
                     January=runif(5,10,20),
                     March=runif(5,20,30),
                     April=runif(5,30,40),stringsAsFactors = F)
    #Plot and data reshape
    df %>% pivot_longer(-Category) %>%
      mutate(name=factor(name,levels = unique(name),ordered = T)) %>%
      ggplot(aes(x=name,y=value,group=Category,color=Category))+
      geom_line(size=1)+
      theme_bw()+
      xlab('Month')
    

    输出:

    【讨论】:

      【解决方案2】:

      我们可以在base R 中使用matplot 轻松做到这一点

      matplot(t(df[-1]), type = 'l', xlab = "", xaxt = 'n', col = seq_len(nrow(df)))
      legend("topright", inset = .05, legend = df$Category, pch = 1, 
                col = seq_len(nrow(df)), horiz = TRUE)
      

      数据

      df <- structure(list(Category = c("Cat.1", "Cat.2", "Cat.3", "Cat.4", 
      "Cat.5"), January = c(19.8101808479987, 12.8288395586424, 18.4788214950822, 
      10.8223923086189, 18.8645875058137), March = c(24.7193073085509, 
      21.0910096345469, 23.3327798452228, 28.3741656923667, 22.76849841699
      ), April = c(35.8703514141962, 38.3673226973042, 30.7115402398631, 
      37.0277874334715, 36.9882453721948)), class = "data.frame", 
      row.names = c(NA, 
      -5L))
      

      【讨论】:

      • 如果我不想像您在这里所做的那样对所有值进行硬编码怎么办?
      • @j_nj 我没有硬编码这些值。只是dput(df)给出了数据的结构