Reputation: 6561
I create a figure containing two plots using a function i.e.
data1<-1:3
basic<-function(data1){
par(mfrow=c(2,1))
plot(data1)
plot(data1)
}
basic(data1)
Now I want to add text to the plots without having to include it in the function. But I can only add text to the bottom plot (see below).
text(x=c(1.5,1.6,1.7),y=c(2,2.1,2.2), labels=c("X","Y","Z"))
How can I add text to the top plot outside of the function? (I have lots of figures I create using the same function but need to place slightly different text labels in slightly different positions on each one). Thanks for any advice.
Upvotes: 4
Views: 4447
Reputation: 49640
Here is one way to do it using the par
command:
data1 <- 1:3
basic <- function(data1) {
out <- list()
par(mfrow=c(2,1))
plot(data1)
out[[1]] <- par(no.readonly=TRUE)
plot(data1)
out[[2]] <- par(no.readonly=TRUE)
invisible(out)
}
pars <- basic(data1)
par(pars[[1]])
par(mfg=c(1,1))
text( x=c(1.5,1.6,1.7), y=c(2,2.1,2.2), labels=c("X","Y","Z") )
par(pars[[2]])
par(mfg=c(2,1))
text( x=c(1.5,1.6,1.7), y=c(2,2.1,2.2), labels=c("A","B","C") )
par(pars[[1]])
par(mfg=c(1,1))
text( x=c(1.7,1.6,1.5), y=c(2,2.1,2.2), labels=c("X","Y","Z") )
par(pars[[2]])
par(mfg=c(2,1))
text( x=c(1.7,1.6,1.5), y=c(2,2.1,2.2), labels=c("A","B","C") )
Upvotes: 2
Reputation: 18749
To do this you can use function split.screen
instead of par(mfrow=...)
or layout
.
split.screen(c(2,1)) # Two rows of plots, one column.
You can then switch from one "screen" to the other using function screen
. See ?split.screen
for more information.
In your example that gives the following:
basic <- function(data1){
split.screen(c(2,1))
screen(1)
plot(data1)
screen(2)
plot(data1)
}
basic(data1)
screen(1, new=FALSE)
text(x=c(1.5,1.6,1.7),y=c(2,2.1,2.2), labels=c("X","Y","Z"))
Upvotes: 2
Reputation: 15441
You could outline what the different texts are first e.g.
data1<-1:3
text1 <- data.frame(x=c(1.5,1.6,1.7),y=c(2,2.1,2.2), labels=c("X","Y","Z"))
text2 <- data.frame(x=c(2,2.9,1.0),y=c(2,2.1,2.2), labels=c("X","Y","Z"))
then put them in your function
basic<-function(data1){
par(mfrow=c(2,1))
plot(data1)
text(text1)
plot(data1)
text(text2)
}
basic(data1)
As @Andrie says calling plot means any further text()
calls will work on the last plot only
Upvotes: 1