1

I know how to plot with R's default plotting function. How do I do the same thing as the following R-code in ggplot2?

double <- function(x){
  return(x^2)
}
triple <- function(x){
  return(x^3)
}

xs <- seq(-3,3,0.01)
dou  <- double(xs)
tri <- triple(xs)

plot(rep(xs, 2), c(dou, tri), typ="n")
lines(xs, dou, col="red")
lines(xs, tri, col="green")

Plot

Christian
  • 25,249
  • 40
  • 134
  • 225
  • 1
    See http://stackoverflow.com/questions/5177846/equivalent-of-curve-for-ggplot and http://kohske.wordpress.com/2010/12/25/draw-function-without-data-in-ggplot2/ – Adrian Nov 30 '13 at 23:11

2 Answers2

5

There's no need to apply the functions before plotting when using ggplot2. You can tell ggplot2 to use your functions.

library(ggplot2)
ggplot(as.data.frame(xs), aes(xs)) +
  stat_function(fun = double, colour = "red") + 
  stat_function(fun = triple, colour = "green")

enter image description here

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
2

You can use stat_function, but since you don't use curve in the base plot, I think your are looking for a simple scatter plot with geom_line.

  1. put your data in a data.frame : ggplot2 works with data.frame as data source.
  2. reshape the data in the long format : aes works in the long format , generally you plot x versus y according to a third variable z.

For example:

dat <- data.frame(xs=xs,dou=dou,tri=tri)
library(reshape2)
library(ggplot2)
ggplot(melt(dat,id.vars='xs'),
       aes(xs,value,color=variable))+
  geom_line()

enter image description here

EDIT

Using basic plots you can simplify your plots using curve:

curve(x^3,-3,3,col='green',n=600)
curve(x^2,-3,3,col='red',n=600,add=TRUE)

enter image description here

agstudy
  • 119,832
  • 17
  • 199
  • 261