提问人:Dai 提问时间:9/30/2023 更新时间:10/1/2023 访问量:20
ggplot2:在分面图中为轴标题添加边框和彩色背景
ggplot2: Add border and colored background for axis title in faceted plot
问:
我有一个以下 R 代码
pdf <- data.frame(xx = as.factor(c(rep(0, 100), rep(1, 100))),
value = rnorm(200),
selected_site = c('y', rep('n', 98), 'y'),
name = as.factor(rep(1:5, each = 20)),
version = rep(c('A', 'B'), each = 100))
pdf %>%
ggplot(aes(x = value, fill = xx)) +
geom_histogram(alpha=0.6, position="identity") +
facet_grid(selected_site ~ name, scale = 'free_y') +
scale_fill_manual(name = '', values = c('red', 'blue')) +
facetted_pos_scales(
y = list(selected_site == 'n' ~ scale_y_continuous(limits = c(0,5)),
selected_site == 'y' ~ scale_y_continuous(limits = c(0,2)))) +
xlab('') + ylab('THIS IS A TEST') +
theme_bw() +
theme(legend.position = 'none',
strip.background.y = element_blank(),
strip.text.y = element_blank(),
panel.spacing=unit(0.2, "lines"))
我想为 y 轴标题创建一个背景,其中背景框高度与带有灰色阴影的绘图高度相匹配。
这可能吗?也许用textGrob?
答:
1赞
Allan Cameron
10/1/2023
#1
我可能会通过使用拼凑在主图的左侧添加一个细长的纯文本 ggplot 来做到这一点
library(ggh4x)
library(patchwork)
p2 <- pdf %>%
ggplot(aes(x = value, fill = xx)) +
geom_histogram(alpha=0.6, position="identity") +
facet_grid(selected_site ~ name, scale = 'free_y') +
scale_fill_manual(name = '', values = c('red', 'blue')) +
facetted_pos_scales(
y = list(selected_site == 'n' ~ scale_y_continuous(limits = c(0,5)),
selected_site == 'y' ~ scale_y_continuous(limits = c(0,2)))) +
xlab('') + ylab(NULL) +
theme_bw() +
theme(legend.position = 'none',
strip.background.y = element_blank(),
strip.text.y = element_blank(),
panel.spacing=unit(0.2, "lines"))
p1 <- ggplot(data.frame(x = 1, y = 1, label = "THIS IS A TEST"), aes(x, y)) +
geom_text(aes(label = label), angle = 90) +
coord_cartesian(clip = "off") +
theme_void() +
theme(panel.background = element_rect(fill = "gray"),
plot.margin = margin(5, 5, 5, 5))
p1 + p2 + plot_layout(widths = c(1, 30))
评论