簡體   English   中英

如何使用 R 中的 lapply 將 y 軸標簽從 R 圖中移開

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

我有以下代碼(感謝@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)
})

這會產生以下圖:

在此處輸入圖片說明

明顯的問題是 y 軸標簽與 y 軸值的重疊。 我曾嘗試使用mar()oma()但這些只是改變了周圍的邊距,我希望這能將事情移開。 如何將 y 軸標簽與繪圖分開移動? 我還將稍微移動邊距,以便兩列圖之間的空白區域會更靠近。

您可以單獨定義 ylab,就像您對 xlab 所做的一樣,並設置line參數以定義它與繪圖的距離(如本文所述)。

我通過結合您的代碼和您上一個問題中的@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情節:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM