代码之家  ›  专栏  ›  技术社区  ›  Alexander

在离散X轴上绘制几何图形

  •  1
  • Alexander  · 技术社区  · 8 年前

    在绘图的x轴上以离散(因子)级别绘制垂直线时遇到问题。在这个解决方案中,它似乎起作用了 drawing vertical line with factor levels in ggplot2

    但是这不适用于 geom_tile ?

    基本上,要删除geom_tile中的空白,我需要转换为 numeric x值到因子级别。但同时我想画一个 geom_vline 有一个数值。

    这就是问题所在

     df <- data.frame(
      x = rep(c(2, 5, 7, 9, 12), 2),
      y = rep(c(1, 2), each = 5),
      z = factor(rep(1:5, each = 2)))
    
    
     library(ggplot2)
     ggplot(df, aes(x, y)) +
      geom_tile(aes(fill = z), colour = "grey50")+
       geom_vline(aes(xintercept=6),linetype="dashed",colour="red",size=1)
    

    enter image description here

    删除空白 土工织物 需要转换为x factor(x) 但当我这么做的时候,地球线就消失了!

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  3
  •   pogibas    8 年前

    一种解决方案可能是修改数据-将其转换为 拟因素 .

    # Get rank of each x element within group
    df$xRank <- ave(df$x, df$y, FUN = rank)
    
        x y z xRank
    1   2 1 1      1
    2   5 1 1      2
    3   7 1 2      3
    4   9 1 2      4
    5  12 1 3      5
    6   2 2 3      1
    7   5 2 4      2
    8   7 2 4      3
    9   9 2 5      4
    10 12 2 5      5
    

    打印值列组而不是值,并将X轴元素标记为原始值:

    library(ggplot2)
    ggplot(df, aes(xRank, y)) +
        geom_tile(aes(fill = z), colour = "grey50") +
        # On x axis put values as labels
        scale_x_continuous(breaks = df$xRank, labels = df$x) +
        # draw line at 2.5 (between second and third element)
        geom_vline(aes(xintercept = 2.5), 
                   linetype = "dashed", colour = "red",size = 1)
    

    enter image description here