0

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.

4
  • Your code is rather unclear what you want, considering you are limiting the length of your x-axis in your initial plot to data$a[1:16], where you wanting to stack all of the data points? Do you have an image of a desired output (or something similar)? Also your limits access 2 different datasets, is that intentional (min of a, max of b)? Commented Sep 25, 2015 at 14:47
  • I removed that bit. It wasn't necessary. Thanks Commented Sep 25, 2015 at 14:49
  • Can you show, how one plot looks like? your points are outside of plot and they are not being plotted. What is the desired output? Commented Sep 25, 2015 at 14:51
  • Ah! sorry. I fail miserably in creating artificial data. Now I have fixed my question. This should work fine Commented Sep 25, 2015 at 15:01

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.