0

我有一个由构面绘制和分隔的数据库。第一行 (row a) 的刻面需要 0.5 处的水平线,而第二行 (row ) 的刻面需要 1 处的线。按照这个示例b,我已经部分实现了我的目标。但是,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.

在此处输入图像描述

4

2 回答 2

1

要让截距显示在特定面板中,您需要将Rowin 中的引用facet_grid作为变量 inside 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")

在此处输入图像描述

于 2021-03-16T22:53:32.433 回答
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
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,以便它知道如何处理它们
于 2021-03-16T22:56:35.230 回答