我正在尝试绘制矩阵mx
的时间序列版本。我使用了以下代码,但是x轴没有显示我的日期。它显示了一些数字,并没有真正追踪问题。
mx_ts<-ts(mx)
plot(mx_ts, type="l")
可重现的示例mx
如下:
structure(c("0.233632449583826", "0.252105485477729", "0.591295809149662",
"0.0901324567177099", "-0.0423290120373304", "0.0363874105632916",
"-0.136952003053153", "0.451355935617868", "-0.291897852322839",
"0.287789031880016", "-2.1", "-1.4", "-2.6", "1.9", "-0.7", "1.4",
"-0.6", "-1.3", "-1.4", "0"), .Dim = c(10L, 2L), .Dimnames = list(
c("1985-01", "1985-02", "1985-03", "1985-04", "1985-05",
"1985-06", "1985-07", "1985-08", "1985-09", "1985-10"), c("return",
"ukcc")))
答案 0 :(得分:2)
在这种情况下,zoo
类可能更可取:
library(zoo)
##
Dates <- as.Date(paste0(row.names(mx),"-01"))
mx_zoo <- zoo(apply(mx,2,as.numeric),Dates)
##
> plot(mx_zoo)
修改强> 这是使用@Henrik的建议快速获取x轴年份信息的方法:
mx_zoo2 <- zoo(apply(mx,2,as.numeric),
as.yearmon(Dates))
> plot(mx_zoo2)
如果您稍微使用axis
,可以调整轴标签,但说实话,我认为@ eipi10的答案非常清楚,所以我建议改用他的方法。
答案 1 :(得分:2)
以下是其他几个选项:
library(zoo)
library(xts)
# Convert to time series object with dates by month
mx.ts = ts(mx, start=as.yearmon(rownames(mx)[1]), frequency=12)
# Plot with fractional years on x-axis
plot(mx.ts)
# Plot with month-year on x-axis
par(mfrow=c(2,1))
plot(as.xts(mx.ts[,"return"]), major.format="%b-%Y", cex.axis=0.7, main="Return")
plot(as.xts(mx.ts[,"ukcc"]), major.format="%b-%Y", cex.axis=0.7, main="ukcc")
始终是ggplot2
包:
library(reshape2)
library(ggplot2)
mx2 = cbind(Date=rownames(mx), mx)
names(mx2)=c("Date","Return","ukcc")
# Melt data into "long" format
mx2.m = melt(mx2, id.var="Date")
ggplot(mx2.m, aes(Date, value, group=variable, colour=variable)) +
geom_line() + geom_point() +
facet_grid(variable ~ ., scales="free_y")