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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.