首页 > 解决方案 > Draw geom_vline in discrete x axis

问题描述

I have trouble with drawing a vertical line in discrete (factor) levels in the x axis of my plot. in this solution it seems to working drawing vertical line with factor levels in ggplot2

but OTH this is not working with geom_tile?

Basically, to remove the white space in the geom_tile I need to convert to numeric x values to factor levels . But at the same time I want to draw a geom_vline with a numeric value.

here is what is the problem

 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

to remove white space in geom_tile need to convert to x to factor(x) but when I do this geom_vline disappears!

enter image description here

标签: rggplot2

解决方案


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

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

在此处输入图像描述


推荐阅读