I need to graph a metric by spatial position in a call center. I wrote in R a tiny example:
tt<-data.frame(a1=c(0.4,.5,.5,.7),a2=c(.5,.6,.7,.8), a3=c(.8,.7,.9,.8))
row.names(tt)<-paste("L", 1:4, sep='')
tt<-as.matrix(tt)
tt
So my matrix is:
> tt a1 a2 a3 L1 0.4 0.5 0.8 L2 0.5 0.6 0.7 L3 0.5 0.7 0.9 L4 0.7 0.8 0.8
I tried:
palette <- colorRampPalette(c('#f0f3ff','#0033BB'))(256)
library(fields)
image.plot(t(tt[rev(order(row.names(tt))),]),col = palette, axes=F ,
lab.breaks=NULL)
I had to transpose and reorder the matrix because I wanted the way you read it in the table.
So I got:
I need to add next to each square the row and column names. For example, top left squared should have "L1" at the left and "a1" at the top.
Also I would like to add the values in each square.
I tried axis() but I got the wrong result. I'm pretty new in doing graphs in R, so any help would be appreciated.
The axis
command doesnt seem to plot the labels outside the image, even when using the outer
argument.
It does work however, if you use the image
function (with add=TRUE
) after image.plot
image.plot(t(tt[rev(order(row.names(tt))),]),col = palette, axes=FALSE,
lab.breaks=NULL)
# axis labels
image(t(tt[rev(order(row.names(tt))),]), col = palette, axes=FALSE, add=TRUE)
axis(3, at=seq(0,1, length=3), labels=colnames(tt), lwd=0, pos=1.15)
axis(2, at=seq(1,0, length=4), labels=rownames(tt), lwd=0, pos=-0.25)
# add values
e <- expand.grid(seq(0,1, length=3), seq(1,0, length=4))
text(e, labels=t(tt))
I think you'll be much happier using ggplot -- it makes this sort of thing easy, much less error-prone, and plot code is more readable. For this, you'll want to keep your data in a dataframe, and melt it to be in "long form" (here I use melt from the reshape2 package, but you could also just set your dataframe up in this form to start with). Try this:
library(ggplot2)
library(reshape2)
tt<-data.frame(a1=c(0.4,.5,.5,.7),a2=c(.5,.6,.7,.8), a3=c(.8,.7,.9,.8))
tt$row <- paste("L", 1:4, sep='')
tt_melt <- melt(tt)
ggplot(data=tt_melt,
aes(x=variable, y=row, fill=value)) + geom_tile() +
geom_text(aes(label=value), color='white') + theme_bw()
ggplot also allows you to control the color scale if you wish. If you're going to be plotting in R, it's well worth investing a couple hours learning ggplot!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With