【问题标题】:Plotting data against time of the data with dates as column names以日期为列名根据数据的时间绘制数据
【发布时间】:2020-07-28 18:28:44
【问题描述】:

我有所有列名的数据,但第一个是“年”

看起来像这样:

Products      1999   2000   2001   2002   2003  ...

   Rice     23.254  19.42  17.30  10.22   8.05 
   Meat     45.123  30.15   5.33   4.08   1.09
  Metal     60.347  12.48   6.79   4.98   0.86
   ...

我想绘制每行(单独或全部在一个图中)与时间的关系图,x 轴是年份(1999 年、2000 年等),y 轴是数据。例如,

My graph

我已搜索但找不到执行此操作的方法。 我可以以正常方式重新排列我的数据(将年份作为一列),但我想知道是否有办法用这样的数据绘制图表。

我们将不胜感激任何建议。非常感谢您!

【问题讨论】:

    标签: r plot time-series


    【解决方案1】:

    使用matplot;真的一点问题都没有。

    matplot(colnames(dat[-1]), t(dat[-1]), type="l", xlab="year", ylab="percent")
    legend("topright", legend=dat$Products, col=1:3, lty=1:3)
    

    数据

    dat <- structure(list(Products = c("Rice", "Meat", "Metal"), `1999` = c(23.254, 
    45.123, 60.347), `2000` = c(19.42, 30.15, 12.48), `2001` = c(17.3, 
    5.33, 6.79), `2002` = c(10.22, 4.08, 4.98), `2003` = c(8.05, 
    1.09, 0.86)), row.names = c(NA, -3L), class = "data.frame")
    

    【讨论】:

      【解决方案2】:

      这似乎回答了你的问题(但那是转换):

      Plotting column names as x-axis in R

      但要做到这一点而不单独转换一个变量(这里是大米),可以通过将 colnames 的参数传递为 xlike 来完成(假设您的列名是数字格式):

      plot(colnames(df)[-1], df[which(df$Products == "Rice"), -1], xlab = "Year", ylab = "Percent", type = "l")
      

      或者,如果你没有太多的变量,你可以用一个循环来完成它们:

      columns = df$Products
      for (i in 1:nrow(df)) {plot(colnames(df)[-1], df[which(df$Products == columns[i]), -1], xlab = "Year", ylab = "Percent", type = "l")}
      
      

      但 ggplot 更干净,返回的图形更漂亮:)

      这适用于我创建的示例,因此如果这不起作用,请提供可重现的示例以获得更好的答案。

      【讨论】:

      • 你好,谁能给我python解决方案
      【解决方案3】:

      在使用 ggplot2 等 tidyverse 包时,最好根据 tidy data 原则组织数据:即每个变量是一列,每个观察值是一行,正如您提到的那样,年份是一列。

      使用 dplyr::pivot_longer() 或更旧的 dplyr::gather() 这是一个简单的操作。

      或者,可以手动对每一行进行子集化以将数据提取为向量并传递给 plot() 和 lines() 以递归地将每一行添加到绘图中,但这是非常手动的,不推荐使用,因为带有必须首先绘制最大范围的值,以便后续行正确呈现。

      TL;DR 使用整洁的数据。

      【讨论】:

        猜你喜欢
        • 2016-11-11
        • 2019-12-11
        • 1970-01-01
        • 2021-08-06
        • 1970-01-01
        • 2021-02-03
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多