Reputation: 3805
I have a dataframe with 1104 rows and 2 columns
a<-rep(1998:2013,times=69)
b<-rnorm(1104)
data<-data.frame(a,b)
What I am trying to do is plot the first 48 rows in the following fashion:
plot(data$b[1:16] ~ data$a[1:16],col="red")
points(data$b[17:32] ~ data$a[17:32],col="green")
points(data$b[33:48] ~ data$a[33:48],col="blue")
This will give me a graph with three sets of data on it. Then I want to repeat this for the next set of 48 rows, something like this:
plot(data$b[49:64] ~ data$a[1:16])
points(data$b[65:80] ~ data$a[65:80])
points(data$b[81:96] ~ data$a[81:96])
And I want to keep repeating it till the 1104th row
plot(data$b[1057:1072] ~ data$a[1057:1072])
points(data$b[1073:1088] ~ data$a[1073:1088])
points(data$b[1089:1104] ~ data$a[1089:1104])
Is there any way I can put this in a loop? This implies that I will have 23 plots.
Thank you for your help.
Upvotes: 0
Views: 766
Reputation: 3711
I would add some column in initial dataset.
set.seed(1)
a<-rep(1998:2013,times=69)
b<-rnorm(1104)
set<-rep(1:23,each=48)
col<-rep(c("red","green", "blue"),each=16, times=23)
data<-data.frame(a,b, set, col)
I like to work with ggplot, but you use base if you want
library(ggplot2)
pdf("multplot.pdf")
for (x in 1:23){
#subset data based on set
df.s<-subset(data, set==x)
g<-ggplot(df.s, aes(x=a,y=b, color=col))+geom_point()
print(g)
}
dev.off()
in base R
pdf("multplot2.pdf")
for (x in 1:23){
df.s<-subset(data, set==x)
#the `col` column is not used
plot(df.s$b[1:16] ~ df.s$a[1:16],col="red")
points(df.s$b[17:32] ~ df.s$a[17:32],col="green")
points(df.s$b[33:48] ~ df.s$a[33:48],col="blue")
}
dev.off()
Upvotes: 1