【问题标题】:How to move y-axis labels away from R plot using lapply in R如何使用 R 中的 lapply 将 y 轴标签从 R 图中移开
【发布时间】:2020-03-22 22:38:39
【问题描述】:

我有以下代码(感谢@Rawr 在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)
})

这会产生以下情节:

明显的问题是 y 轴标签与 y 轴值重叠。我尝试过使用mar()oma(),但这些只是改变了周围的边距,我希望这能把事情排除在外。如何将 y 轴标签与绘图分开移动?我还将稍微移动边距,以便两列图之间的空白更靠近。

【问题讨论】:

  • 地块之间的列中似乎有更多空间。试试c("", "P(LNG)","","Volume(LNG)","","P(oil)","","Can.GDP","","US GDP")
  • 另一种选择是重新缩放 y 轴上的变量,使它们落在一个不错的范围内(例如 0-20),然后在标签中添加适当的单位.例如,将美国 GDP 除以 1,000,000,然后标签将是“美国 GDP (x1,000,000)”。 y 轴刻度标签将是 1.0, 1.2, 1.4, 1.6, 1.8, 2.0
  • 另一个选项是使用layout 函数,它允许更多地控制多面板绘图的绘图尺寸。与par(mar=...) 不同,您可以通过更复杂的方式改变边距。

标签: r plot lapply


【解决方案1】:

您可以单独定义 ylab,就像您为 xlab 所做的那样,并设置 line 参数以定义其与绘图的距离 (as stated in this post)。

我通过结合您的代码和您之前问题中的@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)
})

上面的代码为line = 4 输出以下图表:

line = 3 的这个情节:

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多