用 grid 图形对象把文字排在色条上方和下方,再通过 guide_custom() 加入图例,并隐藏原来的填色图例。我把文字留在图例自己的区域内,绘图区沿用默认裁切设置。


怎样保证自定义色条与热图配色一致?
从已训练的填色标尺中取色。我把 2–14 等分为 64 个区间,用各区间中点向同一标尺取色,再按从低到高的顺序画色条。这是连续标尺的分段近似,格子上的数字仍给出准确数值。
本例只处理固定的线性标尺。自定义图例使用独立传入的图形对象,标签、范围和方向需手动更新。修改这些设置后,要重建色条并核对两端;对数标尺、反向色条和范围外扩展需要另行处理。
完整代码怎样运行,能下载哪些文件?
安装 ggplot2 后,在空工作目录运行下面的完整脚本,即可生成数据、两张 PNG、一份 PDF 和核对文件。本文使用模拟演示数据。
实际运行版本为 R 4.5.3、ggplot2 4.0.4。PNG 为 1200 × 900 像素、200 PPI;PDF 为 6 × 4.5 英寸,即 432 × 324 点,PDF 引用标准 Helvetica 字体。
自定义色条是一张 64 × 1 像素的位图,按图例区域拉伸,PDF 中也保留这张位图。使用单张位图可避免独立矩形之间出现可见细缝。
# Original Bopbun demonstration. CC0-1.0. Run in this file's directory.
library(ggplot2)
library(grid)
d <- expand.grid(column = 1:4, row = 1:3)
d$score <- c(2, 8, 4, 14, 6, 10, 12, 3, 9, 5, 11, 7)
write.csv(d, "synthetic.csv", row.names = FALSE)
limits <- c(2, 14)
fill_scale <- scale_fill_gradient(
low = "#f1e5b6", high = "#264e70", limits = limits,
breaks = limits, labels = c("Low (2)", "High (14)"), name = "Score"
)
p <- ggplot(d, aes(column, row, fill = score)) +
geom_tile(colour = "white", linewidth = 1) +
geom_text(aes(label = score, colour = ifelse(score >= 10, "white", "#18212b")),
size = 4, fontface = "bold") + scale_colour_identity() +
fill_scale + coord_fixed() +
scale_x_continuous(breaks = 1:4) +
scale_y_continuous(breaks = 1:3) +
labs(x = "Column", y = "Row") + theme_minimal(base_size = 12) +
theme(panel.grid = element_blank(), legend.position = "right")
before <- p + guides(fill = guide_colourbar(
display = "rectangles", nbin = 64,
theme = theme(legend.key.height = unit(34, "mm"))
))
# Use the trained fill scale so the guide and tiles share the same palette.
trained <- ggplot_build(p)$plot$scales$get_scales("fill")
n <- 64
edges <- seq(limits[1], limits[2], length.out = n + 1)
midpoints <- (head(edges, -1) + tail(edges, -1)) / 2
colours <- trained$map(midpoints)
key <- grobTree(
rasterGrob(matrix(rev(colours), ncol = 1), x = 0.5, y = 0.5,
width = 0.22, height = 0.64, interpolate = FALSE),
textGrob("High (14)", x = 0.5, y = 0.93, gp = gpar(fontsize = 11)),
textGrob("Low (2)", x = 0.5, y = 0.07, gp = gpar(fontsize = 11))
)
after <- p + guides(
fill = "none",
endpoint = guide_custom(key, width = unit(24, "mm"),
height = unit(52, "mm"), title = "Score")
)
for (nm in c("before", "after")) {
png(paste0(nm, ".png"), width = 1200, height = 900, res = 200)
print(get(nm)); dev.off()
}
pdf("after.pdf", width = 6, height = 4.5, timestamp = FALSE)
print(after); dev.off()
b <- ggplot_build(before)$data[[1]]
a <- ggplot_build(after)$data[[1]]
stopifnot(identical(b, a), sum(d$score) == 91,
identical(as.character(key$children[[2]]$label), "High (14)"))
write.csv(data.frame(score = midpoints, fill = colours),
"guide-samples.csv", row.names = FALSE)
write.csv(a, "tile-check.csv", row.names = FALSE)
writeLines(c("12 tile objects identical before/after; score sum=91",
"64 custom guide bands; high above, low below",
capture.output(sessionInfo())), "checks.txt")
下面是本文用到的代码、数据和结果文件。你可以下载代码跟着操作,也可以打开结果文件,对照自己运行后的结果。
- example.R可以在电脑上运行的完整示例代码。
- synthetic.csv本例使用的输入数据,可作为表格打开。
- guide-samples.csv色条各分段采用的数值与颜色。
- tile-check.csv色条修改前后热图格子的数值对照。
- before.png修改前的图,用来比较。
- after.png按本文设置生成的结果图。
- after.pdfPDF 格式的结果图,方便查看和排版。
- 使用许可 · LICENSE.txt说明代码、数据和图表的使用条件,并附来源及字体许可。
去哪里核对图例的工作方式?
官方 guide_custom() 文档说明它显示独立传入的图形对象;普通连续色条由 guide_colourbar() 文档说明。下方 R 链接属于开发版手册,实际运行版本以上文记录为准。
保存 ggplot2 图形的方法见独立的导出指南。
ggplot2 guide_custom · ggplot2 guide_colourbar · R grid
从零开始学习R语言

