使用构面和“自由”比例调整 ggplot2 中的 y 轴限制

Dan*_*ang 5 r ggplot2

这是我可以制作的情节:

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())
Run Code Online (Sandbox Code Playgroud)

示例图

“免费”秤功能很棒,但是,我想进行这两个规格/调整:

  1. Y 轴从 0 开始

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

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

r2e*_*ans 5

首先,随机数据的再现性需要种子。我开始使用set.seed(42),但这会产生负值,从而导致完全不相关的警告。由于有点懒,我将种子更改为set.seed(2021),发现了所有积极的结果。

\n

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

\n
  limits: One of:\n\n            \xe2\x80\xa2 \'NULL\' to use the default scale range\n\n            \xe2\x80\xa2 A numeric vector of length two providing limits of the\n              scale. Use \'NA\' to refer to the existing minimum or\n              maximum\n\n            \xe2\x80\xa2 A function that accepts the existing (automatic) limits\n              and returns new limits Note that setting limits on\n              positional scales will *remove* data outside of the\n              limits. If the purpose is to zoom, use the limit argument\n              in the coordinate system (see \'coord_cartesian()\').\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

对于第二季度,我们将添加expand=, 记录在同一位置。

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

在此输入图像描述

\n