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

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 reproduce this same graph (with the same limits as x and y). I was able 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, you would need to smooth the curve and establish the limits of x and y. How can I get a graph similar to the first using ggplot?

    
asked by anonymous 18.03.2015 / 20:23

2 answers

5

You will use stat_function() for function and ylim() and xlim() to set 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)

    
19.03.2015 / 06:23
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'))
    
19.03.2015 / 01:41