R-axis label in image

I need to display a metric by spatial position in a call center. I wrote a tiny example in R:

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:

> 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 move and reorder the matrix because I wanted you to read it in a table.

So I got:

enter image description here

I need to add row and column names next to each square. For example, the top left square should have "L1" on the left and "a1" at the top.

Also I would like to add values ​​to each square.

I tried axis (), but I got the wrong result. I'm new to doing graphs in R, so any help would be appreciated.

+3


source to share


2 answers


I think you'll be much happier using ggplot - it makes it easier, much less error prone, and the build code is more readable. To do this, you will want to store your data in a dataframe and melt it in "long form" (I'm using a melt from the reshape2 package here, but you can also just set your datafile in that form to start with). Try the following:

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 lets you control the color gamut if you like. If you're going to be scheming in R, it's worth spending a couple of hours learning ggplot!

+3


source


The command axis

does not display labels outside of the image, even with an argument outer

.

However, it works if you use function image

(s add=TRUE

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

+3


source







All Articles