Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visualize 2-variable joint probability mass function in R

Tags:

r

I have a matrix in R that represents the joint probability mass function (pmf) of two variables, for example:

> matrix(c(.13, .00004, 0, 0, 0, .04, .13, .008, 0, 0, .01, .007, .16, .02, .0004, .004, .025, .070, .14, .01, .001, .007, .028, .028, .12), nrow=5)
        [,1]  [,2]   [,3]  [,4]  [,5]
[1,] 0.13000 0.040 0.0100 0.004 0.001
[2,] 0.00004 0.130 0.0070 0.025 0.007
[3,] 0.00000 0.008 0.1600 0.070 0.028
[4,] 0.00000 0.000 0.0200 0.140 0.028
[5,] 0.00000 0.000 0.0004 0.010 0.120

I'd like to create a 2D visualization of this data as a square divided up into 5x5 smaller squares, where the color of the individual square is proportional to the entry in the matrix. (In the case above, it would be darkest along the diagonal). Is there a simple way to generate this type of image?

like image 515
Lorin Hochstein Avatar asked Apr 05 '11 15:04

Lorin Hochstein


3 Answers

Try this:

library(lattice)

#Build the data
x <- matrix(c(.13, .00004, 0, 0, 0, .04, .13, .008, 0, 0, .01, .007, .16, .02, .0004, .004, .025, .070, .14, .01, .001, .007, .028, .028, .12), nrow=5)
xmin <- min(x)
xmax <- max(x)

#Build the plot
pal <- colorRampPalette(c("lightblue", "blue"), space = "rgb")
levelplot(x, main="5 X 5 Levelplot", xlab="", ylab="", col.regions=pal(120), cuts=100, at=seq(xmin, xmax, (xmax-xmin)/20))

enter image description here

like image 110
bill_080 Avatar answered Oct 23 '22 05:10

bill_080


ggplot can handle this pretty easily. I know of two easy methods for doing this:

library(ggplot2)
dat <- matrix(c(.13, .00004, 0, 0, 0, .04, .13, .008, 0, 0, .01, .007, .16, .02, .0004, .004, .025, .070, .14, .01, .001, .007, .028, .028, .12), nrow=5)
ggfluctuation(as.table(dat), type = "colour") +
    scale_fill_gradient(low = "white", high = "blue")

#Or with geom_tile
dat.m <- melt(dat)

ggplot(dat.m, aes(X1, X2, fill = value)) + 
    geom_tile(colour = "grey") + scale_fill_gradient(low = "white", high = "blue")

For completeness, here's a lattice solution (also easy):

library(lattice)
levelplot(dat)
like image 21
Chase Avatar answered Oct 23 '22 06:10

Chase


The image() function can be used:

mat <- matrix(c(.13, .00004, 0, 0, 0, 
                .04, .13, .008, 0, 0,
                .01, .007, .16, .02, .0004,
                .004, .025, .070, .14, .01,
                .001, .007, .028, .028, .12), nrow=5)
image(mat, col = rev(heat.colors(12)))

but you need to come up with the correct colour scheme to fill each class/bin. Here I just reverse the default to get darker colours for the high values. But there are better ways.

like image 3
Gavin Simpson Avatar answered Oct 23 '22 06:10

Gavin Simpson