【发布时间】:2011-08-11 05:55:00
【问题描述】:
我开始对股票配对(配对交易)进行一些分析,这是我为生成图表而编写的函数(pairs.report - 下面列出)。
我需要在一个图中绘制三个不同的线。我列出的功能可以完成我想要它做的事情,但如果我想要在 x 轴(时间线)上进行精细定制,这将需要一些工作。实际上,它仅在 x 轴上打印年份(对于 10 年的数据)或月份(对于 6 个月的数据),没有刻度的格式。
如果我使用 xts 对象,即如果我使用
plot(xts-object-with-date-asset1-asset2, ...)
而不是
plot(date, asset2, ...)
我马上得到了一个格式很好的 x 轴(连同网格和框),但随后使用 points()、text()、lines() 等函数添加到绘图中失败了。我想 points.xts() 和 text.xts() 不会很快出现。
我想要 xts 对象的便利性,但我还需要对我的情节进行细粒度控制。那么我的工作流程应该是什么样的呢?我是否必须坚持基本图形并手动进行所有自定义?或者有什么方法可以让 xts 为我工作?
我知道 lattice 和 ggplot2,但我现在不想使用它们。这是我提到的功能(欢迎对代码改进提出任何批评/建议)-
library(xts)
pairs.report <- function(asset1, asset2, dataset) {
#create data structures
attach(dataset)
datasetlm <- lm(formula = asset1 ~ asset2 + 0, data = dataset)
beta = coef(datasetlm)[1]
#add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 4) + 0.1)
# Plot first set of data and draw its axis
ylim <- c(min(asset2,asset1), max(asset2,asset1))
plot(date,
asset2,
axes=T,
ylim=ylim,
xlab="Timeline",
ylab="asset2 and asset1 equity",
type="l",
col="red",
main="Comparison between asset2 and asset1")
lines(date, asset1, col="green")
box()
grid(lwd=3)
# Allow a second plot on the same graph
par(new=T)
# Plot the second plot and
ylim <- c(min(asset1-beta*asset2), max(asset1-beta*asset2))
plot(date,
asset1-beta*asset2,
xlab="", ylab="",
ylim=ylim,
axes=F,
type="l",
col="blue")
#put axis scale on right
axis(side=4,
ylim=ylim,
col="blue",
col.axis="blue")
mtext("Residual Spread",side=4,col="blue",line=2.5)
abline(h=mean(asset1-beta*asset2))
}
【问题讨论】:
-
也许我在这个线程中对我自己的问题的回答对你也有帮助:stackoverflow.com/questions/7009711/… 至少你应该得到其他时间跨度,而不仅仅是 10 年的跨度。当然,蜱也一样。
-
plot.zoo与 xts 对象一起使用,并为您提供更精细的控制。?plot.zoo有很多例子。
标签: r graphics graph xts quantmod