ggplot2 Heatmap带有断点的离散图例

时间:2015-01-30 14:59:06

标签: r ggplot2

我正在使用ggplot2来制作热图。图例的注释包含间隔,但是我希望有一个断点,如-100,-10,-5,0,5,10,100,标记间隔之间的断点。 是否可以操作图例标签和图例标签位置?

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

1 个答案:

答案 0 :(得分:1)

您可以使用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