R-在使用时间数据进行绘图时遇到一些问题

R-在使用时间数据进行绘图时遇到一些问题,r,R,我目前正试图用R编写一个预测算法,但从txt文件中提取时间数据时遇到了一个问题 我目前有一个包含以下数据的测试文本文件 x 1 2010-01-01 2 2010-07-02 3 2010-08-03 4 2011-02-04 5 2011-11-05 6 2011-12-06 7 2012-06-07 8 2012-08-30 9 2013-04-16 10 2013-03-18 11 2014-02-22 12 2014-01-27 13 2015-12-15 14 2015-09-28 1

我目前正试图用R编写一个预测算法,但从txt文件中提取时间数据时遇到了一个问题

我目前有一个包含以下数据的测试文本文件

x
1 2010-01-01
2 2010-07-02
3 2010-08-03
4 2011-02-04
5 2011-11-05
6 2011-12-06
7 2012-06-07
8 2012-08-30
9 2013-04-16
10 2013-03-18
11 2014-02-22
12 2014-01-27
13 2015-12-15
14 2015-09-28
15 2016-05-04
16 2017-11-07
17 2017-09-22
18 2017-04-04
当我提取它并尝试用以下代码绘制它时:

library(forecast)
library(ggplot2)

Quantity <- c(read.table("....Path..../Quantity.txt"))
Time <- c(read.table("....Path..../Time.txt"))


x <- ts(as.Date(unlist(Time)))
y <- unlist(Quantity)


plot(x,y)
如何纠正这两个问题


提前感谢。

以下是许多可能的解决方案之一。
我希望它能帮助你

# A dataset with date and x values
# Important: the format of date is "character"
df <- structure(list(date = c("2010-01-01", "2010-07-02", "2010-08-03", 
"2011-02-04", "2011-11-05", "2011-12-06", "2012-06-07", "2012-08-30", 
"2013-04-16", "2013-03-18", "2014-02-22", "2014-01-27", "2015-12-15", 
"2015-09-28", "2016-05-04", "2017-11-07", "2017-09-22", "2017-04-04"
), x = c(5L, 3L, 8L, 4L, 0L, 5L, 2L, 7L, 4L, 2L, 6L, 8L, 4L, 
7L, 8L, 9L, 4L, 6L)), .Names = c("date", "x"), row.names = c(NA, 
-18L), class = "data.frame")
str(df)

# Create a x vector with dates as rownames
x <- as.matrix(df$x)
rownames(x) <- df$date
# Convert in a xts object
library(xts)
x <- as.xts(x)

# Plot the xts object
plot(x, grid.col="white")
#包含日期和x值的数据集
#重要提示:日期的格式为“字符”

df这里是许多可能的解决方案之一。
我希望它能帮助你

# A dataset with date and x values
# Important: the format of date is "character"
df <- structure(list(date = c("2010-01-01", "2010-07-02", "2010-08-03", 
"2011-02-04", "2011-11-05", "2011-12-06", "2012-06-07", "2012-08-30", 
"2013-04-16", "2013-03-18", "2014-02-22", "2014-01-27", "2015-12-15", 
"2015-09-28", "2016-05-04", "2017-11-07", "2017-09-22", "2017-04-04"
), x = c(5L, 3L, 8L, 4L, 0L, 5L, 2L, 7L, 4L, 2L, 6L, 8L, 4L, 
7L, 8L, 9L, 4L, 6L)), .Names = c("date", "x"), row.names = c(NA, 
-18L), class = "data.frame")
str(df)

# Create a x vector with dates as rownames
x <- as.matrix(df$x)
rownames(x) <- df$date
# Convert in a xts object
library(xts)
x <- as.xts(x)

# Plot the xts object
plot(x, grid.col="white")
#包含日期和x值的数据集
#重要提示:日期的格式为“字符”
df要回答您的
ggplot
问题,使用Marco提供的上述数据框,您只需使用:

ggplot(df, aes(x = date, y = x)) + geom_line(group = 1)
由于您只有一组或一组点,因此必须使用
geom\u行中的
group=1
arg

我要指出的一点是,时间序列数据具有不规则的周期,您必须确保在时间序列对象中考虑到这一点。大多数时间序列包都有自己的专用功能来处理数据和绘图。

要回答您的
ggplot
问题,使用Marco提供的上述数据框,您只需使用:

ggplot(df, aes(x = date, y = x)) + geom_line(group = 1)
由于您只有一组或一组点,因此必须使用
geom\u行中的
group=1
arg

我要指出的一点是,时间序列数据具有不规则的周期,您必须确保在时间序列对象中考虑到这一点。大多数时间序列包都有自己的专用功能来处理数据和绘图