marcel
marcel

Reputation: 417

How to open new plot window during plot

I am working on a bit of code that creates a plot consisting of multiple individual graphs, one per ID, showing longitudinal data. For visual purposes, I am limiting the number of graphs to 20 per plot using par, but there are more than 20 IDs in the dataset, and therefore I need multiple plots.

Current problem: how to avoid overwriting an earlier plot with a new plot once the code moves beyond the 20th (or N*20th) ID. I think I need to use plot.new(), but not clear how to work this in, and could not find previous post that exactly addressed this.

My code:

# Create sample data by sampling
Start <- as.Date("2012-01-01")
End <- as.Date("2013-01-01")
data1 <- data.frame(ID = sort(rep(seq(64),3)), VisitDate = sort((Start + sample.int(End-Start, 192))), Count = rnorm(192, mean = 300, sd = 12), Treat =  sample(0:1, 192, replace = TRUE))

# calculate days elapsed since start date, by ID
data1$VisitDate <- with(data1,as.Date(VisitDate,format="%y-%b-%d"))
data1$Days <- unlist(with(data1,tapply(VisitDate,ID,function(x){x-x[1]})))

#Define plot function
plot_one <- function(d){
 with(d, plot(Days, Count, t="n", tck=1, main=unique(d$ID), cex.main = 0.8, ylab = "", yaxt = 'n', xlab = "", xaxt="n",  xlim=c(0,8), ylim=c(0,500))) # set limits
    grid(lwd = 0.3, lty = 7)
    with(d[d$Treat == 0,], points(Days, Count, col = 1)) 
    with(d[d$Treat == 1,], points(Days, Count, col = 2))
}

#Create multiple plot figure
par(mfrow=c(4,5), oma = c(0.5,0.5,0.5,0.5), mar = c(0.5,0.5,0.5,0.5))
plyr::d_ply(data1, "ID", plot_one) 

Upvotes: 2

Views: 2828

Answers (1)

gung - Reinstate Monica
gung - Reinstate Monica

Reputation: 11893

If you are using windows, you call windows(). If you are using a Mac, you call quartz(). These will open a new device so that your next call to (e.g.) plot() will not overwrite your existing plots.

Upvotes: 3

Related Questions