使用 facet 和 "free" 刻度调整 ggplot2 中的 y 轴限制。

4

以下是我可以制作的情节:

data <- data.frame(Patient = rep(seq(1, 5, 1), 2),
                   Treatment = c(rep("Pre", 5), rep("Post", 5)),
                   Gene.1 = c(rnorm(5, 10, 5), rnorm(5, 50, 5)),
                   Gene.2 = c(rnorm(5,10,5), rnorm(5, 10, 5)))

data %>%
  gather(Gene, Levels, -Patient, -Treatment) %>%
  mutate(Treatment = factor(Treatment, levels = c("Pre", "Post"))) %>%
  mutate(Patient = as.factor(Patient)) %>%
  ggplot(aes(x = Treatment, y = Levels, color = Patient, group = Patient)) +
  geom_point() +
  geom_line() +
  facet_wrap(. ~ Gene, scales = "free") +
  theme_bw() +
  theme(panel.grid = element_blank())

示例图

"free"比例函数非常好用,但是我想要做出这两个规格/调整:

  1. Y轴从0开始

  2. 将上限y值增加约10%,以便我稍后可以在Photoshop中添加一些注释(p值等)时有一些空间。

另一种策略可能是制作单独的图并将它们组合在一起,但是如果有许多方面元素,则会变得有点繁琐。

1个回答

4

首先,使用随机数据进行重现需要一个种子。我开始使用了set.seed(42),但它生成了负值,导致完全无关的警告。有点懒,我把种子改成了set.seed(2021),找到了所有正值。

对于#1,我们可以添加limits=,在?scale_y_continuous的帮助文档中说明:

  limits: One of:

            • 'NULL' to use the default scale range

            • A numeric vector of length two providing limits of the
              scale. Use 'NA' to refer to the existing minimum or
              maximum

            • A function that accepts the existing (automatic) limits
              and returns new limits Note that setting limits on
              positional scales will *remove* data outside of the
              limits. If the purpose is to zoom, use the limit argument
              in the coordinate system (see 'coord_cartesian()').

所以我们将使用c(0, NA)

对于Q2,我们将添加expand=,在同一位置有文档记录。

data %>%
  gather(Gene, Levels, -Patient, -Treatment) %>%
  mutate(Treatment = factor(Treatment, levels = c("Pre", "Post"))) %>%
  mutate(Patient = as.factor(Patient)) %>%
  ggplot(aes(x = Treatment, y = Levels, color = Patient, group = Patient)) +
  geom_point() +
  geom_line() +
  facet_wrap(. ~ Gene, scales = "free") +
  theme_bw() +
  theme(panel.grid = element_blank()) +
  scale_y_continuous(limits = c(0, NA), expand = expansion(mult = c(0, 0.1)))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接