0

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)
1
  • 1
    in my opinion it is best to separate the plotting step from the data accumulation. So I would suggest that you collect the data frames by running your function several times, e.g. in a list, and only then plot all the data (e.g with matplot). This way you won't get into trouble of having to rescale axes, etc. Is there a specific reason to add lines in a chronological sequence like your question suggests? Commented Jun 3, 2013 at 20:34

2 Answers 2

2

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

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

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.