1

我有以下非常简单的 R 脚本,它使用 zoo 在时间线上可视化每日数字:

# Small script to plot daily number of added users to database
library(zoo)

data <- read.csv("search_history.csv", header=FALSE)
# last line will be cut because it might be incomplete
zoodata <- data[1:(length(data$V2)-1), ]
series <- zoo(zoodata$V2, zoodata$V1)

par(mar=c(7, 6, 4, 2), 
    lab=c(5, 6, 5), 
    mgp = c(4, 1, 0))

plot(series,
     main="Number of users added to database over time", 
     xlab="Date", 
     ylab="Number of users",
     las=2,
     lwd=2,
     col="red",
     cex.axis=0.7)

search_history.csv 的内容:

"2012-12-27","458","4728"
"2012-12-28","239","6766"
"2012-12-29","193","8189"
"2012-12-30","148","7698"
"2012-12-31","137","7370"
"2013-01-01","119","6324"
"2013-01-02","122","7016"
"2013-01-03","115","7986"
"2013-01-04","112","8222"
"2013-01-05","112","6828"
"2013-01-06","124","7318"
"2013-01-07","121","8228"
"2013-01-08","120","8158"
...

我想可视化第一列(V1)和第二列(V2)。我基本上有两个问题:第一个也是显而易见的问题是 y-Position ~50 和 ~450 处的虚线。我怎样才能删除它们,为什么它们甚至包括在内?

第二问题是将 2013-01-26 包含在 x 轴中。如您所见,我删除了包含此数据的数据集的最后一行(就像业余爱好者一样,也许有更好的方法来做到这一点)。所以情节不应该包括最后日期。我不明白为什么它甚至知道这个日期,因为它需要zoodata作为输入,而不是data. 我的阴谋

4

2 回答 2

3

您可以使用read.zoo

## double quotes were removed but they could have been left in
series <- read.zoo(text = '
2012-12-27,458,4728
2012-12-28,239,6766
2012-12-29,193,8189
2012-12-30,148,7698
2012-12-31,137,7370
2013-01-01,119,6324
2013-01-02,122,7016
2013-01-03,115,7986
2013-01-04,112,8222
2013-01-05,112,6828
2013-01-06,124,7318
2013-01-07,121,8228
2013-01-08,120,8158', sep =',')

然后使用你的情节指令,

plot(series,
     main="Number of users added to database over time", 
     xlab="Date", 
     ylab="Number of users",
     las=2,
     lwd=2,
     col="red",
     cex.axis=0.7)

您可以直观地比较 2 Times 系列... 在此处输入图像描述

于 2013-01-26T20:55:01.943 回答
1

两件事:您的字符串被视为因素,并且您zoo通过字符向量而不是日期来索引您的对象。

如果你stringsAsFactors=FALSE在你的read.csv调用中包含并给你的zoo对象一个Date索引,它看起来更像你所期望的。

library(zoo)    
data <- read.csv(text='"2012-12-27","458","4728"
                 "2012-12-28","239","6766"
                 "2012-12-29","193","8189"
                 "2012-12-30","148","7698"
                 "2012-12-31","137","7370"
                 "2013-01-01","119","6324"
                 "2013-01-02","122","7016"
                 "2013-01-03","115","7986"
                 "2013-01-04","112","8222"
                 "2013-01-05","112","6828"
                 "2013-01-06","124","7318"
                 "2013-01-07","121","8228"
                 "2013-01-08","120","8158"', header=FALSE, 
                 stringsAsFactors=FALSE)

zoodata <- data[1:(length(data$V2)-1), ]
series <- zoo(zoodata$V2, as.Date(zoodata$V1))

par(mar=c(7, 6, 4, 2), 
    lab=c(5, 6, 5), 
    mgp = c(4, 1, 0))

plot(series,
     main="Number of users added to database over time", 
     xlab="Date", 
     ylab="Number of users",
     las=2,
     lwd=2,
     col="red",
     cex.axis=0.7)

产生:

在此处输入图像描述

于 2013-01-26T20:52:56.207 回答