首页 > 解决方案 > 使用刻面和“自由”比例调整 ggplot2 中的 y 轴限制

问题描述

这是我可以制作的情节:

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())

示例图

“自由”秤功能很棒,但是,我想做这两个规格/调整:

  1. Y 轴从 0 开始

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

另一种策略可能是制作单独的情节并将它们组合在一起,但是,这会因为许多方面元素而变得有点乏味。

标签: rggplot2

解决方案


首先,随机数据的再现性需要一个种子。我开始使用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).

对于第二季度,我们将添加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)))

在此处输入图像描述


推荐阅读