R语言 控制y轴标题的位置时,结合几个地块与拼凑包

wbgh16ku  于 2023-05-11  发布在  其他
关注(0)|答案(2)|浏览(94)

我希望能够控制每个图的y轴标题相对于y轴本身的位置,以便当我在顶部图中输入不同的抗生素名称长度时,底部图中的y轴标题与y轴的距离相同,并且每次我更改顶部图中的抗生素名称时,我不必手动更改底部图中的y轴标题。有人能帮忙吗?
第一个图显示的是未进行任何调整的默认值。
第二个图显示y轴标题与y轴标签之间的所需距离。
第三个图展示了在顶部图中改变抗生素名称长度意味着需要改变校正。我想试着把这段代码自动化。

library(tidyverse)
library(patchwork)

therapy_1 <- tibble(
  antibiotic = c("IV Piperacillin-tazobactam", "IV Piperacillin-tazobactam"),
  time_point = c("start", "end"),
  date = c("2023-04-10","2023-04-25")) %>% 
  mutate(date = as_date(date))

therapy_2 <-tibble(
  antibiotic = c("PO co-trimoxazole", "PO co-trimoxazole"),
  time_point = c("start", "end"),
  date = c("2023-04-10","2023-04-25")) %>% 
  mutate(date = as_date(date))

inflammatory_markers <- tibble(
  date = c("2023-04-10", "2023-04-12"),
  value = c("38.1", "37.8")) %>%
  mutate(date = as_date(date))

p1 <- therapy_1 %>%
  ggplot(aes(x = date)) +
  geom_line(aes(y = antibiotic, colour = antibiotic)) +
  theme(legend.position = "none")

p2 <- therapy_2 %>%
  ggplot(aes(x = date)) +
  geom_line(aes(y = antibiotic, colour = antibiotic)) +
  theme(legend.position = "none")

default <- inflammatory_markers %>%
  ggplot(aes(x = date)) +
  geom_point(aes(y = value))

desired <- inflammatory_markers %>%
  ggplot(aes(x = date)) +
  geom_point(aes(y = value)) +
  theme(axis.title.y = element_text(margin = margin(r = -160)))

# default output
p1 / default

# desired output
p1 / desired

# when length of y-axis labels shortened
p2 / desired

创建于2023-05-08使用reprex v2.0.2

5ssjco0h

5ssjco0h1#

不同的足以值得第二个答案(海事组织)。如果你愿意使用其他包,你也可以使用egg::ggarrange,它应该能满足你的需要。

library(egg)

ggarrange(p1, desired)

ggarrange(p2, desired)

创建于2023-05-08使用reprex v2.0.2

l7mqbcuq

l7mqbcuq2#

这实际上并不是微不足道的(与拼凑)。我建议的解决办法也不会是完美的。我认为最简单的方法是使用自定义注解作为y轴标题,而不是真实的y轴标题。它并不完美,因为图的大小仍然不同,注解位置将根据x比例进行定位。

## adding a custom annotation to your inferior panel. 
desired <-
  inflammatory_markers %>%
  ggplot(aes(x = date)) +
  geom_point(aes(y = value)) +
  ## annotate with geom_text and not annotate, because you are using dates
  ## and you want to use "nudge_x" which doesn't work with annotate
  geom_text(
    data = data.frame(), aes(
      label = "value",
      x = min(inflammatory_markers$date),
      y = 1.5
    ),
    angle = 90, nudge_x = -.4
  ) +
  ## limit coordinates and turn clipping off
  coord_cartesian(xlim = range(inflammatory_markers$date), clip = "off") +
  ## remove y label
  labs(y = NULL)

# default output
p1 / desired

p2 / desired

创建于2023-05-08使用reprex v2.0.2

相关问题