7

Using ggplot, is there a way of graphing several functions on the same plot? I want to use parameters from a text file as arguments for my functions and overlay these on the same plot.

I understand this but I do not know how to add the visualized function together if I loop through.

1
  • Why don't you add a stat_function in every loop e.g. p <- p + stat_function(fun = dnorm, colour="red") and at the end: print(p) ? Take a look at this had.co.nz/ggplot2/stat_function.html Commented Feb 10, 2010 at 15:07

1 Answer 1

7

Here is an implementation of Hadley's idea.

library(ggplot2)
funcs <- list(log,function(x) x,function(x) x*log(x),function(x) x^2,  exp)
cols <-heat.colors(5,1)
p <-ggplot()+xlim(c(1,10))+ylim(c(1,10))
for(i in 1:length(funcs))
    p <- p + stat_function(aes(y=0),fun = funcs[[i]], colour=cols[i])
print(p)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the suggestion, but I can't get this code to work as it is. I'm not very familiar with the R syntax, apologies if I'm missing something obvious.
You will need to have ggplot2 loaded, which you can do by calling library(ggplot2) . If you are still having problems, please share what error you are getting.
Maybe you missed the installation step: install.packages("ggplot2") HIH
Thanks - it works now. I'm not sure what I was doing wrong previously. I did import ggplot2, but I was getting an error about no layers on the plot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.