如何使用R绘制带有自定义标题的两列时间序列网格? [英] How to plot a two-columned grid of time series with custom titles using R?

查看:60
本文介绍了如何使用R绘制带有自定义标题的两列时间序列网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(可悲的是,虽然没有数据):

I have the following code (although without data, sadly):

detrend_plot <- cbind(l_p_lng,l_vol_lng,l_p_oil,l_rgdpe, ldiff_p_lng,ldiff_vol_lng,ldiff_p_oil,ldiff_rgdpe)

plot.ts(detrend_plot, main="",)

给出以下图:

我要做的是添加自定义标题,单个y轴标签和x轴标签.我知道使用 GGPLOT 可以做到这一点,尽管我对此知之甚少.有没有人遇到过类似的问题?我认为使用常规的 plot.ts()函数是不可能的.

What I want to do is to add custom titles, individual y-axis labels, and x-axis labels. I know that this is possible using GGPLOT, although my knowledge of it is sparse. Has anyone encountered a similar problem? I don't think this is possible using the regular plot.ts( ) function.

推荐答案

我认为您不能直接将多个标题和标签传递给 plot.ts ,但是您可以循环遍历您的列带有每个标签的向量:

I don't think you can pass multiple titles and labels to plot.ts directly, but you can just loop over your columns with vectors of labels for each:

set.seed(1)
z <- ts(matrix(rt(200 * 8, df = 3), 200, 8), start = c(1961, 1), frequency = 12)

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

par(mfrow = c(4, 2), mar = c(5, 5, 1, 1), oma = c(0, 0, 1, 2))
lapply(1:8, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = xl[ii], ylab = yl[ii], main = ml[ii])
})

您还可以使用列表传递参数向量(例如,用于x轴或y轴限制):

You can also pass vectors of arguments (eg, for x- or y-axis limits) using lists:

ylim <- list(c(-10, 10))
ylim <- rep(ylim, 8)

par(mfrow = c(4, 2), mar = c(5, 5, 1, 1), oma = c(0, 0, 1, 2))
lapply(1:8, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = xl[ii], ylab = yl[ii], main = ml[ii], col = ii, ylim = ylim[[ii]])
})

要使图形更接近默认的 plot.ts 外观,您只需将顶部和底部边距设置为0并调整轴(这就是 plot.ts >正在幕后进行).该方法比 plot.ts 更为冗长,但可以进行更多的自定义:

To get a figure closer to the default plot.ts look, you can just set top and bottom margins to 0 and adjust the axes (which is what plot.ts is doing under the hood). This method is a bit more verbose than plot.ts but will allow for more customization:

par(mfrow = c(4, 2), mar = c(0, 5, 0, 1), oma = c(5, 0, 3, 2))
lapply(1:8, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = xl[ii], ylab = yl[ii], col = ii, axes = FALSE)
  axis(2, las = 1)
  box()
  if (ii %in% 7:8) {
    axis(1)
    title(xlab = 'Year', xpd = NA)
  }
  if (ii %in% 1:2)
    title(main = c('Group 1', 'Group 2')[ii], xpd = NA, line = 1)
})

这篇关于如何使用R绘制带有自定义标题的两列时间序列网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆