nj2012
nj2012

Reputation: 105

Combaning Multiple plots into a Single plot

I am writing a code to generate four stimulations and then generate graphs. My code works, but I want instead of generating four graphs I want to combine them all in one graph. How can I do that?

My code:

queueSimulation <- function(arriverate, servrate, endtime) {
    queue = numeric(0)
    arrivetimes = rexp(10000, arriverate)
    servtimes = rexp(10000, servrate)

    clock = 0.0 
    clist=c() 
    qlist=c()
    while(clock <= endtime) {
       if(length(queue) > 0 && queue[1] < arrivetimes[1]) {
          clock = clock + queue[1]
          queue = queue[-1]   
       }   
       else {
          clock = clock + arrivetimes[1]
          queue[length(queue) + 1] = servtimes[1]
          arrivetimes = arrivetimes[-1]
          servtimes = servtimes[-1]
       }   

    #queue_size= length(round(clock, 2))
       clist = c(clist , clock)
       qlist = c(qlist , length(queue))
    }   
    a<-data.frame(time=clist , qsize=qlist)
    print(a)
    mean1<-mean(qlist)
    cat("Average :", mean1, "\n")
    plot(a)
}

and calling the function:

queueSimulation(1.0, 5.0, 100) 
queueSimulation(2.0, 4.0, 100)
queueSimulation(2.3, 3.5, 100) 
queueSimulation(4.0, 5.0, 100)

Upvotes: 0

Views: 92

Answers (2)

Chargaff
Chargaff

Reputation: 1572

There might be a better solution to this, but how about slightly changing your approach.

1- In your function, add two variables, one for color (cl) and one to tell your function if your plotting the main plot or just adding lines (pl). 1 for main and 0 for lines.

function(arriverate, servrate, endtime,cl,pl) {

2- call your plot with an if statement, and fix your y axis to range from 0 to 200.

if(pl==1){plot(a,col=cl,ylim=c(0,200),type="l")} else{lines(a,col=cl)}}

and then, call your function with theses two variables (cl and pl) :

queueSimulation(1.0, 5.0, 100,"red",1)  
queueSimulation(2.0, 4.0, 100,"blue",0)  
queueSimulation(2.3, 3.5, 100,"green",0)  
queueSimulation(4.0, 5.0, 100,"black",0) 

The problem I see with this is that your simulations can get values way over 200 for the y axis, maybe try to find a way to get max y values in one of your call.

enter image description here

Upvotes: 2

Thomas
Thomas

Reputation: 44525

Take a look at layout, specifically put layout(matrix(1:4,nrow=2)) (or a variant) before you call your plotting functions.

Upvotes: 2

Related Questions