简体   繁体   English

如何使用 R 中的 lapply 将 y 轴标签从 R 图中移开

[英]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 ):我有以下代码(感谢@Rawr 在这个问题中的回答):

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.明显的问题是 y 轴标签与 y 轴值的重叠。 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.我曾尝试使用mar()oma()但这些只是改变了周围的边距,我希望这能将事情移开。 How can I move the y-axis labels as separate from the plot?如何将 y 轴标签与绘图分开移动? 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 ).您可以单独定义 ylab,就像您对 xlab 所做的一样,并设置line参数以定义它与绘图的距离(如本文所述)。

I got a running example from combining your code and @rawr's from your previous question.我通过结合您的代码和您上一个问题中的@rawr 得到了一个运行示例。

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 :上面的代码为line = 4输出了下图:

在此处输入图片说明

and this plot for line = 3 :line = 3情节:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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