1

I'm trying to graph a simulated model of infectious disease spread.

My data has three columns, x, y, and infection time. I need to plot each point (x coordinate, y coordinate) at each time (t), where t runs between 1 and 4. SO I'm looking for four graphs, one at each time, where the first graphs plots the first infected point, the second plots the infected points at time 1 and 2, etc.

I know I can get multiple graphs using par(mfrow=c(2,2)), but I'm not sure how to incorporate each time into the code. Any suggestions?

Carly
  • 125
  • 3
  • 1
    Help us to help you by providing some sample of your data, this makes your [question/problem reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Jilber Urbina Oct 07 '13 at 15:26

4 Answers4

2

Here is one approach using base graphics:

par(mfrow=c(2,2))

for ( i in 1:4 ) {
  plot( y ~ x, data= mydf[ mydf$time <= i, ] )
}

or

lapply( 1:4, function(tt) plot(x[time<=tt], y[time<=tt]) )

Or other similar approaches depending on what the structure of your data is.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
1

I would use the package ggplot2. Install it using install.packages("ggplot2") and then library(ggplot2) once the packages is installed, try the code:

p <- ggplot(data, aes(x=x,y=y)) + geom_point() + facet_wrap(~t)

I'm pretty sure you could have found this out without asking a question on this site! Be careful to do more research before asking these questions.

keithing
  • 281
  • 1
  • 3
  • 2
    I wholly agree, but keep in mind that @Carly asked on [crossvalidated](http://stats.stackexchange.com) and might not have considered this site at the time. Also, the search function can often fail to retrieve the right stuff when you don't know the exact terms to look for. You got a point, but just sayin'. – Backlin Oct 07 '13 at 15:38
  • I think that this approach will plot only time 2 points in the second facet and only time 3 points in the 3rd facet, etc. (or am I missing something?) The question asked how to plot times 1 and 2 in the second facet/panel, etc. – Greg Snow Oct 07 '13 at 15:46
1

There are about a thousand ways to do this, depending on your original data set. Learning ggplot2 is probably the best in the long run. Using base graphics, though, you can make a plot for each subset of data (and can also use the subset command instead of t<=Ti, customize colors, etc):

par(mfrow=c(2,2))
for (Ti in 1:4){  
    plot(x[t <= Ti], y[t <= Ti])
}

If you are trying to convey the passage of time, you might want to plot the entire range of data invisibly on each plot, to set up the same axes. Then use points or lines to plot the data into each of those identical frames...

par(mfrow=c(4,1))
for (Ti in 1:4){  
  plot(x, y, type="n")
  points(x[t <= Ti], y[t <= Ti])
}
beroe
  • 11,784
  • 5
  • 34
  • 79
0

You can find a good overview here:
http://www.statmethods.net/graphs/scatterplot.html

vonjd
  • 4,202
  • 3
  • 44
  • 68