代码之家  ›  专栏  ›  技术社区  ›  Daniel Valencia C.

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

  •  0
  • Daniel Valencia C.  · 技术社区  · 3 年前

    我有一个数据库,它是按面绘制和分隔的。第一行(行 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.
    

    enter image description here

    0 回复  |  直到 3 年前
        1
  •  1
  •   Jon Spring    3 年前

    为了在特定面板中显示拦截,您需要 Row 提及 facet_grid 可作为内部变量使用 Lines_in_plot .你还想把 yintercept 里面 aes 以便ggplot知道引用 线条_ in_plot 数据为 接受治疗 .

    ...
    #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")
    

    enter image description here

        2
  •  1
  •   CALUM Polwart    3 年前

    以下是您的解决方案:

    
    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,以便它知道如何处理它们