user3703592
user3703592

Reputation: 160

ggplot2 Heatmap discrete legend with break points

I am using ggplot2 to produce a heatmap. The annotation of the legend contains intervals, however I would like to have break points like -100,-10,-5,0,5,10,100 marking the breakpoints between the intervals. Is it possible to manipulate legend labels and legend label positions ?

daf <- data.frame(row=(rep(paste(LETTERS[1:5],1:50,sep=""),2)),col=c(rep("A",50),rep("B",50)),val=runif(100,-20,20))

intervals <- c(100,10,5,0,-5,-10,-100)
binned <- cut(daf$val,breaks=intervals)
colfunc <- colorRampPalette(c("yellow", "black", "steelblue"))
colgroups <- colfunc(length(levels(binned)))
res <- colgroups[as.integer(binned)]
res <- factor(res,levels=colgroups)


p <- ggplot(daf,aes(x=col, y=row,fill=res)) + 
  geom_tile(color="white") +
  scale_fill_manual(values=levels(res),labels=levels(binned))

enter image description here

enter image description here

Upvotes: 2

Views: 1639

Answers (1)

C. Braun
C. Braun

Reputation: 5211

You can manipulate legend labels with labels.vjust:

build_labels <- function(breaks) {
    labels <- gsub('\\([^,]*,(-?\\d+).*', '\\1', levels(binned))
    c(head(labels, -1), '')
}

ggplot(daf,aes(x=col, y=row,fill=res)) + 
    geom_tile(color="white") +
    scale_fill_manual(values=levels(res),labels=build_labels) +
    guides(fill = guide_legend(label.vjust = -0.25))

plot with legend labels at box border

Upvotes: 1

Related Questions