[R] Simple plot loop
Jim Lemon
jim at bitwrit.com.au
Thu May 3 12:40:13 CEST 2012
On 05/03/2012 05:50 PM, Ben Neal wrote:
> Trying to plot multiple lines from a simple matrix with headers (eight observations per column). I will be doing a number of these, with varying numbers of columns, and do not want to enter the header names for each one (I got frustrated and just wrote them out, which did work).
>
> Data reads fine, first plot is fine, but when i use the code at the bottom for a for i loop it tells me that x and y do not match. . .
>
> One other issue is that I would prefer not to specify the first column either, but when I enter Plot(MONTH, Data2[2] . . . it also does not plot. Should this not call the second column?
>
> Thank you very much for any comments. I know this is simple, but I appreciate any assistance. Cheers, Ben
>
> #########################################
>
> # LOAD DATA FROM CSV
> library(zoo)
> setwd("/Users/benjaminneal/Documents/All Panama/1110_Panama/CNAT_Segmenting")
> Data = read.csv("120503_CNAT_Summary.csv", header=T)
>
> #fill in missing data from last observation
> Data2<- na.locf(Data)
> attach(Data2)
>
> # PLOT ALL ON ONE CHART
> plot(MONTH,T102, type="o", ann="False", ylim=c(1, 100), pch=22, lty=2, col="red")
> title(main="5m and 10 m Colpophylia natans colonies over time", ylab="% live coral / colony",
> xlab="Months", col.main="black", font.main=4)
>
> lines(MONTH,T162, type="o", pch=22, lty=2, col="red")
> lines(MONTH,T231, type="o", pch=22, lty=2, col="green")
> lines(MONTH,T250, type="o", pch=22, lty=2, col="green")
>
> ##(many other similar lines here, with entered column headers . . . up to 75)
>
> lines(MONTH,T373, type="o", pch=22, lty=2, col="blue")
> lines(MONTH,T374, type="o", pch=22, lty=2, col="blue")
> lines(MONTH,T377, type="o", pch=22, lty=2, col="blue")
>
> # Tried to add lines another way with for i loop, but this is the part not working
> for (i in 2:length(Data2)) {
> lines(MONTH, i, type="o", pch=22, lty=2, col="blue"))
> }
> #####################################
>
Hi Ben,
I think what you may want in your loop is this:
for(column in names(Data2)[2:length(Data2)])
lines(MONTH,column,type="o",pch=22,lty=2,col="blue")
But, if you want the first two lines to be green, you'll probably have
to get a vector of colors:
colorvec<-rep("blue",length(Data2))
colorvec[1]<-"red"
colorvec[2:3]<-"green"
and change the above to:
columnnames<-names(Data2)
for(column in 2:length(Data2))
lines(MONTH,columnnames[column],type="o",pch=22,lty=2,col=colvec[column])
Jim
More information about the R-help
mailing list