4
votes

I am producing a ggplot which looks at a curve in a dataset. When I build the plot, ggplot is automatically adding fill to data which is on the negative side of the x axis. Script and plot shown below.

ggplot(df, aes(x = Var1, y = Var2)) +
 geom_line() + 
 geom_vline(xintercept = 0) +
 geom_hline(yintercept = Var2[1])

enter image description here

Using base R, I am able to get the plot shown below which is how it should look.

plot(x = df$Var1, y = df$Var2, type = "l",
 xlab = "Var1", ylab = "Var2")
abline(v = 0) 
abline(h = df$Var2[1])

enter image description here

If anyone could help identify why I might be getting the automatic fill and how I could make it stop, I would be very appreciative. I would like to make this work in ggplot so I can later animate the line as it is a time series that can be used to compare between other datasets from the same source.

Can add data if necessary. Data set is 1561 obs long however. Thanks in advance.

1

1 Answers

4
votes

I guess you should try

ggplot(df, aes(x = Var1, y = Var2)) +
  geom_path() + 
  geom_vline(xintercept = 0) +
  geom_hline(yintercept = Var2[1])

instead. The geom_line()-function connects the points in order of the variable on the x-axis.

Take a look at this example

dt <-  data.frame(
  x = c(seq(-pi/2,3*pi,0.001),seq(-pi/2,3*pi,0.001)),
  y = c(sin(seq(-pi/2,3*pi,0.001)), cos(seq(-pi/2,3*pi,0.001)))
  )

ggplot(dt, aes(x,y)) + geom_line()

The two points with x-coordinate -pi/2 will be connected first, creating a vertical black line. Next x = -pi/2 + 0.001 will be processed and so on. The x values will be processed in order.

Therefore you should use geom_path() to get the desired result

dt <-  data.frame(
  x = c(seq(-pi/2,3*pi,0.001),seq(-pi/2,3*pi,0.001)),
  y = c(sin(seq(-pi/2,3*pi,0.001)), cos(seq(-pi/2,3*pi,0.001)))
 )

ggplot(dt, aes(x,y)) + geom_path()