Daniel Winkler - 3 months ago 10

R Question

Hi I am plotting functions like these:

`eq <-function(x) ifelse(x<(-1)|x>1|(x>(-1)& x<1),(x/((x^2)-1)),NA)`

eq2 <-function(x) ifelse(x<(-sqrt(2))|x>sqrt(2)|x>(-sqrt(2))&x<sqrt(2),(x/((x^2)-2)), NA)

eq3 <-function(x) ifelse(x<(-sqrt(3))|x>sqrt(3)|x>(-sqrt(3))&x<sqrt(3),(x/((x^2)-3)), NA)

library(ggplot2)

ggplot(data.frame(x=c(-3,3)), aes(x))+

stat_function(fun=eq,geom="line", aes(colour="x/(x^2-1)"))+

stat_function(fun=eq2,geom='line',aes(color='x/(x^2-2)')) +

stat_function(fun=eq3,geom='line', aes(color ='x/(x^2-3)'))+

scale_x_continuous(breaks = (seq(-3, 3, by = 0.5)))+ ylim(-3,3)

This creates a plot but the lines seem to stop randomly. I would like them to continue to the edge of the plot. I am fairly certain my code is equivalent to the answer to this question Plotting Noncontinuous Function ggplot2.

Any suggestions?

Answer

`ylim(-3,3)`

is causing data values outside that range to be removed from the plot (which also happens with `scale_y_continuous`

). Use `coord_cartesian`

to set limits without removing data outside those limits:

```
ylim(-10,10) +
coord_cartesian(ylim=c(-3,3))
```

In the code above, I've also set a `ylim`

range, but one much larger than the range limits for the graph. This is to avoid vertical lines where the function values blow up to `Inf`

or `-Inf`

.