ggplot2:为多面图中的轴标题添加边框和彩色背景

问题描述 投票:0回答:1

我有以下 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?

r ggplot2 axis axis-labels facet-grid
1个回答
0
投票

我可能会通过使用拼凑在主图左侧添加一个细长的纯文本 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) +
  theme_void() +
  theme(panel.background = element_rect(fill = "gray"),
        panel.border = element_rect(fill = NA, color = "black"))

p1 + p2 + plot_layout(widths = c(1, 30))

© www.soinside.com 2019 - 2024. All rights reserved.