【问题标题】:Draw geom_vline in discrete x axis在离散 x 轴上绘制 geom_vline
【发布时间】:2018-06-15 06:35:22
【问题描述】:

我无法在绘图的 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)

要删除geom_tile 中的空格,需要将x 转换为factor(x) 但是当我这样做时 geom_vline 消失了!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    一种解决方案可能是修改您的数据 - 将其变成伪因素

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

    【讨论】:

    • 这是一个绝妙的解决方案。但为什么它必须如此复杂?我的意思是在这个post 中它可以工作,但它不能与geom_tile 一起工作?正如@Len 提到的,没有 x=6 但我认为应该有更简单的方法?我只是想知道。
    • 此解决方案在 y 轴和块“2”的开头之间添加了一堆空格。当您设置 panel.background = element_blank() 时,与 x 轴相比,这个添加的空间看起来很奇怪。有没有办法去掉这个空间?
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2020-02-05
    • 2017-09-25
    • 1970-01-01
    相关资源
    最近更新 更多