[R] Suggestions ?!?!

Jason Turner jasont at indigoindustrial.co.nz
Tue Feb 24 23:27:45 CET 2004


"ivo welch" <ivo.welch at yale.edu> said...
> * Finally, a more complex question: I have a historical rate of stock
> return series (yes, I teach finance).  I would like to make a ts plot on
> the left (plot(date,returns,type="h")), and a plot(density(returns)) on
> the right.  works nicely with par(mfrow=c(1,2)), but it would be even
> nicer if I could rotate the density plot 90 degrees, so that it is more
> apparent that the density plot is an aggregation of the points at the
> same y coordinates.  (if need be, a histogram could replace the density
> plot.)  Is it possible to rotate an entire subpanel figure.  if there
> was a "horizontal" parameter to ps.options for plot(), it would do the
> trick, but this does not work.   So, this may be a suggestion, too.

There might be a more natural way to do this using grid graphics, but I'm
still not familiar with grid.  This type of plot is one I do enough of
that I rolled by own the old-fashioned way.

Try

zz <- ts(rnorm(100))
DenTSplot(zz)

## ts and density
DenTSplot <- function(x, ylim=NULL,main=NULL,...) {
	# data sanity check
	if(!is.ts(x))
		x <- ts(x)
	if(!is.null(dim(x))) {
		stop("can only handle univariate time series\n")
	}

	# set layout - FIXME - should this be user-setable?
	layout(matrix(c(1,1,1,2),nrow=1))

	# find x density.  FIXME - need to take arguments about
	# bandwidth selector, etc.
	x.d <- density(x)

	if(is.null(ylim)) {
		ylim <- range(x.d$x)
	}
	if(is.null(main))
		main <- "Series"

	opar <- par(no.readonly=TRUE)
	on.exit(par(opar))
	mai <- par("mai")
	mai.ts <- c(mai[1:3],0)
	par(mai=mai.ts)
	plot(x,ylim=ylim,main=main,...)

	mai.den <- c(mai[1],0,mai[3:4])
	par(mai=mai.den)
	plot(x.d$y, x.d$x,
		ylim=ylim, type="l", yaxt="n",
		ylab="",xlab="",main="Density")
}




More information about the R-help mailing list