Sebastian Sauer
Sebastian Sauer

Reputation: 1673

Problems adding a vline to ggplot barplot

I am trying to add a vertical line to a ggplot barplot (x axis is continuous). One version works as I expected it to, a second version produces an error. I do not understand why.

Basically I have a vector ("alter") with some numbers, and I want to plot the frequencies of the values:

alter <- c(19, 23, 24, 31, 32, 43, 51, 54, 54)
alter.table <- table(alter) # add frequencies

alter.table.df <- data.frame(alter.table)
alter.table.df$alter <- as.numeric(as.character(alter.table.df$alter)) # convert from factor to numeric

alter.table.df$Freq <- as.numeric(alter.table.df$Freq)

alter.mean <- mean(alter, na.rm = T)
alter.md <- median(alter, na.rm = T)


library(ggplot2)

Version A) does work:

p <- ggplot(alter.table.df, aes(x = alter, y = Freq)) + geom_bar(stat = "identity") 
p

p2 <- p + geom_vline(xintercept = alter.mean, colour = "red") +    geom_vline(xintercept = alter.md, colour = "blue") 
p2

Version B) does not work/produces error:

px <- ggplot(alter.table.df, aes(x = alter, y = Freq)) + geom_bar(stat = "identity") + geom_vline(xintercept = 37, colour = "red") + geom_vline(xintercept = 32, colour = "blue") 

So, it appears if I add the geom_vlines seperately to a new plot, it works out. If I try to put it all in one plot, it fails. I do not understand what the problem is.

Any help is greatly appreciated.

Thanks! Sebastian

Upvotes: 1

Views: 1616

Answers (1)

Koundy
Koundy

Reputation: 5503

No need to call geom_vline twice. You can just give a vector of values as input to xintercept Like

    px <- ggplot(alter.table.df, aes(x = alter, y = Freq)) + geom_bar(stat = 
"identity") + geom_vline(xintercept = c(37,32), colour = "red")

Upvotes: 2

Related Questions