0

I'm trying to draw 3 overlaying curves (please see my R code below) in any 3 different colors (e.g., red, green, blue). I have tried the following but don't get neatly shaped plots.

Could this be looped easily in "R base"? Or there are some other possibilities?

 N  <- c(120, 528, 828)
df1 <- c(3, 3, 3)
df2 <- c(108, 516, 816)
 f  <- c(20, 20, 20) 


## 3 Plots:

Likelihood = curve( df(f, df1, df2, ncp = (x * N) / (1 - x) ) ,
  col = 'red4', lwd = 3, from = 0, to = 1, n = 1e4)
0

1 Answer 1

1

With a basic loop you could try something like:

for(i in 1:length(N)) {
    add <- if(i == 1) FALSE else TRUE
    curve( df(f[i], df1[i], df2[i], ncp = (x * N[i]) / (1 - x) ) ,
           col = i, lwd = 3, from = 0, to = 1, n = 1e4, add=add)
}

Not the prettiest but using the basics. You should definitely explore ggplot2.

To avoid that some curves not complete, you could first get the values for each curve, estimate their ranges and then plot them. For example:

# function to get the values of each curve
curve_ <- function(x, i) df(f[i], df1[i], df2[i], ncp = (x * N[i]) / (1 - x))

# estimate the values of each curve
curves <- lapply(1:length(N), function(i) {
    x <- seq(0,1,length.out = 1e4)
    curve_(x, i)
})

# estimate the ranges
ranges_ <- sapply(curves, range, na.rm=T)

# plot using the ranges as plotting parameters (ylim)
for (i in 1:length(curves)) {
    if(i == 1) {
        plot(curves[[i]], type='l', col=i, xlim=c(0,length(curves[[i]])), ylim=c(min(ranges_[1,]), max(ranges_[2,])))
    } else {
        lines(curves[[i]], col=i)
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, is it possible to put the tallest one be plotted first and then the 2 other one be plotted after that?
Thank you, for color changes, should I be defining a separate vector?
Yes. You can define a vector with the colours and then use it with col=color_vector[i]
for (i in 1:10) plot(rnorm(10))
spadarian, can I send you an R file before asking a question, it is a loop question and everything works fine except when I want to get a png file for each "i", the png file come out blank?

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.