kanpu
kanpu

Reputation: 261

How can I use geom_vline with string x-xis

The code is like this:

dt5 <- data.frame(x=c("aa", "bb", "cc", "dd"), y=c(1,2,3,4))
p <- ggplot(dt5)    
p <- p + geom_point(aes(x=x, y=y, group=x))

All the above code workes OK. But I want to add vline in the "bb" and "cc". So use the following code:

v <- c("bb", "cc")
p <- p + geom_vline(xintercept=c)

Since I don't have enough right to put up the image. But any one who run the code can see the vline is not shown as we thought.

I tried use as.numeric just as when x-axis is Date, but it failed. Also I tried use v <- c(2, 3), but it also failed.

So how can use geom_vline when the x-axis is string?

Upvotes: 4

Views: 398

Answers (1)

Roland
Roland

Reputation: 132969

The documentation of geom_vline could be improved. You can't pass it characters.

v <- factor(c("bb", "cc"), 
            levels=c("aa", "bb", "cc", "dd"))

p + geom_vline(xintercept = as.integer(v))

Upvotes: 3

Related Questions