Daniel Winkler Daniel Winkler - 1 year ago 65
R Question

Plotting a function that is not defined for all values with ggplot2

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)

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 Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download