如何使用 ggplot2 在不同方面为 2x2 排列添加水平线?

How to add horizontal lines in different facets for 2x2 arrangements using ggplot2?

我有一个数据库,它是按刻面绘制和分隔的。第一行(行a)的面需要0.5处的水平线,而第二行(行b)的面需要1处的线。我已经部分实现了以下目标this example。但是,0.5 和 1 处的水平线出现在所有面中。

library(ggplot2)

#Data
values <- c(0.4, 0.6, 0.9, 1.1)
Column <- c("UW", "LW", "UW", "LW")
Row <- c("a", "a", "b", "b")
DF <- data.frame(Row, Column, values)
DF$Column <- factor(DF$Column,
                 levels = c("UW", "LW"))
DF$Row <- factor(DF$Row,
                 levels = c("a", "b"))

#Auxiliar DF
Target <- c("a", "b")
Lines <- c(0.5, 1)
Lines_in_plot <- data.frame(Target, Lines)
Lines_in_plot$Target <- factor(Lines_in_plot$Target)

#Plot
ggplot(data = DF, aes(y = values)) +
  geom_bar() +
  facet_grid(Row~Column,
             scales = "free") +
  geom_hline(data = Lines_in_plot,
             yintercept = Lines,
             linetype = "dashed",
             color = "red")

此 MWE 运行但显示以下警告消息:

geom_hline(): Ignoring `data` because `yintercept` was provided.

为了在特定面板中显示拦截,您需要将 facet_grid 中引用的 Row 作为 Lines_in_plot 中的变量提供。您还需要将 yintercept 放在 aes 中,以便 ggplot 知道引用 Lines_in_plot 数据 yintercept.

...
#Auxiliar DF
Row <- c("a", "b")
Lines <- c(0.5, 1)
Lines_in_plot <- data.frame(Row, Lines)
Lines_in_plot$Row <- factor(Lines_in_plot$Target)

#Plot
ggplot(data = DF, aes(y = values)) +
  geom_bar() +
  facet_grid(Row~Column,
             scales = "free") +
  geom_hline(data = Lines_in_plot,
             aes(yintercept = Lines),
             linetype = "dashed",
             color = "red")

这是您的解决方案:


library(ggplot2)

#Data
values <- c(0.4, 0.6, 0.9, 1.1)
Column <- c("UW", "LW", "UW", "LW")
Row <- c("a", "a", "b", "b")
DF <- data.frame(Row, Column, values)
DF$Column <- factor(DF$Column,
                 levels = c("UW", "LW"))
DF$Row <- factor(DF$Row,
                 levels = c("a", "b"))

#Auxiliar DF
Row <- c("a", "b")
Lines <- c(0.5, 1)
Lines_in_plot <- data.frame(Row, Lines)
Lines_in_plot$Row <- factor(Lines_in_plot$Row)

#Plot
ggplot(data = DF, aes(y = values)) +
  geom_bar() +
  facet_grid(Row~Column,
             scales = "free") +
  geom_hline(data = Lines_in_plot,
             aes(yintercept = Lines),
             linetype = "dashed",
             color = "red")

两个变化:

  1. 将y截距移入美学
  2. 将目标重命名为 Row 以匹配 Facet,以便它知道如何处理它们