grid の grob でバーの上下に文字を置き、guide_custom() で追加して元の塗り分けガイドを非表示にします。文字をガイド内に収めるので、パネルは既定のクリッピング設定を使います。


バーとヒートマップの配色を合わせるには?
学習済みの塗り分けスケールから色を取得します。2–14 を 64 の等間隔区間に分け、各中点を同じスケールで色に変換します。バーは連続スケールの分割近似で、セル内の数値は正確な値を示します。
ここでは固定した線形スケールを使います。カスタムガイドは独立したグラフィカルオブジェクトを表示します。ラベル、範囲、方向は手動で更新します。設定を変えたらバーを作り直し、両端を確認してください。対数スケール、反転、範囲外の拡張は別の処理が必要です。
完全なコードと出力ファイルはどう使いますか?
ggplot2 をインストールし、空の作業フォルダーで以下のスクリプトを実行すると、データ、PNG 2 枚、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.pdf閲覧やページへの配置に使える PDF 形式の結果です。
- 利用条件 · LICENSE.txtコード・データ・図の利用条件と、出典・フォントの情報。
ガイドの仕様はどこで確認できますか?
公式の guide_custom() 文書には、独立して指定した grob を表示することが記されています。通常の連続カラーバーは guide_colourbar() の文書で確認できます。下の R リンクは開発版マニュアルで、実行した R のバージョンは上記のとおりです。
ggplot2 の保存方法は別の書き出しガイドを参照してください。
ggplot2 guide_custom · ggplot2 guide_colourbar · R grid
R言語入門

