Reputation: 4645
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)
to remove white space in geom_tile
need to convert to x to factor(x)
but when I do this geom_vline disappears!
Upvotes: 4
Views: 4474
Reputation: 28369
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)
Upvotes: 4