Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 根据以日期为列名的数据的时间打印数据_R_Plot_Time Series - Fatal编程技术网

R 根据以日期为列名的数据的时间打印数据

R 根据以日期为列名的数据的时间打印数据,r,plot,time-series,R,Plot,Time Series,我有所有colname的数据,但第一个是'year' 看起来是这样的: 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 ... 我想根据时间绘制每一行

我有所有colname的数据,但第一个是'year'

看起来是这样的:

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轴为数据。比如说,

我已经搜索过了,但找不到这样做的方法。 我可以按照正常的方式重新排列数据(以年为列),但我想知道是否有一种方法可以用这样的数据绘制一个图表


如有任何建议,将不胜感激。提前非常感谢

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

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

或者,可以手动子集每一行,以提取作为向量的数据,并传递给plot()和lines(),以递归方式将每一行添加到绘图中,但这是非常手动的,不建议这样做,因为必须首先绘制具有最大值范围的行,以便正确渲染后续行


TL;DR使用整洁的数据。

使用
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这似乎回答了您的问题(但这是转换):

但要做到这一点而不单独转换一个变量(这里是rice),只需将colnames的参数传递为xlike即可(前提是列名为数字格式):

或者,如果没有太多的变量,可以通过循环来完成:

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解决方案吗
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")}