khajlk
khajlk

Reputation: 851

Creating subplots using R base

This link shows good examples of creating side-by-side plots using several packages. However, I would like to create a (4 x 1) plot in R using base functions only.

Here is what I have tried:

par(mar=c(0.2, 0.2, 0.7, 0.7), mfrow=c(4,1), oma = c(4, 4, 0.2, 0.2))
# Plot 1
plot(my_data$date, my_data$col1, type="l", col = "red", ylab = expression("my_legend"^{-5}), xlab = "", xaxt="nan", lwd = 1)
lines(my_data$date, my_data$col2, type="l", col = "blue", lwd = 1)
legend(14, 20, legend=c("Line 1", "Line 2"), col=c("red", "blue"), lty=1:2, cex=0.8)
# Plot 2
plot(my_data$date, my_data$col3, type="l", col = "magenta",xlab = "", xaxt = "nan", ylab = expression("my_legend"^{2}))
lines(my_data$date, my_data$col4, type="l", col = "green")
legend(14, 20, legend=c("Line 3", "Line 5"), col=c("orange", "yellow"), lty=1:2, cex=0.8)
# Plot 3
plot(my_data$date, my_data$col5, type="l", col = "olivedrab2",xlab = "", xaxt = "nan", ylab = expression("my_legend"^{8}))
# Plot 4
plot(my_data$date, my_data$col6, type="l", col = "sandybrown", xlab = "Time (3 May 1994)", ylab = expression("my_legend"^{7}))

I want y-axes titles (all four plots) and a common x-axis title (plot 4). That is, y-axis title (here, plot 1) is not displayed, neither x-axis title (plot 4) and legends (inside plot 1) are shown. Could someone help me to understand why?

Upvotes: 1

Views: 2300

Answers (1)

Michael Tuchman
Michael Tuchman

Reputation: 352

You might find this link useful.

https://stevencarlislewalker.wordpress.com/2012/06/28/overall-axis-labels-with-mfrow/

I'll copy the code here in case the link dies, but you should read his post. As of 2019 it was still available. Idea is to plot without axes using xaxt='n' and yaxt='n' then use mtext to label the 'overall' axes by annotating the margins of the plot.

I still think ggplot offers you more capability, perhaps your company doesn't allow you to install it?

# thanks to 
# https://stevencarlislewalker.wordpress.com/2012/06/28/overall-axis-labels-with-mfrow/
par(mfrow = c(2, 2)) # 2-by-2 grid of plots
par(oma = c(4, 4, 0, 0)) # make room (i.e. the 4's) for the overall x and y axis titles
par(mar = c(2, 2, 1, 1)) # make the plots be closer together

# now plot the graphs with the appropriate axes removed (via xaxt and yaxt),
# remove axis labels (so that they are not redundant with overall labels,
# and set some other nice choices for graphics parameters
plot(runif(10), xlab = '', ylab = '', xaxt = 'n', las = 1, ylim = c(0, 1))
plot(runif(10), xlab = '', ylab = '', xaxt = 'n', yaxt = 'n', ylim = c(0, 1))
plot(runif(10), xlab = '', ylab = '', las = 1, ylim = c(0, 1))
plot(runif(10), xlab = '', ylab = '', yaxt = 'n', ylim = c(0, 1))

# print the overall labels
mtext('x-axis title', side = 1, outer = TRUE, line = 2)
mtext('y-axis title', side = 2, outer = TRUE, line = 2)

Upvotes: 1

Related Questions