Replaced trn by ifelse(m==1,1,trn) in the 2nd and 3rd plots
Added na.rm=T to min() and max()
Added ifelse(trn==5,2,1) to for (m in x:nm)
Set ns=1 and nv=1
Fixed the legend when trn==5
Replaced for (s in 1:ns) by s=ns