3

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

pogibas
  • 27,303
  • 19
  • 84
  • 117
Alexander
  • 4,527
  • 5
  • 51
  • 98

1 Answers1

4

One solution could be to modify your data - turn it into 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

Plot value ranks instead of values and label x-axis elements as original values:

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

pogibas
  • 27,303
  • 19
  • 84
  • 117
  • that is a brilliant solution. But why it have to be so complex ?. I mean in this [post](https://stackoverflow.com/questions/50534862/drawing-vertical-line-with-factor-levels-in-ggplot2) it is working but it is not working with `geom_tile`? and as @Len mentions there is no x=6 but I am thinking there should be a more simpler way? I just wonder. – Alexander Jun 15 '18 at 06:58
  • This solution adds a bunch of space between y axis and the beginning of block "2." When you set panel.background = element_blank(), this added space looks strange compared to the x axis. Is there a way to remove this space? – nad7wf Nov 23 '19 at 08:45