Arne
Arne

Reputation: 357

R: legends in lattice function

I visualized a matrix with the lattice package of R to obtain a 10x10 grid.

Unfortunately, I do have some problems regarding finetuning.

The colorbar would need an explanatory title (written vertically next to it).

Here is an example code to see how it looks like now plus a picture.

library(lattice)

#Build the horizontal and vertical axis information

hor=c("0.0005", "0.001", "0.005", "0.01", "0.05", "0.1", "0.5", "1", "5", "10")
ver=c("1000","2000","3000","4000","5000","6000","7000","8000","9000","10000")

nrowcol=length(ver)
cor = matrix(runif(nrowcol*nrowcol, min=0.4), nrow=nrowcol, ncol=nrowcol, dimnames = list(hor, ver))
for (i in 1:nrowcol) cor[i,i] = 1

rgb.palette <- colorRampPalette(c("blue", "yellow"), space = "rgb")
levelplot(cor, col.regions=rgb.palette(120), cuts=100, at=seq(0,1,0.01),
          xlab=expression("DAG depletion rate k"[B49] *" [ s"^"-1"*" ]"),
          ylab=expression("PKC activation rate k"[D5] *" [ l / (mol*s) ]"))

Do you have a guess how I can fix these little issues?

Best and thank you very much!

enter image description here

Upvotes: 3

Views: 394

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270298

Add these lines tweaking the x and y positions as needed:

library(grid)
grid.text("Here is some text explaining the legend", .77, .5, rot = 270)

screenshot

Upvotes: 5

Nancy
Nancy

Reputation: 4109

I couldn't figure out how to add a legend using levelplot(), but it's pretty straightforward to recreate your plot using ggplot's geom_tile. Here's what I got:

library("ggplot2")
this = melt(cor, id.vars = row.names(cor))
ggplot(this) + 
  geom_tile(aes(x = factor(Var1), y = factor(Var2), fill = value)) + 
  scale_fill_continuous(high = "yellow", low = "slateblue4", name = "Your Legend Title") +
  ggtitle("Your Title") + 
  xlab(expression("DAG depletion rate k"[B49] *" [ s"^"-1"*" ]")) + 
  ylab(expression("PKC activation rate k"[D5] *" [ l / (mol*s) ]")) + 
  theme_bw()

enter image description here

Fine tuning in ggplot is pretty well documented, so you'll probably be able to do what you need. Full disclosure though: if your x and y coordinates aren't evenly spaced, geom_tile won't always know how to fill the spaces. Noticed that I had to convert Var1 and Var2 to factors. This post gives some good ideas of how to handle this issue.

Upvotes: 1

Related Questions