Fabio Correa
Fabio Correa

Reputation: 1363

plotting multiple geom-vline in a graph

I am trying to plot two ´geom_vline()´ in a graph.

The code below works fine for one vertical line:

x=1:7
y=1:7
df1 = data.frame(x=x,y=y)
vertical.lines <- c(2.5)

ggplot(df1,aes(x=x, y=y)) +
  geom_line()+
  geom_vline(aes(xintercept = vertical.lines))

However, when I add the second desired vertical line by changing

vertical.lines <- c(2.5,4), I get the error:

´Error: Aesthetics must be either length 1 or the same as the data (7): xintercept´

How do I fix that?

Upvotes: 12

Views: 19723

Answers (2)

RLave
RLave

Reputation: 8364

Just remove aes() when you use + geom_vline:

ggplot(df1,aes(x=x, y=y)) +
  geom_line()+
  geom_vline(xintercept = vertical.lines)

It's not working because the second aes() conflicts with the first, it has to do with the grammar of ggplot.

You should see +geom_vline as a layer of annotation to the graph, not like +geom_points or +geom_line which are for mapping data to the plot. (See here how they are in two different sections).

All the aesthetics need to have either length 1 or the same as the data, as the error tells you. But the annotations can have different lengths.

Data:

x=1:7
y=1:7
df1 = data.frame(x=x,y=y)
vertical.lines <- c(2.5,4)

Upvotes: 23

d.b
d.b

Reputation: 32548

ggplot(df1, aes(x = x, y = y)) +
    geom_line() +
    sapply(vertical.lines, function(xint) geom_vline(aes(xintercept = xint)))

Upvotes: 7

Related Questions