Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r- axis label in image

Tags:

r

image

label

axis

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:

enter image description here

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.

like image 421
GabyLP Avatar asked Dec 10 '14 16:12

GabyLP


2 Answers

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))

enter image description here

like image 94
user20650 Avatar answered Oct 15 '22 16:10

user20650


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()

enter image description here

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!

like image 30
eamcvey Avatar answered Oct 15 '22 14:10

eamcvey