我需要以相同的格式制作几个时间序列图,如图所示。我对格式本身感兴趣。
我会很感激你的帮助。
这是一个带有模拟数据的最小示例
set.seed(1234)
nobs<-50
x<-rnorm(nobs,0,10)
t<-seq(1,nobs)
data<-ts(20+x+t, freq=4, start=c(2004,1))
par(family="serif")
plot(data, lwd=2, col="blue4", ylab="Millions")
title(main="Gráfico 1. Evolución del ...")
legend(2010,10,"GDP", col="blue4",lwd=2)
abline(lm(data~t), lwd=2, col="red") # This does not work
最佳答案
我假设您的数据是 ts
对象,如您的示例所示。这是使用 base
图形的方法。我们从一个最小的情节开始,然后在元素上分层。首先,最小图,确保在第 1 侧(即底部)留出大量空间:
par(mar = c(8, 4, 4, 2), family = "serif", las = 1)
plot(data,
frame = FALSE,
xaxt = "n",
ylab = "Millones de pesos", xlab = "",
main = "Gráfico 1. Evolución del ...",
col = "darkblue", lwd = 2)
fit <- forecast::tslm(data ~ trend)
lines(fitted(fit), col = "red", lwd = 2)
请注意,上面我们使用
forecast::tslm
来获取时间序列的时间趋势。现在,添加 x 轴元素。我使用 mtext
插入刻度标签:axis(1, at = seq(2003.875, 2015.875, 1), tck = -.2, labels = FALSE)
mtext(rep(c("ener-mar", "abril-jun", "jul-sep", "oct-dic"), l = length(data)),
side = 1, line = 0.25, las = 2,
at = seq(tsp(data)[1], tsp(data)[2], by = 1/tsp(data)[3]),
cex = .6)
mtext(2004:2016, side = 1, line = 3, at = seq(2004.3, 2016.3), cex = .7)
title(xlab = "Trimestres", line = 5, cex.lab = .8)
用传奇结束:
par(xpd = TRUE)
legend(2010, -27, c("PIB", "Tendencia PIB"),
bty = "n",
xjust = .5,
lty = c(1, 1),
col = c("darkblue", "red"),
cex = .7,
horiz = TRUE)
输出:
关于r - 如何用 R 复制这个图?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39563916/