Carly
Carly

Reputation: 125

Graphing Scatter Plots in R

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?

Upvotes: 1

Views: 441

Answers (4)

vonjd
vonjd

Reputation: 4380

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

Upvotes: 0

beroe
beroe

Reputation: 12326

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])
}

Upvotes: 1

Greg Snow
Greg Snow

Reputation: 49660

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.

Upvotes: 2

keithing
keithing

Reputation: 281

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.

Upvotes: 1

Related Questions