简体   繁体   中英

plot for double loop in R

My question is about the for loop in combination with the plot function in R. I want to plot multiple points in one plot. I do not know what is wrong with my functions. Any help please?

DATA
 a x y  z
149 1 1  0
153 1 1 10
160 1 1 10
149 1 2  0
153 1 2  0
160 1 2 10
149 2 1  0
153 2 1  0
160 2 1  5
149 2 2  0
153 2 2  0
160 2 2  5

PCH=0;
plot(c(142,169),c(0,11),type="n")
for(i in unique(DATA$x)) {
  for(j in unique(DATA$y)) {
    PCH=PCH+1
    select <- DATA[i,j]
    X = DATA[select,"a"]; 
    Y = DATA[select,"z"]
    points(X,Y,pch=PCH)
  }  
}

Does this by chance do what you want to achieve?

plot(z~a,data=DATA,
         pch=as.numeric(interaction(x,y)),
         xlim=c(142,169),ylim=c(0,11))

Your selection is wrong. Try the following code:

PCH <- 0
plot(c(142,169), c(0,11), type="n")
for(i in unique(DATA$x)) {
  for(j in unique(DATA$y)) {
    PCH <- PCH+1
    select <- DATA$x == i & DATA$y == j
    X <- DATA[select,"a"] 
    Y <- DATA[select,"z"]
    points(X,Y,pch=PCH)
  }  
}

Note that it is better style to use <- instead of = , as = is also used in other purposes where it has another syntactical meaning. Forthermore, you do not need ; at the end of the line in R.

your X and Y values are off.. you don't need the select statement

  plot(c(142,169),c(0,11),type="n")
  for(i in unique(DATA$x)) {
    for(j in unique(DATA$y)) {
      PCH=PCH+1
      X = DATA[(DATA$x==i) & (DATA$y==j),"a"]; 
      Y = DATA[(DATA$x==i) & (DATA$y==j),"z"]
     (points(X,Y,pch=PCH))
    }  
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM