Michael Michael - 2 months ago 6
R Question

Multiple Curves With Different Domains in a Single Plot ( with ggplot2)

eq = function(x){x^-1}
ggplot(data.frame(x=c(-6,6)), aes(x = x, y=eq(x)))+
geom_line(data=as.data.frame(curve(from=-6, to=-.01, eq)))+
geom_line(data=as.data.frame(curve(from=.01, to=6, eq)))

I am trying to produce a single plot, and this code gives me the plot I want, but with two additional plots, one with each geom_line. I don't understand why those additional two plots are being created.


As @shayaa noted in the comments, curve itself generates plots, which is why you are getting the extra plots. To avoid this, you can just create a dataframe before you plot, and subset it in geom_line:

eq = function(x){x^-1}
df <- data.frame(x =seq(-6, 6, 0.01), y = eq(seq(-6, 6, 0.01)))
ggplot(df) +
  geom_line(data=subset(df, x<=-.01), aes(x = x, y = y)) +
  geom_line(data=subset(df, x>=.01), aes(x = x, y = y))