关于r:在离散的x轴上绘制geom_vline

Draw geom_vline in discrete x axis

我在绘图的x轴上绘制离散(因子)水平的垂直线时遇到麻烦。在此解决方案中,似乎正在使用ggplot2

中的因子水平绘制垂直线

但是这不能与geom_tile一起使用吗?

基本上,要删除geom_tile中的空白,我需要将numeric x值转换为因子水平。但同时我想用数字值绘制geom_vline

这是什么问题

1
2
3
4
5
6
7
8
9
10
 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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轴元素标记为原始值:

1
2
3
4
5
6
7
8
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