我开始对一对股票(对交易)进行一些分析,这里是我为生成图表(pairs.report - 下面列出)而编写的函数。使用xts对象添加点,图例和文本到图表
我需要在一个绘图中绘制三条不同的线。我列出的函数做我想做的事情,但是如果我想在x轴(时间线)中进行良好的自定义,它将需要一些工作。实际上,它仅在X轴上打印年份(10年的数据)或月份(6个月的数据),没有格式化蜱。
如果我使用XTS对象,也就是说,如果我用
plot(xts-object-with-date-asset1-asset2, ...)
,而不是
plot(date, asset2, ...)
我得到一个很好的格式化的x轴向右走(与电网和盒子一起),但随后使用诸如points(),text(),lines()等函数添加到绘图失败。我想points.xts()和text.xts()不会很快出来。
我想要xts对象的方便,但我也需要对我的情节进行细致的控制。那么我的工作流程应该如何?我是否必须坚持使用基本图形并手动进行所有定制?或者有什么办法可以让我的XT工作?
我知道格和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))
}
也许我在这个线程中对自己问题的回答也可以帮助你: http://stackoverflow.com/questions/7009711/how-to-get-years-from-a-time-series-index-when - 基础时间序列 - 是米 至少你应该得到其他时间跨度只有10年跨度。当然,蜱也是一样。 –
'plot.zoo'可与xts对象一起使用,并为您提供更精细的控制。 ''plot.zoo'有很多例子。 –