在离散x轴上绘制geom_vline

时间:2018-06-15 06:35:23

标签: r ggplot2

我在绘图的x轴上以离散(因子)级别绘制垂直线时遇到问题。在这个解决方案中似乎工作enter image description here

但是,这不适用于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

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

Update a column value, replacing part of a string

1 个答案:

答案 0 :(得分:3)

一种解决方案可能是修改您的数据 - 将其转换为伪因子

# 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