我有一个xts文件格式,在读取时没有索引列的名称,请参阅下文。如何为其指定名称?理想情况下,我希望在后续阶段使用日期-时间字段进行绘图。谢谢
Elapsed Time Total Inflow Total Evap Surface Infil
2021-04-30 10:02:00 0.033 0 0.125 0
2021-04-30 10:04:00 0.067 0 0.125 0
2021-04-30 10:06:00 0.100 0 0.125 0
2021-04-30 10:08:00 0.133 0 0.125 0
2021-04-30 10:10:00 0.167 0 0.125 0
2021-04-30 10:12:00 0.200 0 0.125 0
我们假设问题是问如何在结尾的Note中绘制一个xts对象,例如x。
zoo和xts对象有许多绘图功能(每个xts对象也是zoo对象(,因此没有必要将其转换为数据帧(尽管在下面的最后一个示例中我们显示了这一点。(使用此功能时,每个绘图系统的所有功能都可用。下面还显示了如何在每种情况下指定x标签。
library(xts) # this also pulls in zoo
# classic graphics
plot(as.zoo(x), xlab = "Time")
# lattice graphics
library(lattice)
xyplot(x, xlab = "Time")
## ggplot2 graphics
library(ggplot2)
autoplot(x) + xlab("Time")
# convert to data frame and then use matplot
d <- fortify.zoo(x)
matplot(d[[1]], d[-1], xlab = "Time")
备注
Lines <- " Elapsed Time Total Inflow Total Evap Surface Infil
2021-04-30 10:02:00 0.033 0 0.125 0
2021-04-30 10:04:00 0.067 0 0.125 0
2021-04-30 10:06:00 0.100 0 0.125 0
2021-04-30 10:08:00 0.133 0 0.125 0
2021-04-30 10:10:00 0.167 0 0.125 0
2021-04-30 10:12:00 0.200 0 0.125 0"
# split into lines, trim whitespace off ends, replace 2+ spaces w comma
L <- Lines |>
textConnection() |>
readLines() |>
trimws() |>
gsub(pattern = " +", replacement = ",")
z <- read.csv.zoo(text = L, index = 0, tz = "", check.names = FALSE)
x <- as.xts(z)
一个建议是使用可以处理xts
数据的绘图函数。没有多少函数可以做到这一点。
另一种选择是将索引作为数据帧中的一个单独列,而不是xts
对象。
library(xts)
data <- data.frame(index = index(sample.xts), coredata(sample.xts))
data
# index Open High Low Close
#1 2007-01-02 50.03978 50.11778 49.95041 50.11778
#2 2007-01-03 50.23050 50.42188 50.23050 50.39767
#3 2007-01-04 50.42096 50.42096 50.26414 50.33236
#4 2007-01-05 50.37347 50.37347 50.22103 50.33459
#5 2007-01-06 50.24433 50.24433 50.11121 50.18112
#6 2007-01-07 50.13211 50.21561 49.99185 49.99185
#...
#...
数据
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')