JustLearning
JustLearning

Reputation: 200

When plotting a curve in R, a piece of the curve gets cut off, not sure why

I am trying to plot this formula. As x approaches 0 from the right, y should be approaching infinity, and so my curve should be going upwards close to y-axis. Instead it gets cut off at y=23 or so.

my_formula = function(x){7.9*x^(-0.5)-1.3}
curve(my_formula,col="red",from=0 ,to=13, xlim=c(0,13),ylim=c(0,50),axes=T, xlab=NA, ylab=NA)

I tried to play with from= parameter, and actually got what I needed when I put from=-4.8 but I have no idea why this works. in fact x doesn't get less than 0, and from/to should represent the range of x values, Do they? If someone could explain it to me, this would be amazing! Thank you!

Upvotes: 2

Views: 804

Answers (2)

thelatemail
thelatemail

Reputation: 93803

This is due mainly to the fact that my_formula(0) is Inf:

So plotting from=0, to=13 in curve means your first 2 values are by default (with 101 points as @Marius notes):

# x
seq(0, 13, length.out=101)[1:2]
#[1] 0.00 0.13

# y
my_formula(seq(0, 13, length.out=101)[1:2])
#[1]      Inf 20.61066

And R will not plot infinite values to join the lines from the first point to the second one.

If you get as close to 0 on your x axis as is possible on your system, you can make this work a-okay. For instance:

curve(my_formula, col="red", xlim=c(0 + .Machine$double.eps, 13), ylim=c(0,50))

Upvotes: 1

Marius
Marius

Reputation: 60060

By default, curve only chooses 101 x-values within the (from, to) range, set by the default value of the n argument. In your case this means there aren't many values that are close enough to 0 to show the full behaviour of the function. Increasing the number of values that are plotted with something like n=500 helps:

curve(my_formula,col="red",from=0 ,to=13, 
      xlim=c(0,13),ylim=c(0,50),axes=T, xlab=NA, ylab=NA, 
      n=500)

Upvotes: 1

Related Questions