plotting multiple geom-vline in a graph

怎甘沉沦 提交于 2021-02-19 07:46:06

问题


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?


回答1:


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. All the aesthetics need to have the same length, as the error tells you.

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).

Data:

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



回答2:


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


来源:https://stackoverflow.com/questions/54558000/plotting-multiple-geom-vline-in-a-graph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!