[R] Producing plot using polygon function

Uwe Ligges ligges at statistik.tu-dortmund.de
Sat Nov 19 19:26:46 CET 2011



On 18.11.2011 23:48, avinash barnwal wrote:
> Hi,
>
> I am looking forward to fill the plot using conditions on variables a2 and
> a3. Whenever variable(a2) goes above variable(a3) i fill it with some color
> .
>
> I am storing the coordinates of a2 and a3 in x and y as well as time where
> it is occurring . But it is not producing properly. I must be wrong
> in assigning  coordinates.
> What should be the correct way to produce the desired plot?
>
> Thanks in advance
> ######################################################################################################
> x<-vector()
> y<-vector()
> temp_time<-vector()

Defining *empty* vectors is almost never what you really want to do.

> for(i in 1:length)

Running a loop 1:length is dangerous if a length is < 1, run it 
seq_along(.).

> {
> if(a2[i]>a3[i])
> {
> j<-j+1
> x[j]<-a2[i]
> y[j]<-a3[j]

You meant a3[i], I guess.

> temp_time<-time[i]
> }
> }

At the end of this loop, this obviously simplifies to:

l <- a2 > a3
x <- a2[l]
y <- a3[l]
temp_time <- time[length]


> time<-q[,1]
> a2<-q[,3]
> a3<-q[,4]
> plot(time,a2type='l',col='red',ylab='',xlab=" ",axes=FALSE)
> lines(time,a3,col='blue',ylab='',xlab=" ")
> polygon(c(time[1:j],time[1:j]),c(x,y),col="grey")

Since you don't use anything from inside your loop here, why do you run 
that at all? Is this homework?

Uwe Ligges



More information about the R-help mailing list