Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotting multiple geom-vline in a graph

Tags:

r

ggplot2

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?

like image 508
Fabio Correa Avatar asked Feb 06 '19 16:02

Fabio Correa


2 Answers

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)
like image 133
RLave Avatar answered Nov 10 '22 12:11

RLave


ggplot(df1, aes(x = x, y = y)) +
    geom_line() +
    sapply(vertical.lines, function(xint) geom_vline(aes(xintercept = xint)))
like image 4
d.b Avatar answered Nov 10 '22 14:11

d.b