或者我们可以创建一个假构面并将情节标题放入其中。之后进行一些调整以删除条形刻面并减少图例边距
library(ggplot2)
d <- data.frame(x = 1:2, y = 1:2, z = c("a", "b"))
d$Title <- "My title\n"
# default legend key text
p1 <- ggplot(d, aes(x = x, y = y, fill = z)) +
geom_col() +
facet_grid(~ Title) +
theme(strip.text.x = element_text(hjust = 0, vjust = 1,
size = 14, face = 'bold'),
strip.background = element_blank()) +
theme(legend.margin = margin(5, 0, 0, 0),
legend.box.margin = margin(0, 0, -10, 0)) +
theme(legend.position = "top") +
NULL
# legend key text at the bottom
p2 <- ggplot(d, aes(x = x, y = y, fill = z)) +
geom_col() +
facet_grid(~ Title) +
theme(strip.text.x = element_text(hjust = 0, vjust = 1,
size = 14, face = 'bold'),
strip.background = element_blank()) +
theme(legend.margin = margin(5, 0, 0, 0),
legend.box.margin = margin(0, 0, -10, 0)) +
guides(fill = guide_legend(label.position = "bottom",
title.position = "left", title.vjust = 1)) +
theme(legend.position = "top") +
NULL
library(patchwork)
p1 | p2
由reprex package (v0.2.1.9000) 于 2018 年 10 月 12 日创建