How to smooth a curve and define ylim for a given function using ggplot2?

Asked

Viewed 620 times

5

I got the following graph with the curve function:

f1 <- function(x){x^4 - 6*(x^2)}
curve(f1, xlim = c(-3, 3), ylim= c(-10, 5), ylab = expression(x^4 - 6*(x^2)))

However, I would like to use the ggplot2 package to play this same chart (with the same limits of x and y). I managed to develop this simple code:

x <- c(-4:4)
y <- c(x^4 - 6*(x^2))
ggplot() +
   geom_line(aes(x=x, y=y)) 

But I would need to smooth the curve and set the limits of x and y. How can I get a graph similar to the first using ggplot?

2 answers

5


You will use the stat_function() for the function and ylim() and xlim() to define the limits:

library(ggplot2)
x <- c(-4:4)
f1 <- function(x){x^4 - 6*(x^2)}
ggplot(data.frame(x), aes(x)) + stat_function(fun=f1) + ylim(-10, 5) + xlim(-3, 3)

inserir a descrição da imagem aqui

3

Here is an example code:

x = seq(from=-4, to=4, length.out=1000)
y = c(x^4 - 6*(x^2))
print(ggplot(data=data.frame(x=x, y=y), aes(x=x, y=y)) +
      geom_point(colour='red') +
      stat_smooth(se=F, colour='blue') +
      coord_cartesian(xlim=c(-3, 3), ylim=c(-10, 5)))

Or with a legend:

print(ggplot(data=data.frame(x=x, y=y), aes(x=x, y=y)) +
      geom_point(aes(colour='source')) +
      stat_smooth(aes(colour='fit'), se=F) +
      coord_cartesian(xlim=c(-3, 3), ylim=c(-10, 5)) +
      scale_color_discrete(name='type'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.