简体   繁体   中英

How to move y-axis labels away from R plot using lapply in R

I have the following code (Thanks to an answer from @Rawr in this question ):

labes1 <- c("P(LNG)","","Volume(LNG)","","P(oil)","","Can.GDP","","US GDP","")
titles <- c("Levels","","","","","Log Difference","","","","")

par(mfrow = c(5, 2), mar = c(0.3, 6, 0, 2), oma = c(5, 0, 3, 2))
lapply(1:10, function(ii) {
  x <- plotdata1[, ii, drop = FALSE]
  plot(x, xlab = "Quarter", ylab = labes1[ii], axes = FALSE)
  axis(2, las = 1)
  box()
  if (ii %in% 9:10) {
    axis(1)
    title(xlab = 'Quarter', xpd = NA)
  }
  if (ii %in% 1:2)
    title(main = c('Levels', 'Log Difference')[ii], xpd = NA, line = 1)
})

This produces the following plot:

在此处输入图片说明

The obvious issue is the overlaying of the y-axis labels with the y-axis values. I have tried playing around with the mar() and oma() but these just change the margins around, I was hoping this would move things out of the way. How can I move the y-axis labels as separate from the plot? I will also be moving the margins a bit so that the white space between the two columns of plots will be closer together.

You can define the ylab separately, like what you're doing for the xlab, and set the line parameter to define its distance from the plot ( as stated in this post ).

I got a running example from combining your code and @rawr's from your previous question.

set.seed(1)
z <- ts(matrix(rt(200 * 10, df = 3), 200, 10), start = c(1961, 1), frequency = 12) 
z <- z * 1e5 # to make "wide" y-axis labels

## vectors of x, y, and main labels
xl <- sprintf('x label %s', 1:10)
yl <- sprintf('y label %s', 1:10)
ml <- sprintf('main label %s', 1:10)


labes1 <- c("P(LNG)","","Volume(LNG)","","P(oil)","","Can.GDP","","US GDP","")
titles <- c("Levels","","","","","Log Difference","","","","")

par(mfrow = c(5, 2), mar = c(0.3, 6, 0, 2), oma = c(5, 0, 3, 2))
lapply(1:10, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = "Quarter", ylab = "", axes = FALSE) # set ylab to ""
  axis(2, las = 1)
  title(ylab = labes1[ii], line = 4) # set the line at an appropriate distance 
  box()
  if (ii %in% 9:10) {
    axis(1)
    title(xlab = 'Quarter', xpd = NA)
  }
  if (ii %in% 1:2)
    title(main = c('Levels', 'Log Difference')[ii], xpd = NA, line = 1)
})

The code above outputs the following graph for line = 4 :

在此处输入图片说明

and this plot for line = 3 :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM