开发者

Binning data for use in matrix and image() or heatmap()

I have a data frame with three columns and I'd like to make a image/heatmap of the data.

The three columns are pe, vix, and ret with pe and vix being x and y and ret being z.

There are 220 lines in the data frame so i'd like to bin the data if possible, the ranges are below.

Any suggestions for how to bin the x and y data and also create a matrix for use in an image()?

> range(matr$pe)
[1] 13.32 44.20
> range(matr$vix)
[1] 10.42 59.89
> range(matr$ret)
[1] -0.09274936  0.04693118
>开发者_开发知识库 class(matr)
[1] "data.frame"
> head(matr)
     pe   vix          ret
1 20.86 13.16 -0.002931561
2 20.46 12.53 -0.003546889
3 20.52 12.42  0.006339165
4 20.61 13.47  0.009683174
5 20.57 11.26 -0.002666668
6 20.81 11.73  0.002895003


Here's what I ended up doing. I used the interp() function in the akima package to create the appropriately binned matrix object. It seems to do the work of binning and 'matricizing' of the data frame. On a side note, in order to make the heatmap WITH a legend, I ended up using the image.plot() method from the fields package. Here's the code:

par(bg = 3)
image.plot(s,xlab="P/E Ratio", ylab="VIX", 
    main="Contour Map of SPY Returns vs P/E Ratio and Vix") 
abline(v=(seq(0,100,5)), col=6, lty="dotted") 
abline(h=(seq(0,100,5)), col=6, lty="dotted") 
contour(s, add=TRUE)

and resulting product for anyone interested:

Binning data for use in matrix and image() or heatmap()

Thanks to everyone for their help and suggestions.


You could use e.g. cutlike this:

matr$binnedpe<-cut(matr$pe, breaks=10)
matr$binnedvix<-cut(matr$vix, breaks=10)

Next you can use e.g. ddply (from package plyr) to get the means per bin:

binneddata<-ddply(matr, .(binnedpe, binnedvix), function(d){c(d$binnendpe, d$binnedvix, mean(d$ret))})

Finally, you use this last data.frame to draw your heat map. I haven't tested any of the above, but it should be close enough to get you going.


you should take a spin through the raster package. In particular, the function rasterfromXYZ() should do most of what you want. It's pretty easy, either with the base graphics tools or the raster package, to setup a 'heatmap' color range for the raster object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜