Reputation: 160
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))
Upvotes: 2
Views: 1639
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))
Upvotes: 1